Programs & Examples On #Ascx

The ascx is used to create or define custom usercontrols to be placed onto web pages.

Calling another different view from the controller using ASP.NET MVC 4

You can directly return a different view like:

return View("NameOfView", Model);

Or you can make a partial view and can return like:

return PartialView("PartialViewName", Model);

The view or its master was not found or no view engine supports the searched locations

Check the build action of your view (.cshtml file) It should be set to content. In some cases, I have seen that the build action was set to None (by mistake) and this particular view was not deploy on the target machine even though you see that view present in visual studio project file under valid folder

jquery toggle slide from left to right and back

See this: Demo

$('#cat_icon,.panel_title').click(function () {
   $('#categories,#cat_icon').stop().slideToggle('slow');
});

Update : To slide from left to right: Demo2

Note: Second one uses jquery-ui also

Why is access to the path denied?

I had this error thrown when I tried to rename a folder very rapidly after it had been either moved or created.

A simple System.Threading.Thread.Sleep(500); solved it:

void RenameFile(string from, string to)
{
   try
   {   
      System.IO.File.Move(from, to)      
   }   
   catch 
   {  
       System.Threading.Thread.Sleep(500);      
       RenameFile(from, to);      
   }   
}

How to make script execution wait until jquery is loaded

A tangential note on the approaches here that load use setTimeout or setInterval. In those cases it's possible that when your check runs again, the DOM will already have loaded, and the browser's DOMContentLoaded event will have been fired, so you can't detect that event reliably using these approaches. What I found is that jQuery's ready still works, though, so you can embed your usual

jQuery(document).ready(function ($) { ... }

inside your setTimeout or setInterval and everything should work as normal.

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

GetFiles can only match a single pattern, but you can use Linq to invoke GetFiles with multiple patterns:

FileInfo[] fi = new string[]{"*.txt","*.doc"}
    .SelectMany(i => di.GetFiles(i, SearchOption.AllDirectories))
    .ToArray();

See comments section here: http://www.codeproject.com/KB/aspnet/NET_DirectoryInfo.aspx

when do you need .ascx files and how would you use them?

ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs". You can embed it in a ASP page to use it:

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

You could also use the RenderView Controller extension from here (source)

and use it like this:

public ActionResult Do() {
var html = this.RenderView("index", theModel);
...
}

it works for razor and web-forms viewengines

Copy files without overwrite

Belisarius' solution is good.

To elaborate on that slightly terse answer:

  • /E makes Robocopy recursively copy subdirectories, including empty ones.
  • /XC excludes existing files with the same timestamp, but different file sizes. Robocopy normally overwrites those.
  • /XN excludes existing files newer than the copy in the source directory. Robocopy normally overwrites those.
  • /XO excludes existing files older than the copy in the source directory. Robocopy normally overwrites those.

With the Changed, Older, and Newer classes excluded, Robocopy does exactly what the original poster wants - without needing to load a scripting environment.

Html attributes for EditorFor() in ASP.NET MVC

Just create your own template for the type in Views/Shared/EditorTemplates/MyTypeEditor.vbhtml

@ModelType MyType

@ModelType MyType
@Code
    Dim name As String = ViewData("ControlId")
    If String.IsNullOrEmpty(name) Then
        name = "MyTypeEditor"
    End If
End Code

' Mark-up for MyType Editor
@Html.TextBox(name, Model, New With {.style = "width:65px;background-color:yellow"})

Invoke editor from your view with the model property:

@Html.EditorFor(Function(m) m.MyTypeProperty, "MyTypeEditor", New {.ControlId = "uniqueId"})

Pardon the VB syntax. That's just how we roll.

How to convert View Model into JSON object in ASP.NET MVC?

Extending the great answer from Dave. You can create a simple HtmlHelper.

public static IHtmlString RenderAsJson(this HtmlHelper helper, object model)
{
    return helper.Raw(Json.Encode(model));
}

And in your view:

@Html.RenderAsJson(Model)

This way you can centralize the logic for creating the JSON if you, for some reason, would like to change the logic later.

The view 'Index' or its master was not found.

Check the generated code at MyAreaAreaRegistration.cs and make sure that the controller parameter is set to your default controller, otherwise the controller will be called bot for some reason ASP.NET MVC won't search for the views at the area folder

public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "SomeArea_default",
            "SomeArea/{controller}/{action}/{id}",
            new { controller = "SomeController", action = "Index", id = UrlParameter.Optional }
        );
    }

Can I set up HTML/Email Templates with ASP.NET?

I like Raj's answer. Programs like ListManager & frameworks like DNN do similar things, and if easy editing by non-technical users is required, WYSIWYG editors to modify HTML stored in SQL is a mostly easy, straightforward way to go and can easily accommodate editing headers independently from footers, etc, as well as using tokens to dynamically insert values.

One thing to keep in mind if using the above method (or any, really) is to be strict and careful about which types of styling and tags you allow the editors to insert. If you think browsers are finicky, just wait until you see how differently email clients render the same thing...

How to make sure you don't get WCF Faulted state exception?

This error can also be caused by having zero methods tagged with the OperationContract attribute. This was my problem when building a new service and testing it a long the way.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

in solution explorer just right click and select convert to web application. It will generate all the designer files again.

Web API Put Request generates an Http 405 Method Not Allowed error

Decorating one of the action params with [FromBody] solved the issue for me:

public async Task<IHttpActionResult> SetAmountOnEntry(string id, [FromBody]int amount)

However ASP.NET would infer it correctly if complex object was used in the method parameter:

public async Task<IHttpActionResult> UpdateEntry(string id, MyEntry entry)

Prevent a webpage from navigating away using JavaScript

That suggested error message may duplicate the error message the browser already displays. In chrome, the 2 similar error messages are displayed one after another in the same window.

In chrome, the text displayed after the custom message is: "Are you sure you want to leave this page?". In firefox, it does not display our custom error message at all (but still displays the dialog).

A more appropriate error message might be:

window.onbeforeunload = function() {
    return "If you leave this page, you will lose any unsaved changes.";
}

Or stackoverflow style: "You have started writing or editing a post."

Error: macro names must be identifiers using #ifdef 0

Use the following to evaluate an expression (constant 0 evaluates to false).

#if 0
 ...
#endif

How to specify a local file within html using the file: scheme?

For apache look up SymLink or you can solve via the OS with Symbolic Links or on linux set up a library link/etc

My answer is one method specifically to windows 10.

So my method involves mapping a network drive to U:/ (e.g. I use G:/ for Google Drive)

open cmd and type hostname (example result: LAPTOP-G666P000, you could use your ip instead, but using a static hostname for identifying yourself makes more sense if your network stops)

Press Windows_key + E > right click 'This PC' > press N (It's Map Network drive, NOT add a network location)

If you are right clicking the shortcut on the desktop you need to press N then enter

Fill out U: or G: or Z: or whatever you want Example Address: \\LAPTOP-G666P000\c$\Users\username\

Then you can use <a href="file:///u:/2ndFile.html"><button type="submit">Local file</button> like in your question


related: You can also use this method for FTPs, and setup multiple drives for different relative paths on that same network.

related2: I have used http://localhost/c$ etc before on some WAMP/apache servers too before, you can use .htaccess for control/security but I recommend to not do so on a live/production machine -- or any other symlink documentroot example you can google

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

There is no need to use an ObjectIndexer<T>, or change the interface of the original object (like suggested in most of the other answers). You can simply narrow the options for key to the ones that are of type string using the following:

type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];

This great solution comes from an answer to a related question here.

Like that you narrow to keys inside T that hold V values. So in your case to to limit to string you would do:

type KeysMatching<ISomeObject, string>;

In your example:

interface ISomeObject {
    firstKey:   string;
    secondKey:  string;
    thirdKey:   string;
}

let someObject: ISomeObject = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   'thirdValue'
};

let key: KeysMatching<SomeObject, string> = 'secondKey';

// secondValue narrowed to string    
let secondValue = someObject[key];

The advantage is that your ISomeObject could now even hold mixed types, and you can anyway narrow the key to string values only, keys of other value types will be considered invalid. To illustrate:

interface ISomeObject {
    firstKey:   string;
    secondKey:  string;
    thirdKey:   string;
    fourthKey:  boolean;
}

let someObject: ISomeObject = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   'thirdValue'
    fourthKey:   true
};


// Type '"fourthKey"' is not assignable to type 'KeysMatching<ISomeObject, string>'.(2322)
let otherKey: KeysMatching<SomeOtherObject, string> = 'fourthKey';

let fourthValue = someOtherObject[otherKey];

You find this example in this playground.

Trim a string in C

void inPlaceStrTrim(char* str) {
    int k = 0;
    int i = 0;
    for (i=0; str[i] != '\0';) {
        if (isspace(str[i])) {
            // we have got a space...
            k = i;
            for (int j=i; j<strlen(str)-1; j++) {
                str[j] = str[j+1];
            }
            str[strlen(str)-1] = '\0';
            i = k; // start the loop again where we ended..
        } else {
            i++;
        }
    }
}

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

If you really don't care about props then the widest possible type is React.ReactType.

This would allow passing native dom elements as string. React.ReactType covers all of these:

renderGreeting('button');
renderGreeting(() => 'Hello, World!');
renderGreeting(class Foo extends React.Component {
   render() {
      return 'Hello, World!'
   }
});

What is "git remote add ..." and "git push origin master"?

Update: note that the currently accepted answer perpetuates a common misunderstanding about the behaviour of git push, which hasn't been corrected despite a comment pointing it out.

Your summary of what remotes are - like a nickname for the URL of a repository - is correct.

So why does the URL not git://[email protected]/peter/first_app.git but in the other syntax -- what syntax is it? Why must it end with .git? I tried not using .git at the end and it works too. If not .git, what else can it be? The git at the beginner seems to be a user account on the git server?

The two URLs that you've mentioned indicate that two different transport protocols should be used. The one beginning with git:// is for the git protocol, which is usually only used for read-only access to repositories. The other one, [email protected]:peter/first_app.git, is one of the different ways of specifying access to a repository over SSH - this is the "scp-style syntax" described in the documentation. That the username in the scp-style syntax is git is because of the way that GitHub deals with identifying users - essentially that username is ignored, and the user is identified based on the SSH key-pair that they used to authenticate.

As for the verbosity of git push origin master, you've noticed that after the first push, you can then just do git push. This is because of a series of difficult-to-remember-but-generally-helpful defaults :)

  • If no remote is specified, the remote configured for the current branch (in remote.master.url in your case) is used. If that's not set up, then origin is used.
  • If there's no "refspec" (e.g. master, master:my-experiment, etc.) specified, then git defaults to pushing every local branch that has the same name as a branch on the remote. If you just have a branch called master in common between your repository and the remote one, that'll be the same as pushing your master to the remote master.

Personally, since I tend to have many topic branches (and often several remotes) I always use the form:

git push origin master

... to avoid accidentally pushing other branches.


In reply to your comments on one of the other answers, it sounds to me as if are learning about git in a top-down way very effectively - you've discovered that the defaults work, and your question is asking about why ;) To be more serious, git can be used essentially as simply as SVN, but knowing a bit about remotes and branches means you can use it much more flexibily and this can really change the way you work for the better. Your remark about a semester course makes me think of something Scott Chacon said in a podcast interview - students are taught about all kinds of basic tools in computer science and software engineering, but very rarely version control. Distributed version control systems such as git and Mercurial are now so important, and so flexible, that it would be worth teaching courses on them to give people a good grounding.

My view is that with git, this learning curve is absolutely worth it - working with lots of topic branches, merging them easily, and pushing and pulling them about between different repositories is fantastically useful once you become confident with the system. It's just unfortunate that:

  • The primary documentation for git is so hard to parse for newcomers. (Although I'd argue that if you Google for almost any git question, helpful tutorial material (or Stack Overflow answers :)) come up nowadays.)
  • There are a few odd behaviours in git that are hard to change now because many scripts may rely on them, but are confusing to people.

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

Strip out HTML and Special Characters

preg_replace('/[^a-zA-Z0-9\s]/', '',$string) this is using for removing special character only rather than space between the strings.

How to determine whether a substring is in a different string

def find_substring():
    s = 'bobobnnnnbobmmmbosssbob'
    cnt = 0
    for i in range(len(s)):
        if s[i:i+3] == 'bob':
            cnt += 1
    print 'bob found: ' + str(cnt)
    return cnt

def main():
    print(find_substring())

main()

nullable object must have a value

In this case oldDTE is null, so when you try to access oldDTE.Value the InvalidOperationException is thrown since there is no value. In your example you can simply do:

this.MyDateTime = newDT.MyDateTime;

VBA check if file exists

I'll throw this out there and then duck. The usual reason to check if a file exists is to avoid an error when attempting to open it. How about using the error handler to deal with that:

Function openFileTest(filePathName As String, ByRef wkBook As Workbook, _
                      errorHandlingMethod As Long) As Boolean
'Returns True if filePathName is successfully opened,
'        False otherwise.
   Dim errorNum As Long

'***************************************************************************
'  Open the file or determine that it doesn't exist.
   On Error Resume Next:
   Set wkBook = Workbooks.Open(fileName:=filePathName)
   If Err.Number <> 0 Then
      errorNum = Err.Number
      'Error while attempting to open the file. Maybe it doesn't exist?
      If Err.Number = 1004 Then
'***************************************************************************
      'File doesn't exist.
         'Better clear the error and point to the error handler before moving on.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         '[Clever code here to cope with non-existant file]
         '...
         'If the problem could not be resolved, invoke the error handler.
         Err.Raise errorNum
      Else
         'No idea what the error is, but it's not due to a non-existant file
         'Invoke the error handler.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         Err.Raise errorNum
      End If
   End If

   'Either the file was successfully opened or the problem was resolved.
   openFileTest = True
   Exit Function

OPENFILETEST_FAIL:
   errorNum = Err.Number
   'Presumabley the problem is not a non-existant file, so it's
   'some other error. Not sure what this would be, so...
   If errorHandlingMethod < 2 Then
      'The easy out is to clear the error, reset to the default error handler,
      'and raise the error number again.
      'This will immediately cause the code to terminate with VBA's standard
      'run time error Message box:
      errorNum = Err.Number
      Err.Clear
      On Error GoTo 0
      Err.Raise errorNum
      Exit Function

   ElseIf errorHandlingMethod = 2 Then
      'Easier debugging, generate a more informative message box, then terminate:
      MsgBox "" _
           & "Error while opening workbook." _
           & "PathName: " & filePathName & vbCrLf _
           & "Error " & errorNum & ": " & Err.Description & vbCrLf _
           , vbExclamation _
           , "Failure in function OpenFile(), IO Module"
      End

   Else
      'The calling function is ok with a false result. That is the point
      'of returning a boolean, after all.
      openFileTest = False
      Exit Function
   End If

End Function 'openFileTest()

How to get file's last modified date on Windows command line?

What output (exactly) does dir myfile.txt give in the current directory? What happens if you set the delimiters?

FOR /f "tokens=1,2* delims= " %%a in ('dir myfile.txt^|find /i " myfile.txt"') DO SET fileDate=%%a 

(note the space after delims=)
(to make life easier, you can do this from the command line by replacing %%a with %a)

How to send email to multiple recipients using python smtplib?

This really works, I spent a lot of time trying multiple variants.

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = '[email protected]'
recipients = ['[email protected]', '[email protected]']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

Simplest way to wait some asynchronous tasks complete, in Javascript?

Use Promises.

var mongoose = require('mongoose');

mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;

var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
  return new Promise(function(resolve, reject) {
    var collection = conn.collection(name);
    collection.drop(function(err) {
      if (err) { return reject(err); }
      console.log('dropped ' + name);
      resolve();
    });
  });
});

Promise.all(promises)
.then(function() { console.log('all dropped)'); })
.catch(console.error);

This drops each collection, printing “dropped” after each one, and then prints “all dropped” when complete. If an error occurs, it is displayed to stderr.


Previous answer (this pre-dates Node’s native support for Promises):

Use Q promises or Bluebird promises.

With Q:

var Q = require('q');
var mongoose = require('mongoose');

mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;

var promises = ['aaa','bbb','ccc'].map(function(name){
    var collection = conn.collection(name);
    return Q.ninvoke(collection, 'drop')
      .then(function() { console.log('dropped ' + name); });
});

Q.all(promises)
.then(function() { console.log('all dropped'); })
.fail(console.error);

With Bluebird:

var Promise = require('bluebird');
var mongoose = Promise.promisifyAll(require('mongoose'));

mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;

var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
  return conn.collection(name).dropAsync().then(function() {
    console.log('dropped ' + name);
  });
});

Promise.all(promises)
.then(function() { console.log('all dropped'); })
.error(console.error);

SHA1 vs md5 vs SHA256: which to use for a PHP login?

As Johannes Gorset pointed out, the post by Thomas Ptacek from Matasano Security explains why simple, general-purpose hashing functions such as MD5, SHA1, SHA256 and SHA512 are poor password hashing choices.

Why? They are too fast--you can calculate at least 1,000,000 MD5 hashes a second per core with a modern computer, so brute force is feasible against most passwords people use. And that's much less than a GPU-based cracking server cluster!

Salting without key stretching only means that you cannot precompute the rainbow table, you need to build it ad hoc for that specific salt. But it won't really make things that much harder.

User @Will says:

Everyone is talking about this like they can be hacked over the internet. As already stated, limiting attempts makes it impossible to crack a password over the Internet and has nothing to do with the hash.

They don't need to. Apparently, in the case of LinkedIn they used the common SQL injection vulnerability to get the login DB table and cracked millions of passwords offline.

Then he goes back to the offline attack scenario:

The security really comes into play when the entire database is compromised and a hacker can then perform 100 million password attempts per second against the md5 hash. SHA512 is about 10,000 times slower.

No, SHA512 is not 10000 times slower than MD5--it only takes about twice as much. Crypt/SHA512, on the other hand, is a very different beast that, like its BCrypt counterpart, performs key stretching, producing a very different hash with a random salt built-in and will take anything between 500 and 999999 times as much to compute (stretching is tunable).

SHA512 => aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
Crypt/SHA512 => $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21

So the choice for PHP is either Crypt/Blowfish (BCrypt), Crypt/SHA256 or Crypt/SHA512. Or at least Crypt/MD5 (PHK). See www.php.net/manual/en/function.crypt.php

What is the difference between --save and --save-dev?

A perfect example of this is:

$ npm install typescript --save-dev

In this case, you'd want to have Typescript (a javascript-parseable coding language) available for development, but once the app is deployed, it is no longer necessary, as all of the code has been transpiled to javascript. As such, it would make no sense to include it in the published app. Indeed, it would only take up space and increase download times.

How to determine if a point is in a 2D triangle?

There are pesky edge conditions where a point is exactly on the common edge of two adjacent triangles. The point cannot be in both, or neither of the triangles. You need an arbitrary but consistent way of assigning the point. For example, draw a horizontal line through the point. If the line intersects with the other side of the triangle on the right, the point is treated as though it is inside the triangle. If the intersection is on the left, the point is outside.

If the line on which the point lies is horizontal, use above/below.

If the point is on the common vertex of multiple triangles, use the triangle with whose center the point forms the smallest angle.

More fun: three points can be in a straight line (zero degrees), for example (0,0) - (0,10) - (0,5). In a triangulating algorithm, the "ear" (0,10) must be lopped off, the "triangle" generated being the degenerate case of a straight line.

What is the Python equivalent for a case/switch statement?

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

For div to extend full height

if setting height to 100% doesn't work, try min-height=100% for div. You still have to set the html tag.

html {
    height: 100%;
    margin: 0px;
    padding: 0px;
    position: relative;
}

#fullHeight{

    width: 450px;
    **min-height: 100%;**
    background-color: blue;

}

Stop an input field in a form from being submitted

_x000D_
_x000D_
$('#serialize').click(function () {_x000D_
  $('#out').text(_x000D_
    $('form').serialize()_x000D_
  );_x000D_
});_x000D_
_x000D_
$('#exclude').change(function () {_x000D_
  if ($(this).is(':checked')) {_x000D_
    $('[name=age]').attr('form', 'fake-form-id');_x000D_
  } else {_x000D_
    $('[name=age]').removeAttr('form');    _x000D_
  }_x000D_
  _x000D_
  $('#serialize').click();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="/">_x000D_
  <input type="text" value="John" name="name">_x000D_
  <input type="number" value="100" name="age">_x000D_
</form>_x000D_
_x000D_
<input type="button" value="serialize" id="serialize">_x000D_
<label for="exclude">  _x000D_
  <input type="checkbox" value="exclude age" id="exclude">_x000D_
  exlude age_x000D_
</label>_x000D_
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Simple Android RecyclerView example

To get started , just to view something in Recycler view

recycler view adapter can be something like this.

class CustomAdapter: RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
    var data =  listOf<String>()
        set(value) {
            field = value
            notifyDataSetChanged()
        }
    override fun getItemCount() =data.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.txt.text= data[position]
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_view, parent, false)
        )
    }


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val txt: TextView = itemView.findViewById(R.id.item_text_view)
    }
}

and to attach the adapter to the recycler view and to attach data to adapter

val view = findViewById<RecyclerView>(R.id.recycler_view)                                              
val adapter = CustomAdapter()                                                                          
val data = listOf("text1", "text2", "text3")
adapter.data = data                                                                             
view.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
view.adapter = adapter       
            

String contains another two strings

So you want to know if one string contains two other strings?

You could use this extension which also allows to specify the comparison:

public static bool ContainsAll(this string text, StringComparison comparison = StringComparison.CurrentCulture, params string[]parts)
{
    return parts.All(p => text.IndexOf(p, comparison) > -1);
}

Use it in this way (you can also omit the StringComparison):

bool containsAll = d.ContainsAll(StringComparison.OrdinalIgnoreCase, a, b);

Test if object implements interface

Recently I tried using Andrew Kennan's answer and it didn't work for me for some reason. I used this instead and it worked (note: writing the namespace might be required).

if (typeof(someObject).GetInterface("MyNamespace.IMyInterface") != null)

How to search for a string inside an array of strings

In-case if someone wants a little dynamic search.

 let searchInArray=(searchQuery, array, objectKey=null)=>{

  return array.filter(d=>{
      let data =objectKey? d[objectKey] : d //Incase If It's Array Of Objects.
       let dataWords= typeof data=="string" && data?.split(" ")?.map(b=>b&&b.toLowerCase().trim()).filter(b=>b)
      let searchWords = typeof searchQuery=="string"&&searchQuery?.split(" ").map(b=>b&&b.toLowerCase().trim()).filter(b=>b)

     let matchingWords = searchWords.filter(word=>dataWords.includes(word))

    return matchingWords.length

})
    
    
}

For an Array of strings:

let arrayOfStr = [
  "Search for words",
  "inside an array",
  "dynamic searching",
  "match rate 90%"
]

searchInArray("dynamic search", arrayOfStr)

//Results: [ "Search for words", "dynamic searching" ]

For an Array of Objects:

let arrayOfObject = [
  {
    "address": "Karachi Pakistan"
  },
  {
    "address": "UK London"
  },
  {
    "address": "Pakistan Lahore"
  }
]

searchInArray("Pakistan", arrayOfObject,"address")

//Results: [ { "address": "Karachi Pakistan" }, { "address": "Pakistan Lahore" } ]

How to kill a child process by the parent process?

Send a SIGTERM or a SIGKILL to it:

http://en.wikipedia.org/wiki/SIGKILL

http://en.wikipedia.org/wiki/SIGTERM

SIGTERM is polite and lets the process clean up before it goes, whereas, SIGKILL is for when it won't listen >:)

Example from the shell (man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?kill )

kill -9 pid

In C, you can do the same thing using the kill syscall:

kill(pid, SIGKILL);

See the following man page: http://linux.die.net/man/2/kill

Joining 2 SQL SELECT result sets into one

Use a FULL OUTER JOIN:

select 
   a.col_a,
   a.col_b,
   b.col_c
from
   (select col_a,col_bfrom tab1) a
join 
   (select col_a,col_cfrom tab2) b 
on a.col_a= b.col_a

CryptographicException 'Keyset does not exist', but only through WCF

This issue is got resolved after adding network service role.

CERTIFICATE ISSUES 
Error :Keyset does not exist means System might not have access to private key
Error :Enveloped data … 
Step 1:Install certificate in local machine not in current user store
Step 2:Run certificate manager
Step 3:Find your certificate in the local machine tab and right click manage privatekey and check in allowed personnel following have been added:
a>Administrators
b>yourself
c>'Network service'
And then provide respective permissions.

## You need to add 'Network Service' and then it will start working.

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Upgrade to phpMyAdmin 4.8.3. this solves the PHP 7.2 compatibility issues

Mocking python function based on input arguments

I've ended up here looking for "how to mock a function based on input arguments" and I finally solved this creating a simple aux function:

def mock_responses(responses, default_response=None):
  return lambda input: responses[input] if input in responses else default_response

Now:

my_mock.foo.side_effect = mock_responses(
  {
    'x': 42, 
    'y': [1,2,3]
  })
my_mock.goo.side_effect = mock_responses(
  {
    'hello': 'world'
  }, 
  default_response='hi')
...

my_mock.foo('x') # => 42
my_mock.foo('y') # => [1,2,3]
my_mock.foo('unknown') # => None

my_mock.goo('hello') # => 'world'
my_mock.goo('ey') # => 'hi'

Hope this will help someone!

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

Move the jar files from your classpath to web-inf/lib, and run a new tomcat server.

How do I remove the first characters of a specific column in a table?

Why use LEN so you have 2 string functions? All you need is character 5 on...

...SUBSTRING (Code1, 5, 8000)...

Regex to validate JSON

Here my regexp for validate string:

^\"([^\"\\]*|\\(["\\\/bfnrt]{1}|u[a-f0-9]{4}))*\"$

Was written usign original syntax diagramm.

How does data binding work in AngularJS?

AngularJS remembers the value and compares it to a previous value. This is basic dirty-checking. If there is a change in value, then it fires the change event.

The $apply() method, which is what you call when you are transitioning from a non-AngularJS world into an AngularJS world, calls $digest(). A digest is just plain old dirty-checking. It works on all browsers and is totally predictable.

To contrast dirty-checking (AngularJS) vs change listeners (KnockoutJS and Backbone.js): While dirty-checking may seem simple, and even inefficient (I will address that later), it turns out that it is semantically correct all the time, while change listeners have lots of weird corner cases and need things like dependency tracking to make it more semantically correct. KnockoutJS dependency tracking is a clever feature for a problem which AngularJS does not have.

Issues with change listeners:

  • The syntax is atrocious, since browsers do not support it natively. Yes, there are proxies, but they are not semantically correct in all cases, and of course there are no proxies on old browsers. The bottom line is that dirty-checking allows you to do POJO, whereas KnockoutJS and Backbone.js force you to inherit from their classes, and access your data through accessors.
  • Change coalescence. Suppose you have an array of items. Say you want to add items into an array, as you are looping to add, each time you add you are firing events on change, which is rendering the UI. This is very bad for performance. What you want is to update the UI only once, at the end. The change events are too fine-grained.
  • Change listeners fire immediately on a setter, which is a problem, since the change listener can further change data, which fires more change events. This is bad since on your stack you may have several change events happening at once. Suppose you have two arrays which need to be kept in sync for whatever reason. You can only add to one or the other, but each time you add you fire a change event, which now has an inconsistent view of the world. This is a very similar problem to thread locking, which JavaScript avoids since each callback executes exclusively and to completion. Change events break this since setters can have far-reaching consequences which are not intended and non obvious, which creates the thread problem all over again. It turns out that what you want to do is to delay the listener execution, and guarantee, that only one listener runs at a time, hence any code is free to change data, and it knows that no other code runs while it is doing so.

What about performance?

So it may seem that we are slow, since dirty-checking is inefficient. This is where we need to look at real numbers rather than just have theoretical arguments, but first let's define some constraints.

Humans are:

  • Slow — Anything faster than 50 ms is imperceptible to humans and thus can be considered as "instant".

  • Limited — You can't really show more than about 2000 pieces of information to a human on a single page. Anything more than that is really bad UI, and humans can't process this anyway.

So the real question is this: How many comparisons can you do on a browser in 50 ms? This is a hard question to answer as many factors come into play, but here is a test case: http://jsperf.com/angularjs-digest/6 which creates 10,000 watchers. On a modern browser this takes just under 6 ms. On Internet Explorer 8 it takes about 40 ms. As you can see, this is not an issue even on slow browsers these days. There is a caveat: The comparisons need to be simple to fit into the time limit... Unfortunately it is way too easy to add a slow comparison into AngularJS, so it is easy to build slow applications when you don't know what you are doing. But we hope to have an answer by providing an instrumentation module, which would show you which are the slow comparisons.

It turns out that video games and GPUs use the dirty-checking approach, specifically because it is consistent. As long as they get over the monitor refresh rate (typically 50-60 Hz, or every 16.6-20 ms), any performance over that is a waste, so you're better off drawing more stuff, than getting FPS higher.

How to restore SQL Server 2014 backup in SQL Server 2008

Pretty old question... but I had the same problem today and solved with script, a little bit slow and complex but worked. I did this:

Let's start from the source DB (SQL 2014) right click on the database you would like to backup -> Generate Scripts -> "Script entire database and all database objet" (or u can select only some table if u want) -> the most important step is in the "Set Scripting Options" tab, here you have to click on "Advanced" and look for the option "Script for Server version" and in my case I could select everything from SQL 2005, also pay attention to the option "Types of data to script" I advice "Schema and data" and also Script Triggers and Script Full-text Indexes (if you need, it's false by default) and finally click ok and next. Should look like this:

Set Scripting Options

Now transfer your generated script into your SQL 2008, open it and last Important Step: You must change mdf and ldf location!!

That's all folks, happy F5!! :D

Could not load file or assembly Exception from HRESULT: 0x80131040

Finally found the answer!! Go to References --> right cilck on dll file that causing the problem --> select the properties --> check the version --> match the version in properties to web config

<dependentAssembly>
    <assemblyIdentity name="YourDllFile" publicKeyToken="2780ccd10d57b246"               culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-YourDllFileVersion" newVersion="YourDllFileVersion" />
  </dependentAssembly>

How to Sort Multi-dimensional Array by Value?

The most flexible approach would be using this method

Arr::sortByKeys(array $array, $keys, bool $assoc = true): array

here's why:

  • You can sort by any key (also nested like 'key1.key2.key3' or ['k1', 'k2', 'k3'])

  • Works both on associative and not associative arrays ($assoc flag)

  • It doesn't use reference - return new sorted array

In your case it would be as simple as:

$sortedArray = Arr::sortByKeys($array, 'order');

This method is a part of this library.

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Without external variables:

       $('.element').bind('mousewheel', function(e, d) {
            if((this.scrollTop === (this.scrollHeight - this.offsetHeight) && d < 0)
                || (this.scrollTop === 0 && d > 0)) {
                e.preventDefault();
            }
        });

Is null reference possible?

Yes:

#include <iostream>
#include <functional>

struct null_ref_t {
   template <typename T>
   operator T&() {
      union TypeSafetyBreaker {
         T *ptr;

         // see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
         std::reference_wrapper<T> ref; 
      };

      TypeSafetyBreaker ptr = {.ptr = nullptr};

      // unwrap the reference
      return ptr.ref.get();
   }
};

null_ref_t nullref;


int main() {
   int &a = nullref;

   // Segmentation fault
   a = 4;
   return 0;
}

Automatically add all files in a folder to a target using CMake?

So Why not use powershell to create the list of source files for you. Take a look at this script

param (
    [Parameter(Mandatory=$True)]
    [string]$root 
)

if (-not (Test-Path  -Path $root)) {    
throw "Error directory does not exist"
}

#get the full path of the root
$rootDir = get-item -Path $root
$fp=$rootDir.FullName;


$files = Get-ChildItem -Path $root -Recurse -File | 
         Where-Object { ".cpp",".cxx",".cc",".h" -contains $_.Extension} | 
         Foreach {$_.FullName.replace("${fp}\","").replace("\","/")}

$CMakeExpr = "set(SOURCES "

foreach($file in $files){

    $CMakeExpr+= """$file"" " ;
}
$CMakeExpr+=")"
return $CMakeExpr;

Suppose you have a folder with this structure

C:\Workspace\A
--a.cpp
C:\Workspace\B 
--b.cpp

Now save this file as "generateSourceList.ps1" for example, and run the script as

~>./generateSourceList.ps1 -root "C:\Workspace" > out.txt

out.txt file will contain

set(SOURCE "A/a.cpp" "B/b.cpp")

Accessing dictionary value by index in python

While you can do

value = d.values()[index]

It should be faster to do

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

Also, note that this assumes that your index is not negative

How do I output an ISO 8601 formatted string in JavaScript?

I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a local ISO date, I use the function:

function toLocalIsoString(date, includeSeconds) {
    function pad(n) { return n < 10 ? '0' + n : n }
    var localIsoString = date.getFullYear() + '-'
        + pad(date.getMonth() + 1) + '-'
        + pad(date.getDate()) + 'T'
        + pad(date.getHours()) + ':'
        + pad(date.getMinutes()) + ':'
        + pad(date.getSeconds());
    if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
    return localIsoString;
};

The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:

function getOffsetFromUTC() {
    var offset = new Date().getTimezoneOffset();
    return ((offset < 0 ? '+' : '-')
        + pad(Math.abs(offset / 60), 2)
        + ':'
        + pad(Math.abs(offset % 60), 2))
};

toLocalIsoString uses pad. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:

// Pad a number to length using padChar
function pad(number, length, padChar) {
    if (typeof length === 'undefined') length = 2;
    if (typeof padChar === 'undefined') padChar = '0';
    var str = "" + number;
    while (str.length < length) {
        str = padChar + str;
    }
    return str;
}

What do the result codes in SVN mean?

There is also an 'E' status

E = File existed before update

This can happen if you have manually created a folder that would have been created by performing an update.

Bind failed: Address already in use

The error usually means that the port you are trying to open is being already used by another application. Try using netstat to see which ports are open and then use an available port.

Also check if you are binding to the right ip address (I am assuming it would be localhost)

How can I select the row with the highest ID in MySQL?

This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery

SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )

How to add a new object (key-value pair) to an array in javascript?

.push() will add elements to the end of an array.

Use .unshift() if need to add some element to the beginning of array i.e:

items.unshift({'id':5});

Demo:

_x000D_
_x000D_
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.unshift({'id': 0});_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

And use .splice() in case you want to add object at a particular index i.e:

items.splice(2, 0, {'id':5});
           // ^ Given object will be placed at index 2...

Demo:

_x000D_
_x000D_
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.splice(2, 0, {'id': 2.5});_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

How to access elements of a JArray (or iterate over them)

Once you have a JArray you can treat it just like any other Enumerable object, and using linq you can access them, check them, verify them, and select them.

var str = @"[1, 2, 3]";
var jArray = JArray.Parse(str);
Console.WriteLine(String.Join("-", jArray.Where(i => (int)i > 1).Select(i => i.ToString())));

Why did Servlet.service() for servlet jsp throw this exception?

I had this error; it happened somewhat spontaneously, and the page would halt in the browser in the middle of an HTML tag (not a section of code). It was baffling!

Turns out, I let a variable go out of scope and the garbage collector swept it away and then I tried to use it. Thus the seemingly-random timing.

To give a more concrete example... Inside a method, I had something like:

Foo[] foos = new Foo[20];
// fill up the "foos" array...
return Arrays.asList(foos); // this returns type List<Foo>

Now in my JSP page, I called that method and used the List object returned by it. The List object is backed by that "foos" array; but, the array went out of scope when I returned from the method (since it is a local variable). So shortly after returning, the garbage collector swept away the "foos" array, and my access to the List caused a NullPointerException since its underlying array was now wiped away.

I actually wondered, as I wrote the above method, whether that would happen.

The even deeper underlying problem was premature optimization. I wanted a list, but I knew I would have exactly 20 elements, so I figured I'd try to be more efficient than new ArrayList<Foo>(20) which only sets an initial size of 20 but can possibly be less efficient than the method I used. So of course, to fix it, I just created my ArrayList, filled it up, and returned it. No more strange error.

Reading an integer from user input

You need to typecast the input. try using the following

int input = Convert.ToInt32(Console.ReadLine()); 

It will throw exception if the value is non-numeric.

Edit

I understand that the above is a quick one. I would like to improve my answer:

String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
      switch(selectedOption) 
      {
           case 1:
                 //your code here.
                 break;
           case 2:
                //another one.
                break;
           //. and so on, default..
      }

} 
else
{
     //print error indicating non-numeric input is unsupported or something more meaningful.
}

Parsing a JSON string in Ruby

That data looks like it is in JSON format.

You can use this JSON implementation for Ruby to extract it.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

I faced the same issue and solve after several trial and error. In the /etc/ssh/ssh_config, set

  • PubkeyAuthentication yes

  • AuthorizedKeysFile .ssh/authorized_keys

  • PasswordAuthentication no

  • AuthenticationMethods publickey

then, open putty. In the "Saved Sessions", enter the server IP, go through the path Connection->SSH->Auth->Browse on the left panel to search your private key and open it. Last but not least, go back to Session of putty on the left panel and you can see the server IP address is still in the field, "Saved Sessions", then click "Save", which is the critical step. It will let the user login without password any more. Have fun,

H2 in-memory database. Table not found

I was trying to fetch table meta data, but had the following error:

Using:

String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";

DatabaseMetaData metaData = connection.getMetaData();
...
metaData.getColumns(...);

returned an empty ResultSet.

But using the following URL instead it worked properly:

String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false";

There was a need to specify: DATABASE_TO_UPPER=false

Can two Java methods have same name with different return types?

You can have two methods with the same arguments and different return types only if one of the methods is inherited and the return types are compatible.

For example:

public class A
{
    Object foo() { return null; }
}

public class B
    extends A
{
    String foo() { return null; }
}

Benefits of EBS vs. instance-store (and vice-versa)

I've had the exact same experience as Eric at my last position. Now in my new job, I'm going through the same process I performed at my last job... rebuilding all their AMIs for EBS backed instances - and possibly as 32bit machines (cheaper - but can't use same AMI on 32 and 64 machines).

EBS backed instances launch quickly enough that you can begin to make use of the Amazon AutoScaling API which lets you use CloudWatch metrics to trigger the launch of additional instances and register them to the ELB (Elastic Load Balancer), and also to shut them down when no longer required.

This kind of dynamic autoscaling is what AWS is all about - where the real savings in IT infrastructure can come into play. It's pretty much impossible to do autoscaling right with the old s3 "InstanceStore"-backed instances.

What are .NumberFormat Options In Excel VBA?

In Excel, you can set a Range.NumberFormat to any string as you would find in the "Custom" format selection. Essentially, you have two choices:

  1. General for no particular format.
  2. A custom formatted string, like "$#,##0", to specify exactly what format you're using.

How to get JSON objects value if its name contains dots?

If json object key/name contains dot......! like

var myJson = {"my.name":"vikas","my.age":27}

Than you can access like

myJson["my.name"]
myJson["my.age"]

How can I combine two HashMap objects containing the same types?

If you know you don't have duplicate keys, or you want values in map2 to overwrite values from map1 for duplicate keys, you can just write

map3 = new HashMap<>(map1);
map3.putAll(map2);

If you need more control over how values are combined, you can use Map.merge, added in Java 8, which uses a user-provided BiFunction to merge values for duplicate keys. merge operates on individual keys and values, so you'll need to use a loop or Map.forEach. Here we concatenate strings for duplicate keys:

map3 = new HashMap<>(map1);
for (Map.Entry<String, String> e : map2.entrySet())
    map3.merge(e.getKey(), e.getValue(), String::concat);
//or instead of the above loop
map2.forEach((k, v) -> map3.merge(k, v, String::concat));

If you know you don't have duplicate keys and want to enforce it, you can use a merge function that throws an AssertionError:

map2.forEach((k, v) ->
    map3.merge(k, v, (v1, v2) ->
        {throw new AssertionError("duplicate values for key: "+k);}));

Taking a step back from this specific question, the Java 8 streams library provides toMap and groupingBy Collectors. If you're repeatedly merging maps in a loop, you may be able to restructure your computation to use streams, which can both clarify your code and enable easy parallelism using a parallel stream and concurrent collector.

Need to perform Wildcard (*,?, etc) search on a string using Regex

You can do a simple wildcard mach without RegEx using a Visual Basic function called LikeString.

using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;

if (Operators.LikeString("This is just a test", "*just*", CompareMethod.Text))
{
  Console.WriteLine("This matched!");
}

If you use CompareMethod.Text it will compare case-insensitive. For case-sensitive comparison, you can use CompareMethod.Binary.

More info here: http://www.henrikbrinch.dk/Blog/2012/02/14/Wildcard-matching-in-C

MSDN: http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compilerservices.operators.likestring%28v=vs.100%29.ASPX

How to change the playing speed of videos in HTML5?

You can use this code:

var vid = document.getElementById("video1");

function slowPlaySpeed() { 
    vid.playbackRate = 0.5;
} 

function normalPlaySpeed() { 
    vid.playbackRate = 1;
} 

function fastPlaySpeed() { 
    vid.playbackRate = 2;
}

How to call a SOAP web service on Android

If you can, go for JSON. Android comes with the complete org.json package

What is a good game engine that uses Lua?

Heroes of Might and Magic V used modified Silent Storm engine. I think you can find many good engines listed in wikipedia: Lua-scriptable game engines

Python: split a list based on a condition?

I basically like Anders' approach as it is very general. Here's a version that puts the categorizer first (to match filter syntax) and uses a defaultdict (assumed imported).

def categorize(func, seq):
    """Return mapping from categories to lists
    of categorized items.
    """
    d = defaultdict(list)
    for item in seq:
        d[func(item)].append(item)
    return d

Maven project version inheritance - do I have to specify the parent version?

eFox's answer worked for a single project, but not when I was referencing a module from another one (the pom.xml were still stored in my .m2 with the property instead of the version).

However, it works if you combine it with the flatten-maven-plugin, since it generates the poms with the correct version, not the property.

The only option I changed in the plug-in definition is the outputDirectory, it's empty by default, but I prefer to have it in target, which is set in my .gitignore configuration:

<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>flatten-maven-plugin</artifactId>
   <version>1.0.1</version>
   <configuration>
      <updatePomFile>true</updatePomFile>
      <outputDirectory>target</outputDirectory>
   </configuration>
   <executions>
      <execution>
         <id>flatten</id>
         <phase>process-resources</phase>
         <goals>
            <goal>flatten</goal>
         </goals>
      </execution>
   </executions>
</plugin>

The plug-in configuration goes in the parent pom.xml

jQuery - Check if DOM element already exists

In this case, you may want to check if element exists in current DOM

if you want to check if element exist in DOM tree (is attached to DOM), you can use:

var data = $('#data_1'); 
if(jQuery.contains(document.documentElement, data[0])){
    // #data_1 element attached to DOM
} else {
    // is not attached to DOM
}

Python: Find in list

As for your first question: that code is perfectly fine and should work if item equals one of the elements inside myList. Maybe you try to find a string that does not exactly match one of the items or maybe you are using a float value which suffers from inaccuracy.

As for your second question: There's actually several possible ways if "finding" things in lists.

Checking if something is inside

This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the in operator for that:

3 in [1, 2, 3] # => True

Filtering a collection

That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:

matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)

The latter will return a generator which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to

matches = filter(fulfills_some_condition, lst)

in Python 2. Here you can see higher-order functions at work. In Python 3, filter doesn't return a list, but a generator-like object.

Finding the first occurrence

If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else clause as well, which is not really well-known). You can also use

next(x for x in lst if ...)

which will return the first match or raise a StopIteration if none is found. Alternatively, you can use

next((x for x in lst if ...), [default value])

Finding the location of an item

For lists, there's also the index method that can sometimes be useful if you want to know where a certain element is in the list:

[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError

However, note that if you have duplicates, .index always returns the lowest index:......

[1,2,3,2].index(2) # => 1

If there are duplicates and you want all the indexes then you can use enumerate() instead:

[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]

Margin while printing html page

Firstly said, I try to force all my users to use Chrome when printing because other browsers create different layouts.

An answer from this question recommends:

@page {
  size: 210mm 297mm; 
  /* Chrome sets own margins, we change these printer settings */
  margin: 27mm 16mm 27mm 16mm; 
}

However, I ended up using this CSS for all my pages to be printed:

@media print 
{
    @page {
      size: A4; /* DIN A4 standard, Europe */
      margin:0;
    }
    html, body {
        width: 210mm;
        /* height: 297mm; */
        height: 282mm;
        font-size: 11px;
        background: #FFF;
        overflow:visible;
    }
    body {
        padding-top:15mm;
    }
}



Special case: Long Tables

When I needed to print a table over several pages, the margin:0 with the @page was leading to bleeding edges:

bleeding edges

I could solve this thanks to this answer with:

table { page-break-inside:auto }
tr    { page-break-inside:avoid; page-break-after:auto }
thead { display:table-header-group; }
tfoot { display:table-footer-group; }

Plus setting the top-bottom-margins for @page:

@page { 
    size: auto;
    margin: 20mm 0 10mm 0;
}
body {
    margin:0;
    padding:0;
}

Result:

solved bleeding edges

I would rather prefer a solution that is concise and works with all browser. For now, I hope the information above can help some developers with similar issues.

getting the reason why websockets closed with close code 1006

In my and possibly @BIOHAZARD case it was nginx proxy timeout. In default it's 60 sec without activity in socket

I changed it to 24h in nginx and it resolved problem

proxy_read_timeout 86400s;
proxy_send_timeout 86400s;

jQuery: how to scroll to certain anchor/div on page load?

    /* START --- scroll till anchor */
        (function($) {
             $.fn.goTo = function() {
                  var top_menu_height=$('#div_menu_header').height() + 5 ;
                  //alert ( 'top_menu_height is:' + top_menu_height );
                  $('html, body').animate({
                        scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px'
                  }, 500);
                  return this; // for chaining...
             }
        })(jQuery);

        $(document).ready(function(){

          var url = document.URL, idx = url.indexOf("#") ;
          var hash = idx != -1 ? url.substring(idx+1) : "";

          $(window).load(function(){
             // Remove the # from the hash, as different browsers may or may not include it
             var anchor_to_scroll_to = location.hash.replace('#','');
             if ( anchor_to_scroll_to != '' ) {
                 anchor_to_scroll_to = '#' + anchor_to_scroll_to ;
                 $(anchor_to_scroll_to).goTo();
             }
            });
        });
    /* STOP --- scroll till anchror */

Use of the MANIFEST.MF file in Java

Manifest.MF contains information about the files contained in the JAR file.

Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:

Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)

These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.

Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,

Main-Class: {fully qualified classname}

The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.

Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,

Class-Path: {jar1-name jar2-name directory-name/jar3-name}

This header can be used to specify the external JAR files on the same local network and not inside the current JAR.

Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:

Headers in a manifest
Header                  | Definition
-------------------------------------------------------------------
Name                    | The name of the specification.
Specification-Title     | The title of the specification.
Specification-Version   | The version of the specification.
Specification-Vendor    | The vendor of the specification.
Implementation-Title    | The title of the implementation.
Implementation-Version  | The build number of the implementation.
Implementation-Vendor   | The vendor of the implementation.

Package sealing related headers:

We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,

Name: {package/some-package/} Sealed:true

Here, the package name must end with ‘/’.

Enhancing security with manifest files:

We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.

META-INF folder:

This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.

Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

Select from one table where not in another

To expand on Johan's answer, if the part_num column in the sub-select can contain null values then the query will break.

To correct this, add a null check...

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN 
      (SELECT pd.part_num FROM wpsapi4.product_details pd 
                  where pd.part_num is not null)
  • Sorry but I couldn't add a comment as I don't have the rep!

Proper use of const for defining functions in JavaScript

Although using const to define functions seems like a hack, but it comes with some great advantages that make it superior (in my opinion)

  1. It makes the function immutable, so you don't have to worry about that function being changed by some other piece of code.

  2. You can use fat arrow syntax, which is shorter & cleaner.

  3. Using arrow functions takes care of this binding for you.

example with function

_x000D_
_x000D_
// define a function_x000D_
function add(x, y) { return x + y; }_x000D_
_x000D_
// use it_x000D_
console.log(add(1, 2)); // 3_x000D_
_x000D_
// oops, someone mutated your function_x000D_
add = function (x, y) { return x - y; };_x000D_
_x000D_
// now this is not what you expected_x000D_
console.log(add(1, 2)); // -1
_x000D_
_x000D_
_x000D_

same example with const

_x000D_
_x000D_
// define a function (wow! that is 8 chars shorter)_x000D_
const add = (x, y) => x + y;_x000D_
_x000D_
// use it_x000D_
console.log(add(1, 2)); // 3_x000D_
_x000D_
// someone tries to mutate the function_x000D_
add = (x, y) => x - y; // Uncaught TypeError: Assignment to constant variable._x000D_
// the intruder fails and your function remains unchanged
_x000D_
_x000D_
_x000D_

Editing legend (text) labels in ggplot

The legend titles can be labeled by specific aesthetic.

This can be achieved using the guides() or labs() functions from ggplot2 (more here and here). It allows you to add guide/legend properties using the aesthetic mapping.

Here's an example using the mtcars data set and labs():

ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
  geom_point() +
  labs(x="miles per gallon", y="displacement", size="horsepower", 
       col="# of cylinders", shape="# of gears")

enter image description here

Answering the OP's question using guides():

# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")

# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) + 
  geom_point(size=5) +
  labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  guides(color=guide_legend("my title"))  # add guide properties by aesthetic

enter image description here

iterating over and removing from a map

You have to use Iterator to safely remove element while traversing a map.

How to save python screen output to a text file

Let me summarize all the answers and add some more.

  • To write to a file from within your script, user file I/O tools that are provided by Python (this is the f=open('file.txt', 'w') stuff.

  • If don't want to modify your program, you can use stream redirection (both on windows and on Unix-like systems). This is the python myscript > output.txt stuff.

  • If you want to see the output both on your screen and in a log file, and if you are on Unix, and you don't want to modify your program, you may use the tee command (windows version also exists, but I have never used it)

  • Even better way to send the desired output to screen, file, e-mail, twitter, whatever is to use the logging module. The learning curve here is the steepest among all the options, but in the long run it will pay for itself.

Centering Bootstrap input fields

For me this solution worked well to center an input field in a TD:

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet" />_x000D_
<td style="background:#B3AEB5;">_x000D_
  <div class="form-group text-center">_x000D_
    <div class="input-group" style="margin:auto;">_x000D_
      <input type="month" name="p2" value="test">_x000D_
    </div>_x000D_
  </div>_x000D_
</td>
_x000D_
_x000D_
_x000D_

How to cast a double to an int in Java by rounding it down?

Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)

Simply typecast with (int), e.g.:

System.out.println((int)(99.9999)); // Prints 99

This being said, it does have a different behavior from Math.floor which rounds towards negative infinity (@Chris Wong)

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

Entity Framework – Use a Guid as the primary key

Using a Guid as your tables primary key, when using Entity Framework, requires a little more effort than when using a integer. The setup process is straightforward, after you’ve read/been shown how to do it.

The process is slightly different for the Code First and Database First approaches. This post discusses both techniques.

enter image description here

Code First

Using a Guid as the primary key when taking the code first approach is simple. When creating your entity, add the DatabaseGenerated attribute to your primary key property, as shown below;

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

Entity framework will create the column as you would expect, with a primary key and uniqueidentifier data type.

codefirst-defaultvalue

Also notice, very important, that the default value on the column has been set to (newsequentialid()). This generates a new sequential (continuous) Guid for each row. If you were so inclined, you could change this to newid()), which would result in a completely random Guid for each new row. This will be cleared each time your database gets dropped and re-created, so this works better when taking the Database First approach.

Database First

The database first approach follows a similar line to the code first approach, but you’ll have to manually edit your model to make it work.

Ensure that you edit the primary key column and add the (newsequentialid()) or (newid()) function as the default value before doing anything.

enter image description here

Next, open you EDMX diagram, select the appropriate property and open the properties window. Ensure that StoreGeneratedPattern is set to identity.

databasefirst-model

No need to give your entity an ID in your code, that will be populated for you automatically after the entity has been commited to the database;

using (ApplicationDbContext context = new ApplicationDbContext())
{
    var person = new Person
                     {
                         FirstName = "Random",
                         LastName = "Person";
                     };

    context.People.Add(person);
    context.SaveChanges();
    Console.WriteLine(person.Id);
}

Important Note: Your Guid field MUST be a primary key, or this does not work. Entity Framework will give you a rather cryptic error message!

Summary

Guid (Globally Unique Identifiers) can easily be used as primary keys in Entity Framework. A little extra effort is required to do this, depending on which approach you are taking. When using the code first approach, add the DatabaseGenerated attribute to your key field. When taking the Database First approach, explicitly set the StoredGeneratedPattern to Identity on your model.

[1]: https://i.stack.imgur.com/IxGdd.png
[2]: https://i.stack.imgur.com/Qssea.png

How to prevent a click on a '#' link from jumping to top of page?

The #/ trick works, but adds a history event to the browser. So, clicking back doesn't work as the user may want/expect it to.

$('body').click('a[href="#"]', function(e) {e.preventDefault() }); is the way I went, as it works for already existing content, and any elements added to the DOM after load.

Specifically, I needed to do this in a bootstrap dropdown-menu inside of a .btn-group(Reference), so I did:

$('body').click('.dropdown-menu li a[href="#"]', function(e) {e.preventDefault() });

This way it was targeted, and didn't affect anything thing else on the page.

Python Create unix timestamp five minutes in the future

Another way is to use calendar.timegm:

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return calendar.timegm(future.timetuple())

It's also more portable than %s flag to strftime (which doesn't work on Windows).

Compare given date with today

$date1=date_create("2014-07-02");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);

(the w3schools example, it works perfect)

Accessing bash command line args $@ vs $*

This example let may highlight the differ between "at" and "asterix" while we using them. I declared two arrays "fruits" and "vegetables"

fruits=(apple pear plumm peach melon)            
vegetables=(carrot tomato cucumber potatoe onion)

printf "Fruits:\t%s\n" "${fruits[*]}"            
printf "Fruits:\t%s\n" "${fruits[@]}"            
echo + --------------------------------------------- +      
printf "Vegetables:\t%s\n" "${vegetables[*]}"    
printf "Vegetables:\t%s\n" "${vegetables[@]}"    

See the following result the code above:

Fruits: apple pear plumm peach melon
Fruits: apple
Fruits: pear
Fruits: plumm
Fruits: peach
Fruits: melon
+ --------------------------------------------- +
Vegetables: carrot tomato cucumber potatoe onion
Vegetables: carrot
Vegetables: tomato
Vegetables: cucumber
Vegetables: potatoe
Vegetables: onion

Array as session variable

First change the array to a string by using implode() function. E.g $number=array(1,2,3,4,5,...); $stringofnumber=implode("|",$number); then pass the string to a session. e.g $_SESSION['string']=$stringofnumber; so when you go to the page where you want to use the array, just explode your string. e.g $number=explode("|", $_SESSION['string']); finally number is your array but remember to start array on the of each page.

How to search if dictionary value contains certain string with Python

import re
for i in range(len(myDict.values())):
     for j in range(len(myDict.values()[i])):
             match=re.search(r'Mary', myDict.values()[i][j])
             if match:
                     print match.group() #Mary
                     print myDict.keys()[i] #firstName
                     print myDict.values()[i][j] #Mary-Ann

Should I use the Reply-To header when sending emails as a service to others?

I tested dkarp's solution with gmail and it was filtered to spam. Use the Reply-To header instead (or in addition, although gmail apparently doesn't need it). Here's how linkedin does it:

Sender: [email protected]
From: John Doe via LinkedIn <[email protected]>
Reply-To: John Doe <[email protected]>
To: My Name <[email protected]>

Once I switched to this format, gmail is no longer filtering my messages as spam.

How can I join multiple SQL tables using the IDs?

You have not joined TableD, merely selected the TableD FIELD (dID) from one of the tables.

Java decimal formatting using String.format?

Yes you can do it with String.format:

String result = String.format("%.2f", 10.0 / 3.0);
// result:  "3.33"

result = String.format("%.3f", 2.5);
// result:  "2.500"

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.

Wrap long lines in Python

You can use the fact that Python concatenates string literals which appear adjacent to each other:

>>> def fun():
...     print '{0} Here is a really long ' \
...           'sentence with {1}'.format(3, 5)

PHPExcel - set cell type before writing a value in it

I wanted the Number same as I get from database for example.

1) 00100.220000

2) 00123

3) 0000.0000100

So I modified the code as below

$objPHPExcel->getActiveSheet()
    ->setCellValue('A3', '00100.220000');
$objPHPExcel->getActiveSheet()
    ->getStyle('A3')
    ->getNumberFormat()
    ->setFormatCode('00000.000000');


$objPHPExcel->getActiveSheet()
    ->setCellValue('A4', '00123');
$objPHPExcel->getActiveSheet()
  ->getStyle('A4')
 ->getNumberFormat()
->setFormatCode('00000');


$objPHPExcel->getActiveSheet()
    ->setCellValue('A5', '0000.0000100');
$objPHPExcel->getActiveSheet()
  ->getStyle('A5')
 ->getNumberFormat()
->setFormatCode('0000.0000000');

Why emulator is very slow in Android Studio?

Android Development Tools (ADT) 9.0.0 (or later) has a feature that allows you to save state of the AVD (emulator), and you can start your emulator instantly. You have to enable this feature while creating a new AVD or you can just create it later by editing the AVD.

Also I have increased the Device RAM Size to 1024 which results in a very fast emulator.

Refer the given below screenshots for more information.

Creating a new AVD with the save snapshot feature.

enter image description here

Launching the emulator from the snapshot.

enter image description here

And for speeding up your emulator you can refer to Speed up your Android Emulator!:

no pg_hba.conf entry for host

in my case i just changed spring.postgresql.jdbc.url that contained IPV4, i changed it to 127.0.0.1

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

"psql: could not connect to server: Connection refused" Error when connecting to remote database

Following configuration, you need to set:

To open the port 5432 edit your /etc/postgresql/9.1/main/postgresql.conf and change

# Connection Settings -

listen_addresses = '*'          # what IP address(es) to listen on;

In /etc/postgresql/10/main/pg_hba.conf

# IPv4 local connections:
host    all             all             0.0.0.0/0           md5

Now restart your DBMS

sudo service postgresql restart

Now you can connect with

psql -h hostname(IP) -p port -U username -d database

how to create a cookie and add to http response from inside my service layer?

To add a new cookie, use HttpServletResponse.addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction.

Android ListView not refreshing after notifyDataSetChanged

adpter.notifyDataSetInvalidated();

Try this in onPause() method of Activity class.

HTML form readonly SELECT tag/input

If you disable a form field, this won't be sent when form is submitted. So if you need a readonly that works like disabled but sending values do this :

After any change in readonly properties of an element.

$('select.readonly option:not(:selected)').attr('disabled',true);

$('select:not([readonly]) option').removeAttr('disabled');

z-index not working with position absolute

I faced this issue a lot when using position: absolute;, I faced this issue by using position: relative in the child element. don't need to change position: absolute to relative, just need to add in the child element look into the beneath two examples:

_x000D_
_x000D_
let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
_x000D_
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
_x000D_
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>
_x000D_
_x000D_
_x000D_

This's how it can be fixed using position relative:

_x000D_
_x000D_
let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
_x000D_
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
  
  // Just add position relative;
  position: relative;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
_x000D_
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>
_x000D_
_x000D_
_x000D_

Sandbox here

jquery to change style attribute of a div class

Just try $('.handle').css('left', '300px');

How to catch curl errors in PHP

    $responseInfo = curl_getinfo($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $body = substr($response, $header_size);
    $result=array();
    $result['httpCode']=$httpCode;
    $result['body']=json_decode($body);
    $result['responseInfo']=$responseInfo;
    print_r($httpCode); 
     print_r($result['body']); exit;
    curl_close($ch);
    if($httpCode == 403)
    {
        print_r("Access denied");
        exit;
    }   
    else
     {
         //catch more errors 
     }

How to check whether a given string is valid JSON in Java

String jsonInput = "{\"mob no\":\"9846716175\"}";//Read input Here
JSONReader reader = new JSONValidatingReader();
Object result = reader.read(jsonInput);
System.out.println("Validation Success !!");

Please download stringtree-json library

How to change colors of a Drawable in Android?

This code snippet worked for me:

PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(getResources().getColor(R.color.your_color),PorterDuff.Mode.MULTIPLY);

imgView.getDrawable().setColorFilter(porterDuffColorFilter);
imgView.setBackgroundColor(Color.TRANSPARENT)

Select from table by knowing only date without time (ORACLE)

Personally, I usually go with:

select * 
from   t1
where  date between trunc( :somedate )          -- 00:00:00
            and     trunc( :somedate ) + .99999 -- 23:59:59

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

This may be late, but sharing it for the new users visiting this question. To drop multiple columns actual syntax is

alter table tablename drop column col1, drop column col2 , drop column col3 ....

So for every column you need to specify "drop column" in Mysql 5.0.45.

java.lang.NoClassDefFoundError: Could not initialize class XXX

Just several days ago, I met the same question just like yours. All code runs well on my local machine, but turns out error(noclassdeffound&initialize). So I post my solution, but I don't know why, I merely advance a possibility. I hope someone know will explain this.@John Vint Firstly, I'll show you my problem. My code has static variable and static block both. When I first met this problem, I tried John Vint's solution, and tried to catch the exception. However, I caught nothing. So I thought it is because the static variable(but now I know they are the same thing) and still found nothing. So, I try to find the difference between the linux machine and my computer. Then I found that this problem happens only when several threads run in one process(By the way, the linux machine has double cores and double processes). That means if there are two tasks(both uses the code which has static block or variables) run in the same process, it goes wrong, but if they run in different processes, both of them are ok. In the Linux machine, I use

mvn -U clean  test -Dtest=path 

to run a task, and because my static variable is to start a container(or maybe you initialize a new classloader), so it will stay until the jvm stop, and the jvm stops only when all the tasks in one process stop. Every task will start a new container(or classloader) and it makes the jvm confused. As a result, the error happens. So, how to solve it? My solution is to add a new command to the maven command, and make every task go to the same container.

-Dxxx.version=xxxxx #sorry can't post more

Maybe you have already solved this problem, but still hope it will help others who meet the same problem.

Cross Domain Form POSTing

Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).

It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).

But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.

A good example: here

And a good documentation from Mozilla: here

Import error: No module name urllib2

For a script working with Python 2 (tested versions 2.7.3 and 2.6.8) and Python 3 (3.2.3 and 3.3.2+) try:

#! /usr/bin/env python

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

html = urlopen("http://www.google.com/")
print(html.read())

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

only 8.0.0 throw the exception, above 8.0 has remove the exception

8.0.0 throw the exception

Visual Studio debugger error: Unable to start program Specified file cannot be found

Guessing from the information I have, you're not actually compiling the program, but trying to run it. That is, ALL_BUILD is set as your startup project. (It should be in a bold font, unlike the other projects in your solution) If you then try to run/debug, you will get the error you describe, because there is simply nothing to run.

The project is most likely generated via CMAKE and included in your Visual Studio solution. Set any of the projects that do generate a .exe as the startup project (by right-clicking on the project and selecting "set as startup project") and you will most likely will be able to start those from within Visual Studio.

Easiest way to flip a boolean value?

If you know the values are 0 or 1, you could do flipval ^= 1.

change array size

If you really need to get it back into an array I find it easiest to convert the array to a list, expand the list then convert it back to an array.

        string[] myArray = new string[1] {"Element One"};
        // Convert it to a list
        List<string> resizeList = myArray.ToList();
        // Add some elements
        resizeList.Add("Element Two");
        // Back to an array
        myArray = resizeList.ToArray();
        // myArray has grown to two elements.

UIBarButtonItem in navigation bar programmatically?

iOS 11

Setting a custom button using constraint:

let buttonWidth = CGFloat(30)
let buttonHeight = CGFloat(30)

let button = UIButton(type: .custom)
button.setImage(UIImage(named: "img name"), for: .normal)
button.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)
button.widthAnchor.constraint(equalToConstant: buttonWidth).isActive = true
button.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true

self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: button)

How to delete last character from a string using jQuery?

You can do it with plain JavaScript:

alert('123-4-'.substr(0, 4)); // outputs "123-"

This returns the first four characters of your string (adjust 4 to suit your needs).

How can I get the baseurl of site?

The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:

uri.GetComponents(
    UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);

Common Header / Footer with static HTML

The simplest way to do that is using plain HTML.

You can use one of these ways:

<embed type="text/html" src="header.html">

or:

<object name="foo" type="text/html" data="header.html"></object>

javax.persistence.NoResultException: No entity found for query

When using java 8, you may take advantage of stream API and simplify code to

return (YourEntityClass) entityManager.createQuery()
....
.getResultList()
.stream().findFirst();

That will give you java.util.Optional

If you prefer null instead, all you need is

 ...
.getResultList()
.stream().findFirst().orElse(null);

Combating AngularJS executing controller twice

In some cases your directive runs twice when you simply not correct close you directive like this:

<my-directive>Some content<my-directive>

This will run your directive twice. Also there is another often case when your directive runs twice:

make sure you are not including your directive in your index.html TWICE!

CSS media query to target iPad and iPad only?

<html>
<head>
    <title>orientation and device detection in css3</title>

    <link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:portrait)" href="iphone-portrait.css" />
    <link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:landscape)" href="iphone-landscape.css" />
    <link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait)" href="ipad-portrait.css" />
    <link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape)" href="ipad-landscape.css" />
    <link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 1184px) and (orientation:portrait)" href="htcdesire-portrait.css" />
    <link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 390px) and (orientation:landscape)" href="htcdesire-landscape.css" />
    <link rel="stylesheet" media="all and (min-device-width: 1025px)" href="desktop.css" />

</head>
<body>
    <div id="iphonelandscape">iphone landscape</div>
    <div id="iphoneportrait">iphone portrait</div>
    <div id="ipadlandscape">ipad landscape</div>
    <div id="ipadportrait">ipad portrait</div>
    <div id="htcdesirelandscape">htc desire landscape</div>
    <div id="htcdesireportrait">htc desire portrait</div>
    <div id="desktop">desktop</div>
    <script type="text/javascript">
        function res() { document.write(screen.width + ', ' + screen.height); }
        res();
    </script>
</body>
</html>

How to convert a Kotlin source file to a Java source file

To convert a Kotlin source file to a Java source file you need to (when you in Android Studio):

  1. Press Cmd-Shift-A on a Mac, or press Ctrl-Shift-A on a Windows machine.

  2. Type the action you're looking for: Kotlin Bytecode and choose Show Kotlin Bytecode from menu.

enter image description here

  1. Press Decompile button on the top of Kotlin Bytecode panel.

enter image description here

  1. Now you get a Decompiled Java file along with Kotlin file in a adjacent tab:

enter image description here

Running Groovy script from the command line

It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.

Your /usr/local/bin/groovy is a shell script wrapping the Java runtime running Groovy.

See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).

What is __future__ in Python used for and how/when to use it, and how it works

It can be used to use features which will appear in newer versions while having an older release of Python.

For example

>>> from __future__ import print_function

will allow you to use print as a function:

>>> print('# of entries', len(dictionary), file=sys.stderr)

How do you do a limit query in JPQL or HQL?

String hql = "select userName from AccountInfo order by points desc 5";

This worked for me without using setmaxResults();

Just provide the max value in the last (in this case 5) without using the keyword limit. :P

Do I need to pass the full path of a file in another directory to open()?

Yes, you need the full path.

log = open(os.path.join(root, f), 'r')

Is the quick fix. As the comment pointed out, os.walk decends into subdirs so you do need to use the current directory root rather than indir as the base for the path join.

source of historical stock data

Unfortunately historical ticker data that is free is hard to come by. Now that opentick is dead, I dont know of any other provider.

In a previous lifetime I worked for a hedgefund that had an automated trading system, and we used historical data profusely.

We used TickData for our source. Their prices were reasonable, and the data had sub second resolution.

How to send parameters with jquery $.get()

I got this working : -

$.get('api.php', 'client=mikescafe', function(data) {
...
});

It sends via get the string ?client=mikescafe then collect this variable in api.php, and use it in your mysql statement.

Extract digits from string - StringUtils Java

You can use the following regular expression.

string.split(/ /)[0].replace(/[^\d]/g, '')

Calling async method on button click

use below code

 Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));

How can I change the font size of ticks of axes object in matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()

the x/yticks has the same properties as matplotlib.text

Vagrant stuck connection timeout retrying

I have faced the same problem. I fixed this by enabling Virtualization from BIOS setup.

UTF-8 all the way through

Data Storage:

  • Specify the utf8mb4 character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use utf8mb4 encoding if a utf8mb4_* collation is specified (without any explicit character set).

  • In older versions of MySQL (< 5.5.3), you'll unfortunately be forced to use simply utf8, which only supports a subset of Unicode characters. I wish I were kidding.

Data Access:

  • In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to utf8mb4. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.

  • Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:

    • If you're using the PDO abstraction layer with PHP = 5.3.6, you can specify charset in the DSN:

       $dbh = new PDO('mysql:charset=utf8mb4');
      
    • If you're using mysqli, you can call set_charset():

        $mysqli->set_charset('utf8mb4');       // object oriented style
        mysqli_set_charset($link, 'utf8mb4');  // procedural style
      
    • If you're stuck with plain mysql but happen to be running PHP = 5.2.3, you can call mysql_set_charset.

  • If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: SET NAMES 'utf8mb4'.

  • The same consideration regarding utf8mb4/utf8 applies as above.

Output:

  • If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or HTML metadata).

  • In PHP, you can use the default_charset php.ini option, or manually issue the Content-Type MIME header yourself, which is just more work but has the same effect.

  • When encoding the output using json_encode(), add JSON_UNESCAPED_UNICODE as a second parameter.

Input:

  • Unfortunately, you should verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's mb_check_encoding() does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.

  • From my reading of the current HTML spec, the following sub-bullets are not necessary or even valid anymore for modern HTML. My understanding is that browsers will work with and submit data in the character set specified for the document. However, if you're targeting older versions of HTML (XHTML, HTML4, etc.), these points may still be useful:

    • For HTML before HTML5 only: you want all data sent to you by browsers to be in UTF-8. Unfortunately, if you go by the only way to reliably do this is add the accept-charset attribute to all your <form> tags: <form ... accept-charset="UTF-8">.
    • For HTML before HTML5 only: note that the W3C HTML spec says that clients "should" default to sending forms back to the server in whatever charset the server served, but this is apparently only a recommendation, hence the need for being explicit on every single <form> tag.

Other Code Considerations:

  • Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.

  • You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's mbstring extension.

  • PHP's built-in string operations are not by default UTF-8 safe. There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent mbstring function.

  • To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from utf8.com for some good resources to learn everything you need to know.

How to set the part of the text view is clickable

It really helpful for the clickable part for some portion of the text.

The dot is a special character in the regular expression. If you want to spanable the dot need to escape dot as \\. instead of just passing "." to the spanable text method. Alternatively, you can also use the regular expression [.] to spanable the String by a dot in Java.

Can you use Microsoft Entity Framework with Oracle?

Oracle have announced a "statement of direction" for ODP.net and the Entity Framework:

In summary, ODP.Net beta around the end of 2010, production sometime in 2011.

Java equivalent to #region in C#

here is an example:

//region regionName
//code
//endregion

100% works in Android studio

Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory

Possibly, you closed the 'file1'.
Just use 'w' flag, that create new file:

file1 = open('recentlyUpdated.yaml', 'w')

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists)...

(see also https://docs.python.org/3/library/functions.html?highlight=open#open)

Fixing Segmentation faults in C++

On Unix you can use valgrind to find issues. It's free and powerful. If you'd rather do it yourself you can overload the new and delete operators to set up a configuration where you have 1 byte with 0xDEADBEEF before and after each new object. Then track what happens at each iteration. This can fail to catch everything (you aren't guaranteed to even touch those bytes) but it has worked for me in the past on a Windows platform.

Oracle PL/SQL : remove "space characters" from a string

Shorter version of:

REGEXP_REPLACE( my_value, '[[:space:]]', '' )

Would be:

REGEXP_REPLACE( my_value, '\s')

Neither of the above statements will remove "null" characters.

To remove "nulls" encase the statement with a replace

Like so:

REPLACE(REGEXP_REPLACE( my_value, '\s'), CHR(0))

Check if an element is present in a Bash array

Obvious caveats aside, if your array was actually like the one above, you could do

if [[ ${arr[*]} =~ d ]]
then
  do your thing
else
  do something
fi

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

gpg: no valid OpenPGP data found

I too got the same error, when I did this behind a proxy. But after I exported the following from a terminal and re-tried the same command, the problem got resolved:

export http_proxy="http://username:password@proxy_ip_addr:port/"
export https_proxy="https://username:password@proxy_ip_addr:port/"

Embed Youtube video inside an Android app

How it looks:

enter image description here

Best solution to my case. I need video fit web view size. Use embed youtube link with your video id. Example:

WebView youtubeWebView; //todo find or bind web view
String myVideoYoutubeId = "-bvXmLR3Ozc";

outubeWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });

WebSettings webSettings = youtubeWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);

youtubeWebView.loadUrl("https://www.youtube.com/embed/" + myVideoYoutubeId);

Web view xml code

<WebView
        android:id="@+id/youtube_web_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"/>

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

Try with this:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true">


<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--Main layout and ads-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/ll_main_hero"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

        </FrameLayout>

        <FrameLayout
            android:id="@+id/ll_ads"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <View
                android:layout_width="320dp"
                android:layout_height="50dp"
                android:layout_gravity="center"
                android:background="#ff00ff" />
        </FrameLayout>


    </LinearLayout>

    <!--Toolbar-->
    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar"
        android:elevation="4dp" />
</FrameLayout>


<!--left-->
<ListView
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@null"
    android:background="@mipmap/layer_image"
    android:id="@+id/left_drawer"></ListView>

<!--right-->
<FrameLayout
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="right"
    android:background="@mipmap/layer_image">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ken2"
        android:scaleType="centerCrop" />
</FrameLayout>

style :

<style name="ts_theme_overlay" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/red_A700</item>
    <item name="colorPrimaryDark">@color/red1</item>
    <item name="android:windowBackground">@color/blue_A400</item>
</style>

Main Activity extends ActionBarActivity

toolBar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolBar);

Now you can onCreateOptionsMenu like as normal ActionBar with ToolBar.

This is my Layout

  • TOP: Left Drawer - Right Drawer
    • MID: ToolBar (ActionBar)
    • BOTTOM: ListFragment

Hope you understand !have fun !

How to toggle (hide / show) sidebar div using jQuery

This help to hide and show the sidebar, and the content take place of the empty space left by the sidebar.

<div id="A">Sidebar</div>
<div id="B"><button>toggle</button>
Content here: Bla, bla, bla
</div>


//Toggle Hide/Show sidebar slowy
  $(document).ready(function(){
      $('#B').click(function(e) {
          e.preventDefault();
          $('#A').toggle('slow');
          $('#B').toggleClass('extended-panel'); 
      });
  }); 


html, body {
    margin: 0;
    padding: 0;
    border: 0;
}
#A, #B {
    position: absolute;
}
#A {
    top: 0px;
    width: 200px;
    bottom: 0px;
    background:orange;
}
#B {
    top: 0px;
    left: 200px;
    right: 0;
    bottom: 0px;
    background:green;
}

/* makes the content take place of the SIDEBAR 
   which is empty when is hided */
.extended-panel {
  left: 0px !important;
}

How does Java resolve a relative path in new File()?

The working directory is a common concept across virtually all operating systems and program languages etc. It's the directory in which your program is running. This is usually (but not always, there are ways to change it) the directory the application is in.

Relative paths are ones that start without a drive specifier. So in linux they don't start with a /, in windows they don't start with a C:\, etc. These always start from your working directory.

Absolute paths are the ones that start with a drive (or machine for network paths) specifier. They always go from the start of that drive.

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

try staring jboss with ./standalone.sh -c standalone-full.xml or any other alternative that allows you to start with the full profile

How to determine whether a Pandas Column contains a particular value

You can also use pandas.Series.isin although it's a little bit longer than 'a' in s.values:

In [2]: s = pd.Series(list('abc'))

In [3]: s
Out[3]: 
0    a
1    b
2    c
dtype: object

In [3]: s.isin(['a'])
Out[3]: 
0    True
1    False
2    False
dtype: bool

In [4]: s[s.isin(['a'])].empty
Out[4]: False

In [5]: s[s.isin(['z'])].empty
Out[5]: True

But this approach can be more flexible if you need to match multiple values at once for a DataFrame (see DataFrame.isin)

>>> df = DataFrame({'A': [1, 2, 3], 'B': [1, 4, 7]})
>>> df.isin({'A': [1, 3], 'B': [4, 7, 12]})
       A      B
0   True  False  # Note that B didn't match 1 here.
1  False   True
2   True   True

How to get a file directory path from file path?

dirname and basename are the tools you're looking for for extracting path components:

$ export VAR='/home/pax/file.c'
$ echo "$(dirname "${VAR}")" ; echo "$(basename "${VAR}")"
/home/pax
file.c

They're not internal Bash commands but they're part of the POSIX standard - see dirname and basename. Hence, they're probably available on, or can be obtained for, most platforms that are capable of running bash.

How to get screen width and height

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int height = metrics.heightPixels;
int width = metrics.widthPixels;

i guess the code which you wrote is deprecated.

How can I convert a string with dot and comma into a float in Python

Just remove the , with replace():

float("123,456.908".replace(',',''))

How do I select the parent form based on which submit button is clicked?

Eileen: No, it is not var nameVal = form.inputname.val();. It should be either...

in jQuery:

// you can use IDs (easier)

var nameVal =  $(form).find('#id').val();

// or use the [name=Fieldname] to search for the field

var nameVal =  $(form).find('[name=Fieldname]').val();

Or in JavaScript:

var nameVal = this.form.FieldName.value;

Or a combination:

var nameVal = $(this.form.FieldName).val();

With jQuery, you could even loop through all of the inputs in the form:

$(form).find('input, select, textarea').each(function(){

  var name = this.name;
  // OR
  var name = $(this).attr('name');

  var value = this.value;
  // OR
  var value = $(this).val();
  ....
  });

How to sort List of objects by some property

Since Java8 this can be done even cleaner using a combination of Comparator and Lambda expressions

For Example:

class Student{

    private String name;
    private List<Score> scores;

    // +accessor methods
}

class Score {

    private int grade;
    // +accessor methods
}

    Collections.sort(student.getScores(), Comparator.comparing(Score::getGrade);

How do I align views at the bottom of the screen?

You can just give your top child view (the TextView @+id/TextView) an attribute: android:layout_weight="1".

This will force all other elements below it to the bottom.

Fill DataTable from SQL Server database

If the variable table contains invalid characters (like a space) you should add square brackets around the variable.

public DataTable fillDataTable(string table)
{
    string query = "SELECT * FROM dstut.dbo.[" + table + "]";

    using(SqlConnection sqlConn = new SqlConnection(conSTR))
    using(SqlCommand cmd = new SqlCommand(query, sqlConn))
    {
        sqlConn.Open();
        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        return dt;
    }
}

By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input

"Uncaught Error: [$injector:unpr]" with angular after deployment

Ran into the same problem myself, but my controller definitions looked a little different than above. For controllers defined like this:

function MyController($scope, $http) {
    // ...
}

Just add a line after the declaration indicating which objects to inject when the controller is instantiated:

function MyController($scope, $http) {
    // ...
}
MyController.$inject = ['$scope', '$http'];

This makes it minification-safe.

How do I remove the non-numeric character from a string in java?

you could use a recursive method like below:

public static String getAllNumbersFromString(String input) {
        if (input == null || input.length() == 0) {
            return "";
        }
        char c = input.charAt(input.length() - 1);
        String newinput = input.substring(0, input.length() - 1);

            if (c >= '0' && c<= '9') {
            return getAllNumbersFromString(newinput) + c;

        } else {
            return getAllNumbersFromString(newinput);
        }
    } 

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

wt = tt - cpu tm.
Tt = cpu tm + wt.

Where wt is a waiting time and tt is turnaround time. Cpu time is also called burst time.

iptables block access to port 8000 except from IP address

Another alternative is;

sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP

I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

Edit**

According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP

CardView background color always white

XML code

<android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="5dp"
        app:contentPadding="25dp"
        app:cardBackgroundColor="#e4bfef"
        app:cardElevation="4dp"
        app:cardMaxElevation="6dp" />

From the code

CardView card = findViewById(R.id.card_view_top);
card.setCardBackgroundColor(Color.parseColor("#E6E6E6"));

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

Javascript to check whether a checkbox is being checked or unchecked

To toggle a checkbox or you can use

element.checked = !element.checked;

so you could use

if (attribute == elementName)
{
    arrChecks[i].checked = !arrChecks[i].checked;
} else {
    arrChecks[i].checked = false;
}

Sending JWT token in the headers with Postman

  1. Open postman.
  2. go to "header" field.
  3. there one can see "key value" blanks.
  4. in key type "Authorization".
  5. in value type "Bearer(space)your_access_token_value".

Done!

Getting value from a cell from a gridview on RowDataBound event

<asp:TemplateField HeaderText="# Percentage click throughs">
  <ItemTemplate>
    <%# AddPercentClickThroughs(Convert.ToDecimal(DataBinder.Eval(Container.DataItem, "EmailSummary.pLinksClicked")), Convert.ToDecimal(DataBinder.Eval(Container.DataItem, "NumberOfSends")))%>
  </ItemTemplate>
</asp:TemplateField>


public string AddPercentClickThroughs(decimal NumberOfSends, decimal EmailSummary.pLinksClicked)
{
    decimal OccupancyPercentage = 0;
    if (TotalNoOfRooms != 0 && RoomsOccupied != 0)
    {
        OccupancyPercentage = (Convert.ToDecimal(NumberOfSends) / Convert.ToDecimal(EmailSummary.pLinksClicked) * 100);
    }
    return OccupancyPercentage.ToString("F");
}

Check if decimal value is null

Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).

Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue

res.sendFile absolute path

res.sendFile( __dirname + "/public/" + "index1.html" );

where __dirname will manage the name of the directory that the currently executing script ( server.js ) resides in.

How to place a JButton at a desired location in a JFrame using Java

Use child.setLocation(0, 0) on the button, and parent.setLayout(null). Instead of using setBounds(...) on the JFrame to size it, consider using just setSize(...) and letting the OS position the frame.

//JPanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnAddFlight = new JButton("Add Flight");

public Control() {

    //JFrame layout
    this.setLayout(null);

    //JPanel layout
    pnlButton.setLayout(null);

    //Adding to JFrame
    pnlButton.add(btnAddFlight);
    add(pnlButton);

    // postioning
    pnlButton.setLocation(0,0);

Cookies on localhost with explicit domain

By design, domain names must have at least two dots; otherwise the browser will consider them invalid. (See reference on http://curl.haxx.se/rfc/cookie_spec.html)

When working on localhost, the cookie domain must be omitted entirely. You should not set it to "" or NULL or FALSE instead of "localhost". It is not enough.

For PHP, see comments on http://php.net/manual/en/function.setcookie.php#73107.

If working with the Java Servlet API, don't call the cookie.setDomain("...") method at all.

Changing the color of an hr element

I think this can be useful. this was simple CSS selector.

_x000D_
_x000D_
hr { background-color: red; height: 1px; border: 0; }
_x000D_
<hr>
_x000D_
_x000D_
_x000D_

Connection timeout for SQL server

If you want to dynamically change it, I prefer using SqlConnectionStringBuilder .

It allows you to convert ConnectionString i.e. a string into class Object, All the connection string properties will become its Member.

In this case the real advantage would be that you don't have to worry about If the ConnectionTimeout string part is already exists in the connection string or not?

Also as it creates an Object and its always good to assign value in object rather than manipulating string.

Here is the code sample:

var sscsb = new SqlConnectionStringBuilder(_dbFactory.Database.ConnectionString);

sscsb.ConnectTimeout = 30;

var conn = new SqlConnection(sscsb.ConnectionString);

Pandas: drop a level from a multi-level column index?

You can use MultiIndex.droplevel:

>>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")])
>>> df = pd.DataFrame([[1,2], [3,4]], columns=cols)
>>> df
   a   
   b  c
0  1  2
1  3  4

[2 rows x 2 columns]
>>> df.columns = df.columns.droplevel()
>>> df
   b  c
0  1  2
1  3  4

[2 rows x 2 columns]

python: urllib2 how to send cookie with urlopen request

Use cookielib. The linked doc page provides examples at the end. You'll also find a tutorial here.

How to run vi on docker container?

Use below command in Debian based container:

apt-get install vim-tiny

Complete instruction for using in Dockerfile:

RUN apt-get update && apt-get install --no-install-recommends -y \   
 vim-tiny \  
 && apt-get clean && rm -rf /var/lib/apt/lists/*

It doesn't install unnecessary packages and removes unnecessary downloaded files, so your docker image size won't increase dramatically.

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

In HTML5, they are equivalent. Use the shorter one, it is easier to remember and type. Browser support is fine since it was designed for backwards compatibility.

Php $_POST method to get textarea value

Try to use different id and name parameters, currently you have same here. Please visit the link below for the same, this might be help you :

Issue using $_POST with a textarea

Calculate percentage saved between two numbers?

    function calculatePercentage($oldFigure, $newFigure)
{
    $percentChange = (($oldFigure - $newFigure) / $oldFigure) * 100;
    return round(abs($percentChange));
}

Java8: sum values from specific field of the objects in a list

In Java 8 for an Obj entity with field and getField() method you can use:

List<Obj> objs ...

Stream<Obj> notNullObjs =
  objs.stream().filter(obj -> obj.getValue() != null);

Double sum = notNullObjs.mapToDouble(Obj::getField).sum();

python: [Errno 10054] An existing connection was forcibly closed by the remote host

This can be caused by the two sides of the connection disagreeing over whether the connection timed out or not during a keepalive. (Your code tries to reused the connection just as the server is closing it because it has been idle for too long.) You should basically just retry the operation over a new connection. (I'm surprised your library doesn't do this automatically.)

How can I find the number of elements in an array?

void numel(int array1[100][100])
{
    int count=0;
    for(int i=0;i<100;i++)
    {
        for(int j=0;j<100;j++)
        {
            if(array1[i][j]!='\0') 
            {
                count++;
                //printf("\n%d-%d",array1[i][j],count);
            }
            else 
                break;
        }
    }
    printf("Number of elements=%d",count);
}
int main()
{   
    int r,arr[100][100]={0},c;
    printf("Enter the no. of rows: ");
    scanf("%d",&r);
    printf("\nEnter the no. of columns: ");
    scanf("%d",&c);
    printf("\nEnter the elements: ");
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
            scanf("%d",&arr[i][j]);
        }
    }
    numel(arr);
}

This shows the exact number of elements in matrix irrespective of the array size you mentioned while initilasing(IF that's what you meant)

Remove non-ASCII characters from CSV

A perl oneliner would do: perl -i.bak -pe 's/[^[:ascii:]]//g' <your file>

-i says that the file is going to be edited inplace, and the backup is going to be saved with extension .bak.

How to get WordPress post featured image URL

Simply inside the loop write <?php the_post_thumbnail_url(); ?> as shown below:-

$args=array('post_type' => 'your_custom_post_type_slug','order' => 'DESC','posts_per_page'=> -1) ;
$the_qyery= new WP_Query($args);

if ($the_qyery->have_posts()) :
    while ( $the_qyery->have_posts() ) : $the_qyery->the_post();?>

<div class="col col_4_of_12">
    <div class="article_standard_view">
        <article class="item">
            <div class="item_header">
                <a href="<?php the_permalink(); ?>"><img src="<?php the_post_thumbnail_url(); ?>" alt="Post"></a>
            </div>

        </article>
    </div>
</div>            
<?php endwhile; endif; ?>

Variable not accessible when initialized outside function

Make sure you declare the variable on "root" level, outside any code blocks.

You could also remove the var altogether, although that is not recommended and will throw a "strict" warning.

According to the documentation at MDC, you can set global variables using window.variablename.

Removing spaces from a variable input using PowerShell 4.0

You're close. You can strip the whitespace by using the replace method like this:

$answer.replace(' ','')

There needs to be no space or characters between the second set of quotes in the replace method (replacing the whitespace with nothing).

Terminating a Java Program

Calling System.exit(0) (or any other value for that matter) causes the Java virtual machine to exit, terminating the current process. The parameter you pass will be the return value that the java process will return to the operating system. You can make this call from anywhere in your program - and the result will always be the same - JVM terminates. As this is simply calling a static method in System class, the compiler does not know what it will do - and hence does not complain about unreachable code.

return statement simply aborts execution of the current method. It literally means return the control to the calling method. If the method is declared as void (as in your example), then you do not need to specify a value, as you'd need to return void. If the method is declared to return a particular type, then you must specify the value to return - and this value must be of the specified type.

return would cause the program to exit only if it's inside the main method of the main class being execute. If you try to put code after it, the compiler will complain about unreachable code, for example:

public static void main(String... str) {
    System.out.println(1);
    return;
    System.out.println(2);
    System.exit(0);
}

will not compile with most compiler - producing unreachable code error pointing to the second System.out.println call.

C# delete a folder and all files and folders within that folder

dir.Delete(true); // true => recursive delete

Having issues with a MySQL Join that needs to meet multiple conditions

also this should work (not tested):

SELECT u.* FROM room u JOIN facilities_r fu ON fu.id_uc = u.id_uc AND u.id_fu IN(4,3) WHERE 1 AND vizibility = 1 GROUP BY id_uc ORDER BY u_premium desc , id_uc desc

If u.id_fu is a numeric field then you can remove the ' around them. The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".

Also I and Oracle too recommend to enclose table and field names in backticks. So you won't get into trouble if a field name contains a keyword.

How to append text to an existing file in Java?

Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.

Java 7+

For a one-time task, the Files class makes this easy:

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE and APPEND options, which will create the file first if it doesn't already exist:

private void write(final String s) throws IOException {
    Files.writeString(
        Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
        s + System.lineSeparator(),
        CREATE, APPEND
    );
}

However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter is faster:

try(FileWriter fw = new FileWriter("myfile.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Notes:

  • The second parameter to the FileWriter constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
  • Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
  • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
  • But the BufferedWriter and PrintWriter wrappers are not strictly necessary.

Older Java

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Exception Handling

If you need robust exception handling for older Java, it gets very verbose:

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}

Run a single migration file

Assuming fairly recent version of Rails you can always run:

rake db:migrate:up VERSION=20090408054532

Where version is the timestamp in the filename of the migration.

Edit: At some point over the last 8 years (I'm not sure what version) Rails added checks that prevent this from running if it has already been run. This is indicated by an entry in the schema_migrations table. To re-run it, simply execute rake db:migrate:redo VERSION=20090408054532 instead.

Why do we need to use flatMap?

It's not an array of arrays. It's an observable of observable(s).

The following returns an observable stream of string.

requestStream
  .map(function(requestUrl) {
    return requestUrl;
  });

While this returns an observable stream of observable stream of json

requestStream
  .map(function(requestUrl) {
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  });

flatMap flattens the observable automatically for us so we can observe the json stream directly

How to resolve 'npm should be run outside of the node repl, in your normal shell'

As mscdex said NPM comes with the nodejs msi installed file. I happened to just install the node js installer (standalone). To separately add NPM I followed following step

  1. Download the latest zip file of NPM from here.
  2. Extract it in the same file as that of node js installer.
  3. If you have added the directory containing to node js installer to PATH env variable then now even npm should be a recognized command.

Use of ~ (tilde) in R programming Language

R defines a ~ (tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:

library(datasets)
lm( myFormula, data=iris)

help("~") or help("formula") will teach you more.

@Spacedman has covered the basics. Let's discuss how it works.

First, being an operator, note that it is essentially a shortcut to a function (with two arguments):

> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs

That can be helpful to know for use in e.g. apply family commands.

Second, you can manipulate the formula as text:

oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )

Third, you can manipulate it as a list:

myFormula[[2]]
myFormula[[3]]

Finally, there are some helpful tricks with formulae (see help("formula") for more):

myFormula <- Species ~ . 

For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.

How to generate a unique hash code for string input in android...?

I use this i tested it as key from my EhCacheManager Memory map ....

Its cleaner i suppose

   /**
     * Return Hash256 of String value
     *
     * @param text
     * @return 
     */
    public static String getHash256(String text) {
        try {
            return org.apache.commons.codec.digest.DigestUtils.sha256Hex(text);
        } catch (Exception ex) {
            Logger.getLogger(HashUtil.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
    }

am using maven but this is the jar commons-codec-1.9.jar

Spark DataFrame groupBy and sort in the descending order (pyspark)

In PySpark 1.3 sort method doesn't take ascending parameter. You can use desc method instead:

from pyspark.sql.functions import col

(group_by_dataframe
    .count()
    .filter("`count` >= 10")
    .sort(col("count").desc()))

or desc function:

from pyspark.sql.functions import desc

(group_by_dataframe
    .count()
    .filter("`count` >= 10")
    .sort(desc("count"))

Both methods can be used with with Spark >= 1.3 (including Spark 2.x).

Setting a div's height in HTML with CSS

Here's an example of equal-height columns - Equal Height Columns - revisited

You can also check out the idea of "Faux Columns" as well - Faux Columns

Don't go the table route. If it's not tabular data, don't treat it as such. It's bad for accessibility and flexibility.

Writing a dict to txt file and reading it back?

To store Python objects in files, use the pickle module:

import pickle

a = {
  'a': 1,
  'b': 2
}

with open('file.txt', 'wb') as handle:
  pickle.dump(a, handle)

with open('file.txt', 'rb') as handle:
  b = pickle.loads(handle.read())

print a == b # True

Notice that I never set b = a, but instead pickled a to a file and then unpickled it into b.

As for your error:

self.whip = open('deed.txt', 'r').read()

self.whip was a dictionary object. deed.txt contains text, so when you load the contents of deed.txt into self.whip, self.whip becomes the string representation of itself.

You'd probably want to evaluate the string back into a Python object:

self.whip = eval(open('deed.txt', 'r').read())

Notice how eval sounds like evil. That's intentional. Use the pickle module instead.

multiple classes on single element html

Short Answer

Yes.


Explanation

It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

The following example will show you the use of multiple classes.

The first class makes the text color red.

The second class makes the background-color blue.

See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.

Result: multiple CSS statements in different classes will stack up.

You can read more about CSS Specificity.


CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

JavaScript string encryption and decryption?

Simple functions,


function Encrypt(value) 
{
  var result="";
  for(i=0;i<value.length;i++)
  {
    if(i<value.length-1)
    {
        result+=value.charCodeAt(i)+10;
        result+="-";
    }
    else
    {
        result+=value.charCodeAt(i)+10;
    }
  }
  return result;
}
function Decrypt(value)
{
  var result="";
  var array = value.split("-");

  for(i=0;i<array.length;i++)
  {
    result+=String.fromCharCode(array[i]-10);
  }
  return result;
} 

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

THE FINAL ANSWER FOR THOSE WHO USES ANGULAR 6:

Add the below command in your *.service.ts file"

import { map } from "rxjs/operators";

**********************************************Example**Below**************************************
getPosts(){
this.http.get('http://jsonplaceholder.typicode.com/posts')
.pipe(map(res => res.json()));
}
}

I am using windows 10;

angular6 with typescript V 2.3.4.0

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

I'm using ASP.NET SPA Extensions which creates me a proxy on ports 5000 and 5001 that pass through to Angular's port 4200 during development.

I had had CORS correctly setup for https port 5001 and everything was fine, but I inadvertently went to an old bookmark which was for port 5000. Then suddenly this message arose. As others have said in the console there was a 'preflight' error message.

So regardless of your environment, if you're using CORS make sure you have all ports specified - as the host and port both matter.

Convert a string representation of a hex dump to a byte array using Java?

The HexBinaryAdapter provides the ability to marshal and unmarshal between String and byte[].

import javax.xml.bind.annotation.adapters.HexBinaryAdapter;

public byte[] hexToBytes(String hexString) {
     HexBinaryAdapter adapter = new HexBinaryAdapter();
     byte[] bytes = adapter.unmarshal(hexString);
     return bytes;
}

That's just an example I typed in...I actually just use it as is and don't need to make a separate method for using it.

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

Delete the 'first' record from a table in SQL Server, without a WHERE condition

depends on your DBMS (people don't seem to know what that is nowadays)

-- MYSql:
DELETE FROM table LIMIT 1;
-- Postgres:
DELETE FROM table LIMIT 1;
-- MSSql:
DELETE TOP(1) FROM table;
-- Oracle:
DELETE FROM table WHERE ROWNUM = 1;