Programs & Examples On #Tilde

How do I get HTTP Request body content in Laravel?

For those who are still getting blank response with $request->getContent(), you can use:



public function foo(Request $request){
   $bodyContent = $request->all();

What's the difference between tilde(~) and caret(^) in package.json?

~ : Reasonably close to

   ~1.1.5: 1.1.0 <= accepted < 1.2.0

^: Compatible with

   ^1.1.5: 1.1.5 <= accepted < 2.0.0

   ^0.1.3: 0.1.3 <= accepted < 0.2.0

   ^0.0.4: 0.0.4 <= accepted < 0.1.0

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

In your controller add the following:

@RequestParam(value = "_csrf", required = false) String csrf

And on jsp page add

<form:form modelAttribute="someName" action="someURI?${_csrf.parameterName}=${_csrf.token}

Python reading from a file and saving to utf-8

You can't do that using open. use codecs.

when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:

import codecs
file ='data.txt','w','utf-8')

What is the bower (and npm) version syntax?

In a nutshell, the syntax for Bower version numbers (and NPM's) is called SemVer, which is short for 'Semantic Versioning'. You can find documentation for the detailed syntax of SemVer as used in Bower and NPM on the API for the semver parser within Node/npm. You can learn more about the underlying spec (which does not mention ~ or other syntax details) at

There's a super-handy visual semver calculator you can play with, making all of this much easier to grok and test.

SemVer isn't just a syntax! It has some pretty interesting things to say about the right ways to publish API's, which will help to understand what the syntax means. Crucially:

Once you identify your public API, you communicate changes to it with specific increments to your version number. Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version.

So, your specific question about ~ relates to that Major.Minor.Patch schema. (As does the related caret operator ^.) You can use ~ to narrow the range of versions you're willing to accept to either:

  • subsequent patch-level changes to the same minor version ("bug fixes not affecting the API"), or:
  • subsequent minor-level changes to the same major version ("backwards compatible API additions/changes")

For example: to indicate you'll take any subsequent patch-level changes on the 1.2.x tree, starting with 1.2.0, but less than 1.3.0, you could use:

"angular": "~1.2"
"angular": "~1.2.0"

This also gets you the same results as using the .x syntax:

"angular": "1.2.x"

But, you can use the tilde/~ syntax to be even more specific: if you're only willing to accept patch-level changes starting with 1.2.4, but still less than 1.3.0, you'd use:

"angular": "~1.2.4"

Moving left, towards the major version, if you use...

"angular": "~1"

... it's the same as...

"angular": "1.x"
"angular": "^1.0.0"

...and matches any minor- or patch-level changes above 1.0.0, and less than 2.0:

Note that last variation above: it's called a 'caret range'. The caret looks an awful lot like a >, so you'd be excused for thinking it means "any version greater than 1.0.0". (I've certainly slipped on that.) Nope!

Caret ranges are basically used to say that you care only about the left-most significant digit - usually the major version - and that you'll permit any minor- or patch-level changes that don't affect that left-most digit. Yet, unlike a tilde range that specifies a major version, caret ranges let you specify a precise minor/patch starting point. So, while ^1.0.0 === ~1, a caret range such as ^1.2.3 lets you say you'll take any changes >=1.2.3 && <2.0.0. You couldn't do that with a tilde range.

That all seems confusing at first, when you look at it up-close. But zoom out for a sec, and think about it this way: the caret simply lets you say that you're most concerned about whatever significant digit is left-most. The tilde lets you say you're most concerned about whichever digit is right-most. The rest is detail.

It's the expressive power of the tilde and the caret that explains why people use them much more than the simpler .x syntax: they simply let you do more. That's why you'll see the tilde used often even where .x would serve. As an example, see npm itself: its own package.json file includes lots of dependencies in ~2.4.0 format, rather than the 2.4.x format it could use. By sticking to ~, the syntax is consistent all the way down a list of 70+ versioned dependencies, regardless of which beginning patch number is acceptable.

Anyway, there's still more to SemVer, but I won't try to detail it all here. Check it out on the node semver package's readme. And be sure to use the semantic versioning calculator while you're practicing and trying to get your head around how SemVer works.

RE: Non-Consecutive Version Numbers: OP's final question seems to be about specifying non-consecutive version numbers/ranges (if I have edited it fairly). Yes, you can do that, using the common double-pipe "or" operator: ||. Like so:

"angular": "1.2 <= 1.2.9 || >2.0.0"

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:

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:


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.

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

Good to also check the other combinators in the family and to get back to what is this specific one.

  • ul li
  • ul > li
  • ul + ul
  • ul ~ ul

Example checklist:

  • ul li - Looking inside - Selects all the li elements placed (anywhere) inside the ul; Descendant selector
  • ul > li - Looking inside - Selects only the direct li elements of ul; i.e. it will only select direct children li of ul; Child Selector or Child combinator selector
  • ul + ul - Looking outside - Selects the ul immediately following the ul; It is not looking inside, but looking outside for the immediately following element; Adjacent Sibling Selector
  • ul ~ ul - Looking outside - Selects all the ul which follows the ul doesn't matter where it is, but both ul should be having the same parent; General Sibling Selector

The one we are looking at here is General Sibling Selector

The tilde operator in Python

~ is the bitwise complement operator in python which essentially calculates -x - 1

So a table would look like

i  ~i  
0  -1
1  -2
2  -3
3  -4 
4  -5 
5  -6

So for i = 0 it would compare s[0] with s[len(s) - 1], for i = 1, s[1] with s[len(s) - 2].

As for your other question, this can be useful for a range of bitwise hacks.

What is the "double tilde" (~~) operator in JavaScript?

It hides the intention of the code.

It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.

Some use it as a faster alternative to Math.floor, but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.

Update 2011-08:

With optimisation of the JavaScript engine in browsers, the performance for operators and functions change. With current browsers, using ~~ instead of Math.floor is somewhat faster in some browsers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browser.

See: tilde vs floor

Excel to CSV with UTF8 encoding

Using Notepad++

This will fix the corrupted CSV file saved by Excel and re-save it in the proper encoding.

  • Export CSV from Excel
  • Load into Notepad++
  • Fix encoding
  • Save

Excel saves in CP-1252 / Windows-1252. Open the CSV file in Notepad++. Select

Encoding > Character Sets > Western European > Windows-1252


Encoding > Convert to UTF-8
File > Save

First tell Notepad++ the encoding, then convert. Some of these other answers are converting without setting the proper encoding first, mangling the file even more. They would turn what should be into ?. If your character does not fit into CP-1252 then it was already lost when it was saved as CSV. Use another answer for that.

What is the proper way to test if a parameter is empty in a batch file?

Unfortunately I don't have enough reputation to comment or vote on the current answers to I've had to write my own.

Originally the OP's question said "variable" rather than "parameter", which got very confusing, especially as this was the number one link in google for searching how to test for blank variables. Since my original answer, Stephan has edited the original question to use the correct terminology, but rather than deleting my answer I decided to leave it to help clear up any confusion, especially in case google is still sending people here for variables too:


Very important distinction. A single percent sign with a number after it refers to a command line parameter not a variable.

Variables are set using the set command, and are recalled using 2 percent signs - one before and one after. For example %myvar%

To test for an empty variable you use the "if not defined" syntax (commands explicitly for variables do not require any percent signs), for example:

set myvar1=foo  
if not defined myvar1 echo You won't see this because %myvar1% is defined.  
if not defined myvar2 echo You will see this because %myvar2% isn't defined.

(If you want to test command line parameters then I recommend referring to jamesdlin's answer.)

How to check for changes on remote (origin) Git repository

One potential solution

Thanks to Alan Haggai Alavi's solution I came up with the following potential workflow:

Step 1:

git fetch origin

Step 2:

git checkout -b localTempOfOriginMaster origin/master
git difftool HEAD~3 HEAD~2
git difftool HEAD~2 HEAD~1
git difftool HEAD~1 HEAD~0

Step 3:

git checkout master
git branch -D localTempOfOriginMaster
git merge origin/master

What's the difference between HEAD^ and HEAD~ in Git?

Both ~ and ^ on their own refer to the parent of the commit (~~ and ^^ both refer to the grandparent commit, etc.) But they differ in meaning when they are used with numbers:

  • ~2 means up two levels in the hierarchy, via the first parent if a commit has more than one parent

  • ^2 means the second parent where a commit has more than one parent (i.e. because it's a merge)

These can be combined, so HEAD~2^3 means HEAD's grandparent commit's third parent commit.

Removing double quotes from variables in batch file creates problems with CMD environment

  1. set widget="a very useful item"
  2. set widget
  3. widget="a very useful item"
  4. set widget=%widget:"=%"
  5. set widget
  6. set widget=a very useful item"

The trailing quote " in line 4 is adding a quote " to the string. It should be removed. The syntax for line 4 ends with %

In c++ what does a tilde "~" before a function name signify?

It's a destructor. The function is guaranteed to be called when the object goes out of scope.

Meaning of tilde in Linux bash (not home directory)

If you're using autofs then the expansion might actually be coming from /etc/auto.home (or similar for your distro). For example, my /etc/auto.master looks like:

/home2 auto.home --timeout 60

and /etc/auto.home looks like:

mgalgs -rw,noquota,intr space:/space/mgalgs

How does the bitwise complement operator (~ tilde) work?

As others mentioned ~ just flipped bits (changes one to zero and zero to one) and since two's complement is used you get the result you saw.

One thing to add is why two's complement is used, this is so that the operations on negative numbers will be the same as on positive numbers. Think of -3 as the number to which 3 should be added in order to get zero and you'll see that this number is 1101, remember that binary addition is just like elementary school (decimal) addition only you carry one when you get to two rather than 10.

 1101 +
 0011 // 3
 0000 // lose carry bit because integers have a constant number of bits.

Therefore 1101 is -3, flip the bits you get 0010 which is two.

JBoss AS 7: How to clean up tmp?

Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :


Dropping Unique constraint from MySQL table

If you want to remove unique constraints from mysql database table, use alter table with drop index.


create table unique_constraints(unid int,activity_name varchar(100),CONSTRAINT activty_uqniue UNIQUE(activity_name),primary key (unid));

alter table unique_constraints drop index activty_uqniue;

Where activty_uqniue is UNIQUE constraint for activity_name column.

Get selected item value from Bootstrap DropDown with specific ID

$('#demolist li').on('click', function(){

How to configure Glassfish Server in Eclipse manually

For Eclipse Mars use the similar approach as harshit.

1) Help -> Install New Software
2) Use url: repository Above is the OEPE tool provided by oracle for EE development.
3) From all the suggestions, select Glassfish Tools, (Oracle Weblogic Server Tools, Oracle Weblogic Scripting Tools, Oracle patches, Oracle Maven Tools).
4) Install it.
5) Restart eclipse

In point 3) are 4 tools are in braces, I don't know minimal combination, but only install Glassfish Tools has no effect.

During restart Oepe ask for Java 8 JDK if Eclipse run on on older version.

Eclipse 4.5.0 Mars JDK : 1.8

Storing Objects in HTML5 localStorage

For Typescript users willing to set and get typed properties:

 * Silly wrapper to be able to type the storage keys
export class TypedStorage<T> {

    public removeItem(key: keyof T): void {

    public getItem<K extends keyof T>(key: K): T[K] | null {
        const data: string | null =  localStorage.getItem(key);
        return JSON.parse(data);

    public setItem<K extends keyof T>(key: K, value: T[K]): void {
        const data: string = JSON.stringify(value);
        localStorage.setItem(key, data);

Example usage:

// write an interface for the storage
interface MyStore {
   age: number,
   name: string,
   address: {city:string}

const storage: TypedStorage<MyStore> = new TypedStorage<MyStore>();

storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok

const address: {city:string} = storage.getItem("address");

Adjust icon size of Floating action button (fab)

What's your goal?

If set icon image size to bigger one:

  1. Make sure to have a bigger image size than your target size (so you can set max image size for your icon)

  2. My target icon image size is 84dp & fab size is 112dp:

        android:src= <image here>
        app:maxImageSize="84dp" />

Python Hexadecimal

I think this is what you want:

>>> def twoDigitHex( number ):
...     return '%02x' % number
>>> twoDigitHex( 2 )
>>> twoDigitHex( 255 )

Run javascript script (.js file) in mongodb including another file inside js

Another way is to pass the file into mongo in your terminal prompt.

$ mongo < myjstest.js

This will start a mongo session, run the file, then exit. Not sure about calling a 2nd file from the 1st however. I haven't tried it.

Display an image with Python

If you use matplotlib, you need to show the image using unless you are not in interactive mode. E.g.:

plt.imshow(sample_image)  # display it

Ruby replace string with captured regex pattern

Try '\1' for the replacement (single quotes are important, otherwise you need to escape the \):

"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"

But since you only seem to be interested in the capture group, note that you can index a string with a regex:

#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"

Show and hide divs at a specific time interval using jQuery

Try this

         window.setTimeout('test()',time in milliseconds);

      function test(){



iPhone Navigation Bar Title text color

In iOS 5 you can change the navigationBar title color in this manner:

navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};

Serializing enums with Jackson

Here is my solution. I want transform enum to {id: ..., name: ...} form.

With Jackson 1.x:




import my.NamedEnumJsonSerializer;
import my.NamedEnum;

@Table(name = "RULE")
public class Rule {
    @Column(name = "STATUS", nullable = false, updatable = true)
    @JsonSerialize(using = NamedEnumJsonSerializer.class)
    private Status status;
    public Status getStatus() { return status; }
    public void setStatus(Status status) { this.status = status; }

    public static enum Status implements NamedEnum {
        OPEN("open rule"),
        CLOSED("closed rule"),
        WORKING("rule in work");

        private String name;
        Status(String name) { = name; }
        public String getName() { return; }

package my;

public interface NamedEnum {
    String name();
    String getName();

package my;

import my.NamedEnum;
import java.util.*;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;

public class NamedEnumJsonSerializer extends JsonSerializer<NamedEnum> {
    public void serialize(NamedEnum value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        Map<String, String> map = new HashMap<>();
        map.put("name", value.getName());

With Jackson 2.x:




import com.fasterxml.jackson.annotation.JsonFormat;

@Table(name = "RULE")
public class Rule {
    @Column(name = "STATUS", nullable = false, updatable = true)
    private Status status;
    public Status getStatus() { return status; }
    public void setStatus(Status status) { this.status = status; }

    @JsonFormat(shape = JsonFormat.Shape.OBJECT)
    public static enum Status {
        OPEN("open rule"),
        CLOSED("closed rule"),
        WORKING("rule in work");

        private String name;
        Status(String name) { = name; }
        public String getName() { return; }
        public String getId() { return; }

Rule.Status.CLOSED translated to {id: "CLOSED", name: "closed rule"}.

APK signing error : Failed to read key from keystore

The big thing is either the alias or the other password is wrong. Kindly check your passwords and your issue is solved. Incase you have forgotten password, you can recover it from the androidStuido3.0/System/Log ... Search for the keyword password and their you are saved

MySQL Select Query - Get only first 10 characters of a value

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

How to increase time in web.config for executing sql query

You can do one thing.

  1. In the AppSettings.config (create one if doesn't exist), create a key value pair.
  2. In the Code pull the value and convert it to Int32 and assign it to command.TimeOut.

like:- In appsettings.config ->

   <add key="SqlCommandTimeOut" value="240"/>

In Code ->

command.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SqlCommandTimeOut"]);

That should do it.

Note:- I faced most of the timeout issues when I used SqlHelper class from microsoft application blocks. If you have it in your code and are facing timeout problems its better you use sqlcommand and set its timeout as described above. For all other scenarios sqlhelper should do fine. If your client is ok with waiting a little longer than what sqlhelper class offers you can go ahead and use the above technique.

example:- Use this -

 SqlCommand cmd = new SqlCommand(completequery);

 cmd.CommandTimeout =  Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SqlCommandTimeOut"]);

 SqlConnection con = new SqlConnection(sqlConnectionString);
 SqlDataAdapter adapter = new SqlDataAdapter();
 adapter.SelectCommand = new SqlCommand(completequery, con);

Instead of

DataSet ds = new DataSet();
ds = SqlHelper.ExecuteDataset(sqlConnectionString, CommandType.Text, completequery);

Update: Also refer to @Triynko answer below. It is important to check that too.

How to create a link to another PHP page

Use like this

<a href="index.php">Index Page</a>
<a href="page2.php">Page 2</a>

Best font for coding

Funny, I was just researching this yesterday!

I personally use Monaco 10 or 11 for the Mac, but a good cross platform font would have to be Droid Sans Mono: Or DejaVu sans mono is another great one (goes under a lot of different names, will be Menlo on SNow leopard and is really just a repackaged Prima/Vera) check it out here: Prima/Vera... Check it out here:

How do I make a simple crawler in PHP?

I used @hobodave's code, with this little tweak to prevent re-crawling all fragment variants of the same URL:

function crawl_page($url, $depth = 5)
  $parts = parse_url($url);
  if(array_key_exists('fragment', $parts)){
    $url = http_build_url($parts);

  static $seen = array();

Then you can also omit the $parts = parse_url($url); line within the for loop.

How to stop creating .DS_Store on Mac?

the function

find ~/ -name '.DS_Store' -delete

, removed the .DS store files temporarily. But am not sure , whether the files will came back on the Mac. Also i noticed something peculiar, the "DS_Store" start coming to the Mac after installing 'ATOM'. So guys please make it sure to scan properly your third party software before installing them. Best

Save string to the NSUserDefaults?

NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];

to get it back later

NSString *savedValue = [[NSUserDefaults standardUserDefaults]

make sounds (beep) with c++

Easiest way is probbaly just to print a ^G ascii bell


Referer is not a compulsory header. It may or may not be there or could be modified/fictitious. Rely on it at your own risk. Anyways, you should wrap your call so you do not get an undefined index error:

$server = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";

Difference between Role and GrantedAuthority in Spring Security

Like others have mentioned, I think of roles as containers for more granular permissions.

Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.

I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.


These permissions are relatively static, but the relationship of roles to them may be dynamic.

Example -

RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("DELETE"); RolePermissions(roleName, permissions));

You may create APIs to manage the relationship of these permissions to a role.

I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.

To re-use my implementation, I created a repo. Please feel free to contribute!

How to trigger click on page load?

try this,


$("your id here").trigger("click");

Undefined reference to 'vtable for xxx'

The first set of errors, for the missing vtable, are caused because you do not implement takeaway::textualGame(); instead you implement a non-member function, textualGame(). I think that adding the missing takeaway:: will fix that.

The cause of the last error is that you're calling a virtual function, initialData(), from the constructor of gameCore. At this stage, virtual functions are dispatched according to the type currently being constructed (gameCore), not the most derived class (takeaway). This particular function is pure virtual, and so calling it here gives undefined behaviour.

Two possible solutions:

  • Move the initialisation code for gameCore out of the constructor and into a separate initialisation function, which must be called after the object is fully constructed; or
  • Separate gameCore into two classes: an abstract interface to be implemented by takeaway, and a concrete class containing the state. Construct takeaway first, and then pass it (via a reference to the interface class) to the constructor of the concrete class.

I would recommend the second, as it is a move towards smaller classes and looser coupling, and it will be harder to use the classes incorrectly. The first is more error-prone, as there is no way be sure that the initialisation function is called correctly.

One final point: the destructor of a base class should usually either be virtual (to allow polymorphic deletion) or protected (to prevent invalid polymorphic deletion).

Server did not recognize the value of HTTP Header SOAPAction

I had to sort out capitalisation of my service reference, delete the references and re add them to fix this. I am not sure if any of these steps are superstitious, but the problem went away.

Property 'map' does not exist on type 'Observable<Response>'

In Angular v10.x and rxjs v6.x

First import map top of my service,

import {map} from 'rxjs/operators';

Then I use map like this

return this.http.get<return type>(URL)
  .pipe(map(x => {
    // here return your pattern

How to disable sort in DataGridView?

For extending control functionality like this, I like to use extension methods so that it can be reused easily. Here is a starter extensions file that contains an extension to disable sorting on a datagridview.

To use it, just include it in your project and call like this


In my case, I added this line of code in the DataBindingComplete eventhandler of the DataGridView where I wanted sorting disabled

Imports System.ComponentModel
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Windows.Forms

Public Module Extensions

Public Sub DisableSorting(datagrid As DataGridView)
    For index = 0 To datagrid.Columns.Count - 1
        datagrid.Columns(index).SortMode = DataGridViewColumnSortMode.NotSortable
End Sub

End Module

How to save username and password with Mercurial?

You can make an auth section in your .hgrc or Mercurial.ini file, like so:

bb.prefix =
bb.username = foo
bb.password = foo_passwd

The ‘bb’ part is an arbitrary identifier and is used to match prefix with username and password - handy for managing different username/password combos with different sites (prefix)

You can also only specify the user name, then you will just have to type your password when you push.

I would also recommend to take a look at the keyring extension. Because it stores the password in your system’s key ring instead of a plain text file, it is more secure. It is bundled with TortoiseHg on Windows, and there is currently a discussion about distributing it as a bundled extension on all platforms.

Use table name in MySQL SELECT "AS"

SELECT field1, field2, 'Test' AS field3 FROM Test; // replace with simple quote '

How to check if a column exists in a SQL Server table?

table -->script table as -->new windows - you have design script. check and find column name in new windows

Is there anyway to exclude artifacts inherited from a parent POM?

Have you tried explicitly declaring the version of mail.jar you want? Maven's dependency resolution should use this for dependency resolution over all other versions.


Debugging Stored Procedure in SQL Server 2008

MSDN has provided easy way to debug the stored procedure. Please check this link-
How to: Debug Stored Procedures

detect back button click in browser

Please try this (if the browser does not support "onbeforeunload"):

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

  if (window.history && window.history.pushState) {

    $(window).on('popstate', function() {
      var hashLocation = location.hash;
      var hashSplit = hashLocation.split("#!/");
      var hashName = hashSplit[1];

      if (hashName !== '') {
        var hash = window.location.hash;
        if (hash === '') {
          alert('Back button was pressed.');

    window.history.pushState('forward', null, './#forward');


What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

Shortcut way: (windows xp)

1) click Start > run > services.msc

2) Scroll down to 'Windows Presentation Foundation Font Cache' and then right click and select properties

Comparing two hashmaps for equal values and same key sets?

Make an equals check on the keySet() of both HashMaps.


If your Map contains String keys then it is no problem, but if your Map contains objA type keys then you need to make sure that your class objA implements equals().

Bootstrap date time picker

You don't need to give local path. just give cdn link of bootstrap datetimepicker. and it works.

<html lang="en">_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
 <link rel="stylesheet" href="">_x000D_
  <script src=""></script>_x000D_
  <script src=""></script>_x000D_
<script src=""></script>_x000D_
   <div class="container">_x000D_
      <div class="row">_x000D_
        <div class='col-sm-6'>_x000D_
            <div class="form-group">_x000D_
                <div class='input-group date' id='datetimepicker'>_x000D_
                    <input type='text' class="form-control" />_x000D_
                    <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
        <script type="text/javascript">_x000D_
            $(function () {_x000D_

How can I view array structure in JavaScript with alert()?

If what you want is to show with an alert() the content of an array of objects, i recomend you to define in the object the method toString() so with a simple alert(MyArray); the full content of the array will be shown in the alert.

Here is an example:

// Defininf the Point object
function Point(CoordenadaX, CoordenadaY) {
    // Sets the point coordinates depending on the parameters defined
    switch (arguments.length) {
        case 0:
            this.x = null;
            this.y = null;
        case 1:
            this.x = CoordenadaX;
            this.y = null;
        case 2:
            this.x = CoordenadaX;
            this.y = CoordenadaY;
    // This adds the toString Method to the point object so the 
    // point can be printed using alert();
    this.toString = function() {
        return " (" + this.x + "," + this.y + ") ";

Then if you have an array of points:

var MyArray = [];
MyArray.push ( new Point(5,6) );
MyArray.push ( new Point(7,9) );

You can print simply calling:


Hope this helps!

Putting an if-elif-else statement on one line?

It also depends on the nature of your expressions. The general advice on the other answers of "not doing it" is quite valid for generic statements and generic expressions.

But if all you need is a "dispatch" table, like, calling a different function depending on the value of a given option, you can put the functions to call inside a dictionary.

Something like:

def save(): 
def edit():
options = {"save": save, "edit": edit, "remove": lambda : "Not Implemented"}

option = get_input()
result = options[option]()

Instead of an if-else:

if option=="save":

onclick or inline script isn't working in extension

I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.

In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.

  • I found out that by placing the script before the DIV with ID that was called, the script did not work.
  • If the script was in another DIV, also it does not work
  • The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told

        <a id=id_page href ="#loving"   onclick="load_services()"> loving   </a>
                    // This script MUST BE under the "ID" that is calling
                    // Do not transfer it to a differ DIV than the caller "ID"
                    document.getElementById("id_page").addEventListener("click", function(){
                    document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
      <div id="mainbody" class="main_body">
            "here is loaded the external html file when the loving link will 
             be  clicked. "

How to solve SyntaxError on autogenerated

Just activate your virtual environment.

Remove Identity from a column in a table

In SQL Server you can turn on and off identity insert like this:


-- run your queries here


MySQL Select last 7 days

The WHERE clause is misplaced, it has to follow the table references and JOIN operations.

Something like this:

 FROM tartikel p1 
 JOIN tartikelpict p2 
   ON p1.kArtikel = p2.kArtikel 
  AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC

EDIT (three plus years later)

The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"

As to a question about writing a condition that checks a date range of "last 7 days"...

That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.

To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".

If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT


and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:

 WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY

For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...

 WHERE datetimecol >= NOW() + INTERVAL -7 DAY
   AND datetimecol <  NOW() + INTERVAL  0 DAY

the last seven complete days, not including today

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

or past six complete days plus so far today ...

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
   AND datetimecol <  NOW()       + INTERVAL  0 DAY

I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.

SET @clock = '2017-11-17 11:47:47' ;

     , DATE(@clock) + INTERVAL -7 DAY 
     , @clock + INTERVAL -6 DAY 

Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.

(Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax.

And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,

Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is

  WHERE datetimecol >= '2017-11-10 00:00'
    AND datetimecol <  '2017-11-17 00:00'

And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...

  WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
    AND datetimecol <  '2017-11-17 00:00' + INTERVAL 0 SECOND

The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy', m/d/yyyy, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.

How to write a confusion matrix in Python?

Scikit-learn (which I recommend using anyways) has it included in the metrics module:

>>> from sklearn.metrics import confusion_matrix
>>> y_true = [0, 1, 2, 0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 0, 0, 0, 1, 1, 0, 2, 2]
>>> confusion_matrix(y_true, y_pred)
array([[3, 0, 0],
       [1, 1, 1],
       [1, 1, 1]])

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

What exactly is nullptr?

According to cppreference, nullptr is a keyword that:

denotes the pointer literal. It is a prvalue of type std::nullptr_t. There exist implicit conversions from nullptr to null pointer value of any pointer type and any pointer to member type. Similar conversions exist for any null pointer constant, which includes values of type std::nullptr_t as well as the macro NULL.

So nullptr is a value of a distinct type std::nullptr_t, not int. It implicitly converts to the null pointer value of any pointer type. This magic happens under the hood for you and you don't have to worry about its implementation. NULL, however, is a macro and it is an implementation-defined null pointer constant. It's often defined like this:

#define NULL 0

i.e. an integer.

This is a subtle but important difference, which can avoid ambiguity.

For example:

int i = NULL;     //OK
int i = nullptr;  //error
int* p = NULL;    //OK
int* p = nullptr; //OK

and when you have two function overloads like this:

void func(int x);   //1)
void func(int* x);  //2)

func(NULL) calls 1) because NULL is an integer. func(nullptr) calls 2) because nullptr converts implicitly to a pointer of type int*.

Also if you see a statement like this:

auto result = findRecord( /* arguments */ );

if (result == nullptr)

and you can't easily find out what findRecord returns, you can be sure that result must be a pointer type; nullptr makes this more readable.

In a deduced context, things work a little differently. If you have a template function like this:

template<typename T>
void func(T *ptr)

and you try to call it with nullptr:


you will get a compiler error because nullptr is of type nullptr_t. You would have to either explicitly cast nullptr to a specific pointer type or provide an overload/specialization for func with nullptr_t.

Advantages of using nulptr:
  • avoid ambiguity between function overloads
  • enables you to do template specialization
  • more secure, intuitive and expressive code, e.g. if (ptr == nullptr) instead of if (ptr == 0)

Find by key deep in a nested array

Improved answer to take into account circular references within objects. It also displays the path it took to get there.

In this example, I am searching for an iframe that I know is somewhere within a global object:

const objDone = []
var i = 2
function getObject(theObject, k) {
    if (i < 1 || objDone.indexOf(theObject) > -1) return
    var result = null;
    if(theObject instanceof Array) {
        for(var i = 0; i < theObject.length; i++) {
            result = getObject(theObject[i], i);
            if (result) {
        for(var prop in theObject) {
            if(prop == 'iframe' && theObject[prop]) {
                console.log('iframe', theObject[prop])
                return theObject[prop]
            if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
                result = getObject(theObject[prop], prop);
                if (result) {
    if (result)
    return result;

Running the following: getObject(reader, 'reader') gave the following output and the iframe element in the end:

iframe // (The Dom Element)

NOTE: The path is in reverse order

How to normalize a 2-dimensional numpy array in python less verbose?

normed_matrix = normalize(input_data, axis=1, norm='l1')

where input_data is the name of your 2D array

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

OSError: [Errno 2] No such file or directory while using python subprocess in Django

No such file or directory can be also raised if you are trying to put a file argument to Popen with double-quotes.

For example:

call_args = ['mv', '"path/to/file with spaces.txt"', 'somewhere']

In this case, you need to remove double-quotes.

call_args = ['mv', 'path/to/file with spaces.txt', 'somewhere']

What causes the Broken Pipe Error?

The current state of a socket is determined by 'keep-alive' activity. In your case, this is possible that when you are issuing the send call, the keep-alive activity tells that the socket is active and so the send call will write the required data (40 bytes) in to the buffer and returns without giving any error.

When you are sending a bigger chunk, the send call goes in to blocking state.

The send man page also confirms this:

When the message does not fit into the send buffer of the socket, send() normally blocks, unless the socket has been placed in non-blocking I/O mode. In non-blocking mode it would return EAGAIN in this case

So, while blocking for the free available buffer, if the caller is notified (by keep-alive mechanism) that the other end is no more present, the send call will fail.

Predicting the exact scenario is difficult with the mentioned info, but I believe, this should be the reason for you problem.

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

Have a look at the syntax for adding a remote repo.

git remote add origin <url_of_remote repository>


git remote add origin [email protected]:peter/first_app.git

Let us dissect the command :

git remote this is used to manage your Central servers for hosting your git repositories.

May be you are using Github for your central repository stuff. I will give you a example and explain the git remote add origin command

Suppose I am working with GitHub and BitBucket for the central servers for the git repositories and have created repositories on both the websites for my first-app project.

Now if I want to push my changes to both these git servers then I will need to tell git how to reach these central repositories. So I will have to add these,

For GitHub

git remote add gh_origin

And For BitBucket

git remote add bb_origin https://[email protected]/user/first-app-git.git

I have used two variables ( as far it is easy for me to call them variables ) gh_origin ( gh FOR GITHUB ) and bb_origin ( bb for BITBUCKET ) just to explain you we can call origin anything we want.

Now after making some changes I will have to send(push) all these changes to central repositories so that other users can see these changes. So I call

Pushing to GitHub

git push gh_origin master

Pushing to BitBucket

git push bb_origin master

gh_origin is holding value of and bb_origin is holding value of https://[email protected]/user/first-app-git.git

This two variables are making my life easier

as whenever I need to send my code changes I need to use this words instead of remembering or typing the URL for the same.

Most of the times you wont see anything except than origin as most of the times you will deal with only one central repository like Github or BitBucket for example.

Android disable screen timeout while app is running

I used:


to disable the screen timeout and


to re-enable it.

How should I log while using multiprocessing in Python?

I liked zzzeek's answer. I would just substitute the Pipe for a Queue since if multiple threads/processes use the same pipe end to generate log messages they will get garbled.

Check if value is zero or not null in python

If number could be None or a number, and you wanted to include 0, filter on None instead:

if number is not None:

If number can be any number of types, test for the type; you can test for just int or a combination of types with a tuple:

if isinstance(number, int):  # it is an integer
if isinstance(number, (int, float)):  # it is an integer or a float

or perhaps:

from numbers import Number

if isinstance(number, Number):

to allow for integers, floats, complex numbers, Decimal and Fraction objects.

How to get the current time in Google spreadsheet using script editor?

use the JavaScript Date() object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)

function myFunction() {
  var d = new Date();
  var timeStamp = d.getTime();  // Number of ms since Jan 1, 1970

  // OR:

  var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance

Passing the argument to CMAKE via command prompt

CMake 3.13 on Ubuntu 16.04

This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:

$ cat CMakeLists.txt 
    message("MY_VARIABLE evaluates to True")

$ mkdir build && cd build

$ cmake ..
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

Object of class stdClass could not be converted to string - laravel

I was recieving the same error when I was tring to call an object element by using another objects return value like;

$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes

$this->array2->$this->array1->country;// Error line

The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country in another function as return value, (string), taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;

$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes


If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)

How to display an image from a path in MVC 4 and Razor view?

 @foreach (var m in Model)
      <img src="~/Images/@m.Url" style="overflow: hidden; position: relative; width:200px; height:200px;" />

Check for special characters in string

var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";_x000D_
var checkForSpecialChar = function(string){_x000D_
 for(i = 0; i < specialChars.length;i++){_x000D_
   if(string.indexOf(specialChars[i]) > -1){_x000D_
       return true_x000D_
 return false;_x000D_
var str = "YourText";_x000D_
  alert("Not Valid");_x000D_
} else {_x000D_

How to navigate through textfields (Next / Done Buttons)

After you exit from one text field, you call [otherTextField becomeFirstResponder] and the next field gets focus.

This can actually be a tricky problem to deal with since often you'll also want to scroll the screen or otherwise adjust the position of the text field so it's easy to see when editing. Just make sure to do a lot of testing with coming into and out of the text fields in different ways and also leaving early (always give the user an option to dismiss the keyboard instead of going to the next field, usually with "Done" in the nav bar)

Detect when a window is resized using JavaScript ?

Another way of doing this, using only JavaScript, would be this:

window.addEventListener('resize', functionName);

This fires every time the size changes, like the other answer.

functionName is the name of the function being executed when the window is resized (the brackets on the end aren't necessary).

How do you delete a column by name in data.table?

Here is a way when you want to set a # of columns to NULL given their column names a function for your usage :)

deleteColsFromDataTable <- function (train, toDeleteColNames) {

       for (myNm in toDeleteColNames)

       train <- train [,(myNm):=NULL]

       return (train)

How do you force a makefile to rebuild a target

Someone else suggested .PHONY which is definitely correct. .PHONY should be used for any rule for which a date comparison between the input and the output is invalid. Since you don't have any targets of the form output: input you should use .PHONY for ALL of them!

All that said, you probably should define some variables at the top of your makefile for the various filenames, and define real make rules that have both input and output sections so you can use the benefits of make, namely that you'll only actually compile things that are necessary to copmile!

Edit: added example. Untested, but this is how you do .PHONY

.PHONY: clean    

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

This will work definitely.....

Add the below lines in the POM file and give a build.


Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?


def func(TempLake,Z):
    return A*B

This works too , instead of looping , just vectorize however read below notes from the scipy documentation :

The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.

If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if cache is True to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive.

How to copy selected lines to clipboard in vim

If you are using vim in MAC OSX, unfortunately it comes with older verion, and not complied with clipboard options. Luckily, homebrew can easily solve this problem.

install vim:

brew install vim --with-lua --with-override-system-vim

install gui verion of vim:

brew install macvim --with-lua --with-override-system-vim

restart the terminal to take effect.

append the following line to ~/.vimrc

set clipboard=unnamed

now you can copy the line in vim withyy and paste it system-wide.

iPad/iPhone hover problem causes the user to double click a link

It is not entirely clear what your question is, but if you just want to eliminate the double click, while retaining the hover effect for the mouse, my advice is to:

  • Add hover effects on touchstart and mouseenter.
  • Remove hover effects on mouseleave, touchmove and click.


In order to simulate a mouse, browsers such as Webkit mobile fire the following events if a user touches and releases a finger on touch screen (like iPad) (source: Touch And Mouse on

  1. touchstart
  2. touchmove
  3. touchend
  4. 300ms delay, where the browser makes sure this is a single tap, not a double tap
  5. mouseover
  6. mouseenter
    • Note: If a mouseover, mouseenter or mousemove event changes the page content, the following events are never fired.
  7. mousemove
  8. mousedown
  9. mouseup
  10. click

It does not seem possible to simply tell the webbrowser to skip the mouse events.

What's worse, if a mouseover event changes the page content, the click event is never fired, as explained on Safari Web Content Guide - Handling Events, in particular figure 6.4 in One-Finger Events. What exactly a "content change" is, will depend on browser and version. I've found that for iOS 7.0, a change in background color is not (or no longer?) a content change.

Solution Explained

To recap:

  • Add hover effects on touchstart and mouseenter.
  • Remove hover effects on mouseleave, touchmove and click.

Note that there is no action on touchend!

This clearly works for mouse events: mouseenter and mouseleave (slightly improved versions of mouseover and mouseout) are fired, and add and remove the hover.

If the user actually clicks a link, the hover effect is also removed. This ensure that it is removed if the user presses the back button in the web browser.

This also works for touch events: on touchstart the hover effect is added. It is '''not''' removed on touchend. It is added again on mouseenter, and since this causes no content changes (it was already added), the click event is also fired, and the link is followed without the need for the user to click again!

The 300ms delay that a browser has between a touchstart event and click is actually put in good use because the hover effect will be shown during this short time.

If the user decides to cancel the click, a move of the finger will do so just as normal. Normally, this is a problem since no mouseleave event is fired, and the hover effect remains in place. Thankfully, this can easily be fixed by removing the hover effect on touchmove.

That's it!

Note that it is possible to remove the 300ms delay, for example using the FastClick library, but this is out of scope for this question.

Alternative Solutions

I've found the following problems with the following alternatives:

  • browser detection: Extremely prone to errors. Assumes that a device has either mouse or touch, while a combination of both will become more and more common when touch displays prolifirate.
  • CSS media detection: The only CSS-only solution I'm aware of. Still prone to errors, and still assumes that a device has either mouse or touch, while both are possible.
  • Emulate the click event in touchend: This will incorrectly follow the link, even if the user only wanted to scroll or zoom, without the intention of actually clicking the link.
  • Use a variable to suppress mouse events: This set a variable in touchend that is used as a if-condition in subsequent mouse events to prevents state changes at that point in time. The variable is reset in the click event. This is a decent solution if you really don't want a hover effect on touch interfaces. Unfortunately, this does not work if a touchend is fired for another reason and no click event is fired (e.g. the user scrolled or zoomed), and is subsequently trying to following the link with a mouse (i.e on a device with both mouse and touch interface).

Further Reading

See also iPad/iPhone double click problem and Disable hover effects on mobile browsers.

jQuery pass more parameters into callback

If someone still comes here, this is my take:

$('.selector').click(myCallbackFunction.bind({var1: 'hello', var2: 'world'}));

function myCallbackFunction(event) {
    var passedArg1 = this.var1,
        passedArg2 = this.var2

What happens here, after binding to the callback function, it will be available within the function as this.

This idea comes from how React uses the bind functionality.

How to open a txt file and read numbers in Java

Read file, parse each line into an integer and store into a list:

List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;

    while ((text = reader.readLine()) != null) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
    try {
        if (reader != null) {
    } catch (IOException e) {

//print out the list

Why does Firebug say toFixed() is not a function?

You need convert to number type:


How do I get length of list of lists in Java?

import java.util.ArrayList;

public class TestClass {

public static void main(String[] args) {

    ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
    ArrayList<String> List_1 = new ArrayList<String>();

    ArrayList<String> List_2 = new ArrayList<String>();
    for (int i = 0; i < listOLists.size(); i++) {
        System.out.print("list " + i + " :");
        for (int j = 0; j < listOLists.get(i).size(); j++) {
            System.out.print(listOLists.get(i).get(j) + " ;");



I hope this solution gives a better picture of list if lists

Retrieving Data from SQL Using pyodbc

Upvoted answer din't work for me, It was fixed by editing connection line as follows(replace semicolons with coma and also remove those quotes):

import pyodbc
cursor = cnxn.cursor()

for row in cursor.fetchall():
    print row

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];


$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

Here is my one liner. Here 'c' is the name of the column'c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count()

Test if a string contains any of the strings from an array

A more groovyesque approach would be to use inject in combination with metaClass:

I would to love to say:

String myInput="This string is FORBIDDEN"
myInput.containsAny(["FORBIDDEN","NOT_ALLOWED"]) //=>true

And the method would be:

myInput.metaClass.containsAny={List<String> notAllowedTerms->
   notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})

If you need containsAny to be present for any future String variable then add the method to the class instead of the object:

   notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})

Measuring elapsed time with the Time module

Here is an update to Vadim Shender's clever code with tabular output:

import collections
import time
from functools import wraps

PROF_DATA = collections.defaultdict(list)

def profile(fn):
    def with_profiling(*args, **kwargs):
        start_time = time.time()
        ret = fn(*args, **kwargs)
        elapsed_time = time.time() - start_time
        return ret
    return with_profiling

Metrics = collections.namedtuple("Metrics", "sum_time num_calls min_time max_time avg_time fname")

def print_profile_data():
    results = []
    for fname, elapsed_times in PROF_DATA.items():
        num_calls = len(elapsed_times)
        min_time = min(elapsed_times)
        max_time = max(elapsed_times)
        sum_time = sum(elapsed_times)
        avg_time = sum_time / num_calls
        metrics = Metrics(sum_time, num_calls, min_time, max_time, avg_time, fname)
    total_time = sum([m.sum_time for m in results])
    print("\t".join(["Percent", "Sum", "Calls", "Min", "Max", "Mean", "Function"]))
    for m in sorted(results, reverse=True):
        print("%.1f\t%.3f\t%d\t%.3f\t%.3f\t%.3f\t%s" % (100 * m.sum_time / total_time, m.sum_time, m.num_calls, m.min_time, m.max_time, m.avg_time, m.fname))
    print("%.3f Total Time" % total_time)

Android: how to get the current day of the week (Monday, etc...) in the user's language?

Try this...

//global declaration
private TextView timeUpdate;
Calendar calendar;


timeUpdate = (TextView) findViewById(; //initialize in onCreate()


//in onStart()
calendar = Calendar.getInstance();
//date format is:  "Date-Month-Year Hour:Minutes am/pm"
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm a"); //Date and time
String currentDate = sdf.format(calendar.getTime());

//Day of Name in full form like,"Saturday", or if you need the first three characters you have to put "EEE" in the date format and your result will be "Sat".
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE"); 
Date date = new Date();
String dayName = sdf_.format(date);
timeUpdate.setText("" + dayName + " " + currentDate + "");

The result is... enter image description here

happy coding.....

How to get an array of unique values from an array containing duplicates in JavaScript?

It's 2014 now guys, and time complexity still matters!

array.filter(function() {
  var seen = {};
  return function(element, index, array) {
    return !(element in seen) && (seen[element] = 1);

Android 6.0 Marshmallow. Cannot write to SD Card

Right. So I've finally got to the bottom of the problem: it was a botched in-place OTA upgrade.

My suspicions intensified after my Garmin Fenix 2 wasn't able to connect via bluetooth and after googling "Marshmallow upgrade issues". Anyway, a "Factory reset" fixed the issue.

Surprisingly, the reset did not return the phone to the original Kitkat; instead, the wipe process picked up the OTA downloaded 6.0 upgrade package and ran with it, resulting (I guess) in a "cleaner" upgrade.

Of course, this meant that the phone lost all the apps that I'd installed. But, freshly installed apps, including mine, work without any changes (i.e. there is backward compatibility). Whew!

Whitespace Matching Regex - Java

For Java (not php, not javascript, not anyother):

txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")

Render basic HTML view?

For plain html you don't require any npm package or middleware

just use this:

app.get('/', function(req, res) {

Removing address bar from browser (to view on Android)

Here's the NON-jQuery solution that instantly removes the address bar without scrolling. Also, it works when you rotate the browser's orientation.

function hideAddressBar(){

It should work with the iPhone also, but I couldn't test this.

jQuery dialog popup

Use below Code, It worked for me.

<script type="text/javascript">
     $(document).ready(function () {
                autoOpen: false,
                title: 'Basic Dialog'
            $('#contactUs').click(function () {

convert HTML ( having Javascript ) to PDF using JavaScript

Check this out

Basically you need to use html2canvas and jspdf to make it work. First you will convert your dom to image and then you will use jspdf to create pdf with the images.

EDIT: A short note on how it work. We will use two libraries to make this job done. and First we will create a dom image by using html2canvas them we will use jspdf addImage method to add that image to pdf. It seems simple but there are few bugs in jsPdf and html2cavas so you may need to change dom style temporarily. Hope this helps.

How to correct indentation in IntelliJ

In Android Studio this works: Go to File->Settings->Editor->CodeStyle->Java. Under Wrapping and Braces uncheck "Comment at first Column" Then formatting shortcut will indent the comment lines as well.

How do I perform an insert and return inserted identity with Dapper?

Not sure if it was because I'm working against SQL 2000 or not but I had to do this to get it to work.

string sql = "DECLARE @ID int; " +
             "INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff); " +
             "SET @ID = SCOPE_IDENTITY(); " +
             "SELECT @ID";

var id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();

SQL Server: Difference between PARTITION BY and GROUP BY

-- CREATE A database called testDB

-- use testDB
USE [TestDB]

-- create Paints table
CREATE TABLE [dbo].[Paints](
    [Color] [varchar](50) NULL,
    [glossLevel] [varchar](50) NULL


-- Populate Table
insert into paints (color, glossLevel)
select 'red', 'eggshell'
select 'red', 'glossy'
select 'red', 'flat'
select 'blue', 'eggshell'
select 'blue', 'glossy'
select 'blue', 'flat'
select 'orange', 'glossy'
select 'orange', 'flat'
select 'orange', 'eggshell'
select 'green', 'eggshell'
select 'green', 'glossy'
select 'green', 'flat'
select 'black', 'eggshell'
select 'black', 'glossy'
select 'black', 'flat'
select 'purple', 'eggshell'
select 'purple', 'glossy'
select 'purple', 'flat'
select 'salmon', 'eggshell'
select 'salmon', 'glossy'
select 'salmon', 'flat'

/*   COMPARE 'GROUP BY' color to 'OVER (PARTITION BY Color)'  */

-- GROUP BY Color 
-- row quantity defined by group by
-- aggregate (count(*)) defined by group by
select count(*) from paints
group by color

-- row quantity defined by main query
-- aggregate defined by OVER-PARTITION BY
select color
, glossLevel
, count(*) OVER (Partition by color)
from paints

/* COMPARE 'GROUP BY' color, glossLevel to 'OVER (PARTITION BY Color, GlossLevel)'  */

-- GROUP BY Color, GlossLevel
-- row quantity defined by GROUP BY
-- aggregate (count(*)) defined by GROUP BY
select count(*) from paints
group by color, glossLevel

-- Partition by Color, GlossLevel
-- row quantity defined by main query
-- aggregate (count(*)) defined by OVER-PARTITION BY
select color
, glossLevel
, count(*) OVER (Partition by color, glossLevel)
from paints

Writing your own square root function

Let me point out an extremely interesting method of calculating an inverse square root 1/sqrt(x) which is a legend in the world of game design because it is mind-boggingly fast. Or wait, read the following post:

PS: I know you just want the square root but the elegance of quake overcame all resistance on my part :)

By the way, the above mentioned article also talks about the boring Newton-Raphson approximation somewhere.

Get keys from HashMap in Java

Use functional operation for faster iteration.

team1.keySet().forEach((key) -> { System.out.println(key); });

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

I also encountered this problem. I found after changing the table storage engine from MyISAM to Innodb, problem solved .

What is CDATA in HTML?


Since it is useful to be able to use less-than signs (<) and ampersands (&) in web page scripts, and to a lesser extent styles, without having to remember to escape them, it is common to use CDATA markers around the text of inline and elements in XHTML documents. But so that the document can also be parsed by HTML parsers, which do not recognise the CDATA markers, the CDATA markers are usually commented-out, as in this JavaScript example:

<script type="text/javascript">

How to remove border of drop down list : CSS

select#xyz {

Exact solution.

Integrity constraint violation: 1452 Cannot add or update a child row:

I hope my decision will help. I had a similar error in Laravel. I added a foreign key to the wrong table.
Wrong code:

Schema::create('comments', function (Blueprint $table) {

Schema::create('posts', function (Blueprint $table) {

Please note to the function on('comments') above. Correct code


how to check if the input is a number or not in C?

Another way of doing it is by using isdigit function. Below is the code for it:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
    char input[MAXINPUT] = "";
    int length,i; 

    scanf ("%s", input);
    length = strlen (input);
    for (i=0;i<length; i++)
        if (!isdigit(input[i]))
            printf ("Entered input is not a number\n");
    printf ("Given input is a number\n");

How to compare objects by multiple fields


 * @author radler
 * Class Description ...
public class Attribute implements Comparable<Attribute> {

    private String type;
    private String value;

    public String getType() { return type; }
    public void setType(String type) { this.type = type; }

    public String getValue() { return value; }
    public void setValue(String value) { this.value = value; }

    public String toString() {
        return "Attribute [type=" + type + ", value=" + value + "]";

    public int compareTo(Attribute that) {
        return ComparisonChain.start()
            .compare(this.type, that.type)
            .compare(this.value, that.value)


TypeScript: casting HTMLElement

var script = (<HTMLScriptElement[]><any>document.getElementsByName(id))[0];    

Retrieving the last record in each group - MySQL

What about:

select *, max(id) from messages group by name 

I have tested it on sqlite and it returns all columns and max id value for all names.

Age from birthdate in python

Slightly modified Danny's solution for easier reading and understanding

    from datetime import date

    def calculate_age(birth_date):
        today =
        age = today.year - birth_date.year
        full_year_passed = (today.month, < (birth_date.month,
        if not full_year_passed:
            age -= 1
        return age

How do I convert a long to a string in C++?

One of the things not covered by anybody so far, to help you think about the problem further, is what format should a long take when it is cast to a string.

Just have a look at a spreedsheet program (like Calc/Excel). Do you want it rounded to the nearest million, with brackets if it's negative, always to show the sign.... Is the number realy a representation of something else, should you show it in Oractal or Hex instead?

The answers so far have given you some default output, but perhaps not the right ones.

How to get the number of columns in a matrix?

While size(A,2) is correct, I find it's much more readable to first define

rows = @(x) size(x,1); 
cols = @(x) size(x,2);

and then use, for example, like this:

howManyColumns_in_A = cols(A)
howManyRows_in_A    = rows(A)

It might appear as a small saving, but size(.., 1) and size(.., 2) must be some of the most commonly used functions, and they are not optimally readable as-is.

TypeError: 'str' does not support the buffer interface

This problem commonly occurs when switching from py2 to py3. In py2 plaintext is both a string and a byte array type. In py3 plaintext is only a string, and the method outfile.write() actually takes a byte array when outfile is opened in binary mode, so an exception is raised. Change the input to plaintext.encode('utf-8') to fix the problem. Read on if this bothers you.

In py2, the declaration for file.write made it seem like you passed in a string: file.write(str). Actually you were passing in a byte array, you should have been reading the declaration like this: file.write(bytes). If you read it like this the problem is simple, file.write(bytes) needs a bytes type and in py3 to get bytes out of a str you convert it:

py3>> outfile.write(plaintext.encode('utf-8'))

Why did the py2 docs declare file.write took a string? Well in py2 the declaration distinction didn't matter because:

py2>> str==bytes         #str and bytes aliased a single hybrid class in py2

The str-bytes class of py2 has methods/constructors that make it behave like a string class in some ways and a byte array class in others. Convenient for file.write isn't it?:

py2>> plaintext='my string literal'
py2>> type(plaintext)
str                              #is it a string or is it a byte array? it's both!

py2>> outfile.write(plaintext)   #can use plaintext as a byte array

Why did py3 break this nice system? Well because in py2 basic string functions didn't work for the rest of the world. Measure the length of a word with a non-ASCII character?

py2>> len('¡no')        #length of string=3, length of UTF-8 byte array=4, since with variable len encoding the non-ASCII chars = 2-6 bytes
4                       #always gives bytes.len not str.len

All this time you thought you were asking for the len of a string in py2, you were getting the length of the byte array from the encoding. That ambiguity is the fundamental problem with double-duty classes. Which version of any method call do you implement?

The good news then is that py3 fixes this problem. It disentangles the str and bytes classes. The str class has string-like methods, the separate bytes class has byte array methods:

py3>> len('¡ok')       #string
py3>> len('¡ok'.encode('utf-8'))     #bytes

Hopefully knowing this helps de-mystify the issue, and makes the migration pain a little easier to bear.

Automatically get loop index in foreach loop in Perl

Not with foreach.

If you definitely need the element cardinality in the array, use a 'for' iterator:

for ($i=0; $i<@x; ++$i) {
  print "Element at index $i is " , $x[$i] , "\n";

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I know this thread is old, but still answering it so that no-one else should spend sleepless nights.

I was refactoring an old project, whose layout files all contained hardcoded attributes such as android:maxLength = 500. So I decided to register it in my res/dimen file as <dimen name="max_length">500</dimen>.

Finished refactoring almost 30 layout files with my res-value. Guess what? the next time I ran my project it started throwing the same InflateException.

As a solution, needed to redo my all changes and keep all-those values as same as before.


step 1: All running good.

step 2: To boost my maintenance I replaced android:maxLength = 500 with <dimen name="max_length">500</dimen> and android:maxLength = @dimen/max_length , that's where it all went wrong(crashing with InflateException).

step 3: All running bad

step 4: Re-do all my work by again replacing android:maxLength = @dimen/max_length with android:maxLength = 500.Everything got fixed.

step 5: All running good.

Difference between a Seq and a List in Scala

In Scala, a List inherits from Seq, but implements Product; here is the proper definition of List :

sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...

[Note: the actual definition is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

Global events are also deprecated.

Here's a patch, which fixes the browser and event issues:

--- jquery.fancybox-1.3.4.js.orig   2010-11-11 23:31:54.000000000 +0100
+++ jquery.fancybox-1.3.4.js    2013-03-22 23:25:29.996796800 +0100
@@ -26,7 +26,9 @@

        titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }),

-       isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
+       isIE = !+"\v1",
+       isIE6 = isIE && window.XMLHttpRequest === undefined,

         * Private methods 
@@ -322,7 +324,7 @@

            if (":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
-               $.event.trigger('fancybox-cancel');
+               $('.fancybox-inline-tmp').trigger('fancybox-cancel');

                busy = false;
@@ -389,7 +391,7 @@
                        content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish);

-                   $.event.trigger('fancybox-change');
+                   $('.fancybox-inline-tmp').trigger('fancybox-change');

@@ -612,7 +614,7 @@

            if (currentOpts.type == 'iframe') {
-               $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
+               $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + (isIE ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);

@@ -912,7 +914,7 @@

        busy = true;

-       $.event.trigger('fancybox-cancel');
+       $('.fancybox-inline-tmp').trigger('fancybox-cancel');


@@ -957,7 +959,7 @@

-           $.event.trigger('fancybox-cleanup');
+           $('.fancybox-inline-tmp, select:not(#fancybox-tmp select)').trigger('fancybox-cleanup');


How can I trigger an onchange event manually?

For those using jQuery there's a convenient method:

Deserialize from string instead TextReader

1-liner, takes a XML string text and YourType as the expected object type. not very different from other answers, just compressed to 1 line:

var result =  (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

Date Difference in php on days?

strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$seconds_diff = $ts2 - $ts1;

Unpacking a list / tuple of pairs into two lists / tuples

>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')

Edit: Note that zip(*iterable) is its own inverse:

>>> list(source_list) == zip(*zip(*source_list))

When unpacking into two lists, this becomes:

>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)

Addition suggested by rocksportrocker.

Index (zero based) must be greater than or equal to zero

This can also happen when trying to throw an ArgumentException where you inadvertently call the ArgumentException constructor overload

public static void Dostuff(Foo bar)

   // this works
   throw new ArgumentException(String.Format("Could not find {0}", bar.SomeStringProperty));

   //this gives the error
   throw new ArgumentException(String.Format("Could not find {0}"), bar.SomeStringProperty);


How to remove a column from an existing table?

In SQL Server 2016 you can use new DIE statements.


The above query is re-runnable it drops the column only if it exists in the table else it will not throw error.

Instead of using big IF wrappers to check the existence of column before dropping it you can just run the above DDL statement

Python convert csv to xlsx

Simple 1-to-1 CSV to XLSX file conversion without enumerating/looping through the rows:

import pyexcel

sheet = pyexcel.get_sheet(file_name="myFile.csv", delimiter=",")


  1. I have found that if the file_name is really long (>30 characters excluding path) then the resultant XLSX file will throw an error when Excel tries to load it. Excel will offer to fix the error which it does, but it is frustrating.
  2. There is a great answer previously provided that combines all of the CSV files in a directory into one XLSX workbook, which fits a different use case than just trying to do a 1-to-1 CSV file to XLSX file conversion.

Reading file using fscanf() in C

First of all, you're testing fp twice. so printf("Error Reading File\n"); never gets executed.

Then, the output of fscanf should be equal to 2 since you're reading two values.


I'll also point out that using the older syntax is more subject to error. If you use inner joins without an ON clause, you will get a syntax error. If you use the older syntax and forget one of the join conditions in the where clause, you will get a cross join. The developers often fix this by adding the distinct keyword (rather than fixing the join because they still don't realize the join itself is broken) which may appear to cure the problem but will slow down the query considerably.

Additionally for maintenance if you have a cross join in the old syntax, how will the maintainer know if you meant to have one (there are situations where cross joins are needed) or if it was an accident that should be fixed?

Let me point you to this question to see why the implicit syntax is bad if you use left joins. Sybase *= to Ansi Standard with 2 different outer tables for same inner table

Plus (personal rant here), the standard using the explicit joins is over 20 years old, which means implicit join syntax has been outdated for those 20 years. Would you write application code using a syntax that has been outdated for 20 years? Why do you want to write database code that is?

changing visibility using javascript

If you just want to display it when you get a response add this to your loadpage()

function loadpage(page_request, containerid){
   if (page_request.readyState == 4 && page_request.status==200) { 
      var container = document.getElementById(containerid);
      container.innerHTML=page_request.responseText; = 'visible';
      // or = 'block';

but this depend entirely on how you hid the div in the first place

Uninstall mongoDB from ubuntu

To uninstalling existing MongoDB packages. I think this link will helpful.

Using % for host when creating a MySQL user

If you want connect to user@'%' from localhost use mysql -h192.168.0.1 -uuser -p.

Creating a folder if it does not exists - "Item already exists"

With New-Item you can add the Force parameter

New-Item -Force -ItemType directory -Path foo

Or the ErrorAction parameter

New-Item -ErrorAction Ignore -ItemType directory -Path foo

Remove an array element and shift the remaining ones

You just need to overwrite what you're deleting with the next value in the array, propagate that change, and then keep in mind where the new end is:

int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

// delete 3 (index 2)
for (int i = 2; i < 8; ++i)
    array[i] = array[i + 1]; // copy next element left

Now your array is {1, 2, 4, 5, 6, 7, 8, 9, 9}. You cannot delete the extra 9 since this is a statically-sized array, you just have to ignore it. This can be done with std::copy:

std::copy(array + 3, // copy everything starting here
          array + 9, // and ending here, not including it,
          array + 2) // to this destination

In C++11, use can use std::move (the algorithm overload, not the utility overload) instead.

More generally, use std::remove to remove elements matching a value:

// remove *all* 3's, return new ending (remaining elements unspecified)
auto arrayEnd = std::remove(std::begin(array), std::end(array), 3);

Even more generally, there is std::remove_if.

Note that the use of std::vector<int> may be more appropriate here, as its a "true" dynamically-allocated resizing array. (In the sense that asking for its size() reflects removed elements.)

Python conditional assignment operator

I am not sure I understand the question properly here ... Trying to "read" the value of an "undefined" variable name will trigger a NameError. (see here, that Python has "names", not variables...).

== EDIT ==

As pointed out in the comments by delnan, the code below is not robust and will break in numerous situations ...

Nevertheless, if your variable "exists", but has some sort of dummy value, like None, the following would work :

>>> my_possibly_None_value = None
>>> myval = my_possibly_None_value or 5
>>> myval
>>> my_possibly_None_value = 12
>>> myval = my_possibly_None_value or 5
>>> myval

(see this paragraph about Truth Values)

How to change option menu icon in the action bar?

this work for me, just set your xml menu like this:

<menu xmlns:android=""

                android:title="menu 1" />

                android:title="menu 2" />


How to convert strings into integers in Python?

Instead of putting int( ), put float( ) which will let you use decimals along with integers.

How to push files to an emulator instance using Android Studio

I am using Android Studio 3.3.

Go to View -> Tools Window -> Device File Explorer. Or you can find it on the Bottom Right corner of the Android Studio.

enter image description here

If the Emulator is running, the Device File Explorer will display the File structure on Emulator Storage.

enter image description here

Here you can right click on a Folder and select "Upload" to place the file

enter image description here

I usually use mnt - sdcard - download folder. Thanks.

How to set image to fit width of the page using jsPDF?

If you want a dynamic sized image to automatically fill the page as much as possible and still keep the image width/height-ratio, you could do as follows:

let width = doc.internal.pageSize.getWidth()
let height = doc.internal.pageSize.getHeight()

let widthRatio = width / canvas.width
let heightRatio = height / canvas.height

let ratio = widthRatio > heightRatio ? heightRatio : widthRatio

  canvas.toDataURL('image/jpeg', 1.0),
  canvas.width * ratio,
  canvas.height * ratio,

Why is this program erroneously rejected by three C++ compilers?

Your < and >, ( and ), { and } don't seem to match very well; Try drawing them better.

Rollback one specific migration in Laravel

better to used refresh migrate

You may rollback & re-migrate a limited number of migrations by providing the step option to the refresh command. For example, the following command will rollback & re-migrate the last two migrations:

php artisan migrate:refresh --step=2

otherwise used rollback migrate

You may rollback a limited number of migrations by providing the step option to the rollback command. For example, the following command will rollback the last three migrations:

php artisan migrate:rollback --step=3

for more detail about migration see

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.

Pretty-print a Map in Java

Or put your logic into a tidy little class.

public class PrettyPrintingMap<K, V> {
    private Map<K, V> map;

    public PrettyPrintingMap(Map<K, V> map) { = map;

    public String toString() {
        StringBuilder sb = new StringBuilder();
        Iterator<Entry<K, V>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<K, V> entry =;
            if (iter.hasNext()) {
                sb.append(',').append(' ');
        return sb.toString();



Map<String, String> myMap = new HashMap<String, String>();

System.out.println(new PrettyPrintingMap<String, String>(myMap));

Note: You can also put that logic into a utility method.

Python iterating through object attributes

You can use the standard Python idiom, vars():

for attr, value in vars(k).items():
    print(attr, '=', value)

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('', headers={'x-test2': 'true'})


How to get all the values of input array element jquery


function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];

Here is Demo.

How get data from material-ui TextField, DropDownMenu components?

The strategy of the accepted answer is correct, but here's a generalized example that works with the current version of React and Material-UI.

The flow of data should be one-way:

  • the initialState is initialized in the constructor of the MyForm control
  • the TextAreas are populated from this initial state
  • changes to the TextAreas are propagated to the state via the handleChange callback.
  • the state is accessed from the onClick callback---right now it just writes to the console. If you want to add validation it could go there.
import * as React from "react";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";

const initialState = {
    error: null, // you could put error messages here if you wanted
    person: {
        firstname: "",
        lastname: ""

export class MyForm extends React.Component {

    constructor(props) {
        this.state = initialState;
        // make sure the "this" variable keeps its scope
        this.handleChange = this.handleChange.bind(this);
        this.onClick = this.onClick.bind(this);

    render() {
        return (
                        floatingLabelText="First Name"
                        floatingLabelText="Last Name"
                    <RaisedButton onClick={this.onClick} label="Submit!" />

    onClick() {
        console.log("when clicking, the form data is:");

    handleChange(event, newValue): void {
        event.persist(); // allow native event access (see:
        // give react a function to set the state asynchronously.
        // here it's using the "name" value set on the TextField
        // to set state.person.[firstname|lastname].            
        this.setState((state) => state.person[] = newValue);



React.render(<MyForm />, document.getElementById('app'));

(Note: You may want to write one handleChange callback per MUI Component to eliminate that ugly event.persist() call.)

How to get current time with jQuery

Using JavaScript native Date functions you can get hours, minutes and seconds as you want. If you wish to format date and time in particular way you may want to implement a method extending JavaScript Date prototype.

Here is one already implemented:

how to use jQuery ajax calls with node.js

If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('_testcb(\'{"message": "Hello world!"}\')');

and client side JavaScript/jQuery:

$(document).ready(function() {
        url: '',
        dataType: "jsonp",
        jsonpCallback: "_testcb",
        cache: false,
        timeout: 5000,
        success: function(data) {
        error: function(jqXHR, textStatus, errorThrown) {
            alert('error ' + textStatus + " " + errorThrown);

There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
success: function (data) {

JavaScript: How to pass object by value?

Actually, Javascript is always pass by value. But because object references are values, objects will behave like they are passed by reference.

So in order to walk around this, stringify the object and parse it back, both using JSON. See example of code below:

var person = { Name: 'John', Age: '21', Gender: 'Male' };

var holder = JSON.stringify(person);
// value of holder is "{"Name":"John","Age":"21","Gender":"Male"}"
// note that holder is a new string object

var person_copy = JSON.parse(holder);
// value of person_copy is { Name: 'John', Age: '21', Gender: 'Male' };
// person and person_copy now have the same properties and data
// but are referencing two different objects

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.


You should be able to do this by checking the value of $_SERVER['HTTPS'] (it should only be set when using https).


How can I configure my makefile for debug and release builds?

This question has appeared often when searching for a similar problem, so I feel a fully implemented solution is warranted. Especially since I (and I would assume others) have struggled piecing all the various answers together.

Below is a sample Makefile which supports multiple build types in separate directories. The example illustrated shows debug and release builds.

Supports ...

  • separate project directories for specific builds
  • easy selection of a default target build
  • silent prep target to create directories needed for building the project
  • build-specific compiler configuration flags
  • GNU Make's natural method of determining if project requires a rebuild
  • pattern rules rather than the obsolete suffix rules

# Compiler flags
CC     = gcc
CFLAGS = -Wall -Werror -Wextra

# Project files
SRCS = file1.c file2.c file3.c file4.c
OBJS = $(SRCS:.c=.o)
EXE  = exefile

# Debug build settings
DBGDIR = debug
DBGOBJS = $(addprefix $(DBGDIR)/, $(OBJS))

# Release build settings
RELDIR = release
RELOBJS = $(addprefix $(RELDIR)/, $(OBJS))

.PHONY: all clean debug prep release remake

# Default build
all: prep release

# Debug rules
debug: $(DBGEXE)

    $(CC) $(CFLAGS) $(DBGCFLAGS) -o $(DBGEXE) $^

$(DBGDIR)/%.o: %.c
    $(CC) -c $(CFLAGS) $(DBGCFLAGS) -o $@ $<

# Release rules
release: $(RELEXE)

    $(CC) $(CFLAGS) $(RELCFLAGS) -o $(RELEXE) $^

$(RELDIR)/%.o: %.c
    $(CC) -c $(CFLAGS) $(RELCFLAGS) -o $@ $<

# Other rules
    @mkdir -p $(DBGDIR) $(RELDIR)

remake: clean all


Convert array of integers to comma-separated string

int[] arr = new int[5] {1,2,3,4,5};

You can use Linq for it

String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);

Best way to compare dates in Android

Kotlin supports operators overloading

In Kotlin you can easily compare dates with compare operators. Because Kotlin already support operators overloading. So to compare date objects :

firstDate: Date = // your first date
secondDate: Date = // your second date

if(firstDate < secondDate){
// fist date is before second date

and if you're using calendar objects, you can easily compare like this:

if(cal1.time < cal2.time){
// cal1 date is before cal2 date

ASP.NET Web Site or ASP.NET Web Application?

To summarize some of the answers above:

Flexibility, can you can make live changes to a web page?

Web Site: Possible. Pro: short term benefits. Con: long term risk of project chaos.

Web App: Con: not possible. Edit a page, archive the changes to source control, then build and deploy the entire site. Pro: maintain a quality project.

Development issues

Web Site: Simple project structure without a .csproj file.Two .aspx pages may have the same class name without conflicts. Random project directory name leading to build errors like why .net framework conflicts with its own generated file and why .net framework conflicts with its own generated file. Pro: Simple (simplistic). Con: erratic.

Web App: Project structure similar to WebForms project, with a .csproj file. Class names of asp pages must be unique. Pro: Simple (smart). Con: none, because a web app is still simple.

Converting Symbols, Accent Letters to English Alphabet

Following Class does the trick:


What's the difference between Unicode and UTF-8?

UTF-16 and UTF-8 are both encodings of Unicode. They are both Unicode; one is not more Unicode than the other.

Don't let an unfortunate historical artifact from Microsoft confuse you.

How do I install TensorFlow's tensorboard?

Adding this just for the sake of completeness of this question (some questions may get closed as duplicate of this one).

I usually use user mode for pip ie. pip install --user even if instructions assume root mode. That way, my tensorboard installation was in ~/.local/bin/tensorboard, and it was not in my path (which shouldn't be ideal either). So I was not able to access it.

In this case, running

sudo ln -s ~/.local/bin/tensorboard /usr/bin

should fix it.

How do I handle newlines in JSON?



would convert the above string to

"{ \n      a:\"a\"\n    }"

as mentioned here

json stringify

This function adds double quotes at the beginning and end of the input string and escapes special JSON characters. In particular, a newline is replaced by the \n character, a tab is replaced by the \t character, a backslash is replaced by two backslashes \, and a backslash is placed before each quotation mark.

How can I remove an entry in global configuration with git config?

git config information will stored in ~/.gitconfig in unix platform.

In Windows it will be stored in C:/users/<NAME>/.gitconfig.

You can edit it manually by opening this files and deleting the fields which you are interested.

Reading from text file until EOF repeats last line

int x;
ifile >> x

while (!iFile.eof())
    cerr << x << endl;        
    iFile >> x;      

vertical divider between two columns in bootstrap

If your code looks like this:

<div class="row">
  <div class="span6">
  <div class="span6">

Then I'd assume you're using additional DIVS within the "span6" DIVS for holding/styling your content? So...

<div class="row">
  <div class="span6">
    <div class="mycontent-left">
  <div class="span6">
    <div class="mycontent-right">

So you could simply add some CSS to the "mycontent-left" class to create your divider.

.mycontent-left {
  border-right: 1px dashed #333;

Why am I getting an OPTIONS request instead of a GET request?

I don't believe jQuery will just naturally do a JSONP request when given a URL like that. It will, however, do a JSONP request when you tell it what argument to use for a callback:

$.get("", function(data) {

It's entirely up to the receiving script to make use of that argument (which doesn't have to be called "jsoncallback"), so in this case the function will never be called. But, since you stated you just want the script at to execute, that would make it.

How to remove item from list in C#?

    class Program
        public static List<Product> list;
        static void Main(string[] args)

            list = new List<Product>() { new Product() { ProductId=1, Name="Nike 12N0",Brand="Nike",Price=12000,Quantity=50},
                 new Product() { ProductId =2, Name = "Puma 560K", Brand = "Puma", Price = 120000, Quantity = 55 },
                 new Product() { ProductId=3, Name="WoodLand V2",Brand="WoodLand",Price=21020,Quantity=25},
                 new Product() { ProductId=4, Name="Adidas S52",Brand="Adidas",Price=20000,Quantity=35},
                 new Product() { ProductId=5, Name="Rebook SPEED2O",Brand="Rebook",Price=1200,Quantity=15}};

            Console.WriteLine("Enter ProductID to remove");
            int uno = Convert.ToInt32(Console.ReadLine());
            var itemToRemove = list.Find(r => r.ProductId == uno);
            if (itemToRemove != null)
            Console.WriteLine($"{itemToRemove.ProductId}{itemToRemove.Name}{itemToRemove.Brand}{itemToRemove.Price}{ itemToRemove.Quantity}");
            Console.WriteLine("------------sucessfully Removed---------------");

            var query2 = from x in list select x;
            foreach (var item in query2)
                /*Console.WriteLine(item.ProductId+" "+item.Name+" "+item.Brand+" "+item.Price+" "+item.Quantity );*/
                Console.WriteLine($"{item.ProductId}{item.Name}{item.Brand}{item.Price}{ item.Quantity}");



Shell script to capture Process ID and kill it if exist

Came across somewhere..thought it is simple and useful

You can use the command in crontab directly ,

* * * * * ps -lf | grep "user" |  perl -ane '($h,$m,$s) = split /:/,$F
+[13]; kill 9, $F[3] if ($h > 1);'

or, we can write it as shell script ,

ps -lf | grep "user" |  perl -ane '($h,$m,$s) = split /:/,$F[13]; kill
+ 9, $F[3] if ($h > 1);'

And call it crontab like so,

* * * * *

What is the Record type in typescript?

A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.

For example, say I have a Union like this:

type CatNames = "miffy" | "boris" | "mordred";

Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.

type CatList = Record<CatNames, {age: number}>

If I want to satisfy this CatList, I must create an object like this:

const cats:CatList = {
  miffy: { age:99 },
  boris: { age:16 },
  mordred: { age:600 }

You get very strong type safety:

  • If I forget a cat, I get an error.
  • If I add a cat that's not allowed, I get an error.
  • If I later change CatNames, I get an error. This is especially useful because CatNames is likely imported from another file, and likely used in many places.

Real-world React example.

I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes

I had a union like this:

type Statuses = "failed" | "complete";

I used this to create an object like this:

const icons: Record<
  { iconType: IconTypes; iconColor: IconColors }
> = {
  failed: {
    iconType: "warning",
    iconColor: "red"
  complete: {
    iconType: "check",
    iconColor: "green"

I could then render by destructuring an element from the object into props, like so:

const Status = ({status}) => <Icon {...icons[status]} />

If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.

Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

How to Call Controller Actions using JQuery in ASP.NET MVC

the previous response is ASP.NET only

you need a reference to jquery (perhaps from a CDN):

and then a similar block of code but simpler...

$.ajax({ url: '/Controller/Action/Id',
         success: function(data) { alert(data); }, 
         statusCode : {
             404: function(content) { alert('cannot find resource'); },
             500: function(content) { alert('internal server error'); }
         error: function(req, status, errorObj) {
               // handle status === "timeout"
               // handle other errors

I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

Verilog generate/genvar in an always block

Within a module, Verilog contains essentially two constructs: items and statements. Statements are always found in procedural contexts, which include anything in between begin..end, functions, tasks, always blocks and initial blocks. Items, such as generate constructs, are listed directly in the module. For loops and most variable/constant declarations can exist in both contexts.

In your code, it appears that you want the for loop to be evaluated as a generate item but the loop is actually part of the procedural context of the always block. For a for loop to be treated as a generate loop it must be in the module context. The generate..endgenerate keywords are entirely optional(some tools require them) and have no effect. See this answer for an example of how generate loops are evaluated.

//Compiler sees this
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
genvar c;

    always @(posedge sysclk) //Procedural context starts here
        for (c = 0; c < ROWBITS; c = c + 1) begin: test
            temp[c] <= 1'b0; //Still a genvar

how to evenly distribute elements in a div next to each other?

You just need to display the div with id #menu as flex container like this:

    width: 800px;
    display: flex;
    justify-content: space-between;

How do I integrate Ajax with Django applications?

Simple and Nice. You don't have to change your views. Bjax handles all your links. Check this out: Bjax


<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />

Finally, include this in the HEAD of your html:


For more settings, checkout demo here: Bjax Demo

Alter column, add default constraint

Try this

alter table TableName 
 add constraint df_ConstraintNAme 
 default getutcdate() for [Date]


create table bla (id int)

alter table bla add constraint dt_bla default 1 for id

insert bla default values

select * from bla

also make sure you name the default will be a pain in the neck to drop it later because it will have one of those crazy system generated names...see also How To Name Default Constraints And How To Drop Default Constraint Without A Name In SQL Server

subquery in FROM must have an alias

In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

This is usually caused by your CSV having been saved along with an (unnamed) index (RangeIndex).

(The fix would actually need to be done when saving the DataFrame, but this isn't always an option.)

Workaround: read_csv with index_col=[0] argument

IMO, the simplest solution would be to read the unnamed column as the index. Specify an index_col=[0] argument to pd.read_csv, this reads in the first column as the index. (Note the square brackets).

df = pd.DataFrame('x', index=range(5), columns=list('abc'))

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

# Save DataFrame to CSV.

<!- ->


   Unnamed: 0  a  b  c
0           0  x  x  x
1           1  x  x  x
2           2  x  x  x
3           3  x  x  x
4           4  x  x  x

# Now try this again, with the extra argument.
pd.read_csv('file.csv', index_col=[0])

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

You could have avoided this in the first place by using index=False if the output CSV was created in pandas, if your DataFrame does not have an index to begin with:

df.to_csv('file.csv', index=False)

But as mentioned above, this isn't always an option.

Stopgap Solution: Filtering with str.match

If you cannot modify the code to read/write the CSV file, you can just remove the column by filtering with str.match:


   Unnamed: 0  a  b  c
0           0  x  x  x
1           1  x  x  x
2           2  x  x  x
3           3  x  x  x
4           4  x  x  x

# Index(['Unnamed: 0', 'a', 'b', 'c'], dtype='object')

# array([ True, False, False, False])

df.loc[:, ~df.columns.str.match('Unnamed')]
   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

Change arrow colors in Bootstraps carousel

In bootstrap 4 if you are just changing the colour of the controls you can use the sass variables, typically in custom.scss:

$carousel-control-color: #7b277d;

As highlighted in this github issue note:

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

in pure Ruby:

{:a => 1, :b => 2}.tap{|x| x.delete(:a)}   # => {:b=>2}

Reading column names alone in a csv file

here is the code to print only the headers or columns of the csv file.

import csv
HEADERS = next(csv.reader(open('filepath.csv')))
print (HEADERS)

Another method with pandas

import pandas as pd
HEADERS = list(pd.read_csv('filepath.csv').head(0))
print (HEADERS)

Setting the classpath in java using Eclipse IDE

Just had the same issue, for those having the same one it may be that you put the library on the modulepath rather than the classpath while adding it to your project

How do I sort strings alphabetically while accounting for value when a string is numeric?

Even though this is an old question, I'd like to give a solution:

string[] things= new string[] { "105", "101", "102", "103", "90" };

foreach (var thing in things.OrderBy(x => Int32.Parse(x) )

Woha quite simple right? :D

Meaning of @classmethod and @staticmethod for beginner?

Rostyslav Dzinko's answer is very appropriate. I thought I could highlight one other reason you should choose @classmethod over @staticmethod when you are creating an additional constructor.

In the example above, Rostyslav used the @classmethod from_string as a Factory to create Date objects from otherwise unacceptable parameters. The same can be done with @staticmethod as is shown in the code below:

class Date:
  def __init__(self, month, day, year):
    self.month = month   = day
    self.year  = year

  def display(self):
    return "{0}-{1}-{2}".format(self.month,, self.year)

  def millenium(month, day):
    return Date(month, day, 2000)

new_year = Date(1, 1, 2013)               # Creates a new Date object
millenium_new_year = Date.millenium(1, 1) # also creates a Date object. 

# Proof:
new_year.display()           # "1-1-2013"
millenium_new_year.display() # "1-1-2000"

isinstance(new_year, Date) # True
isinstance(millenium_new_year, Date) # True

Thus both new_year and millenium_new_year are instances of the Date class.

But, if you observe closely, the Factory process is hard-coded to create Date objects no matter what. What this means is that even if the Date class is subclassed, the subclasses will still create plain Date objects (without any properties of the subclass). See that in the example below:

class DateTime(Date):
  def display(self):
      return "{0}-{1}-{2} - 00:00:00PM".format(self.month,, self.year)

datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)

isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # False

datetime1.display() # returns "10-10-1990 - 00:00:00PM"
datetime2.display() # returns "10-10-2000" because it's not a DateTime object but a Date object. Check the implementation of the millenium method on the Date class for more details.

datetime2 is not an instance of DateTime? WTF? Well, that's because of the @staticmethod decorator used.

In most cases, this is undesired. If what you want is a Factory method that is aware of the class that called it, then @classmethod is what you need.

Rewriting Date.millenium as (that's the only part of the above code that changes):

def millenium(cls, month, day):
    return cls(month, day, 2000)

ensures that the class is not hard-coded but rather learnt. cls can be any subclass. The resulting object will rightly be an instance of cls.
Let's test that out:

datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)

isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # True

datetime1.display() # "10-10-1990 - 00:00:00PM"
datetime2.display() # "10-10-2000 - 00:00:00PM"

The reason is, as you know by now, that @classmethod was used instead of @staticmethod

Render HTML to an image

May I recommend dom-to-image library, that was written solely to address this problem (I'm the maintainer).
Here is how you use it (some more here):

var node = document.getElementById('my-node');

    .then (function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
    .catch(function (error) {
        console.error('oops, something went wrong!', error);

How to compare numbers in bash?

The bracket stuff (e.g., [[ $a -gt $b ]] or (( $a > $b )) ) isn't enough if you want to use float numbers as well; it would report a syntax error. If you want to compare float numbers or float number to integer, you can use (( $(bc <<< "...") )).

For example,


if (( $(bc <<<"$a > $b") )); then 
    echo "a is greater than b"
    echo "a is not greater than b"

You can include more than one comparison in the if statement. For example,


if (( $(bc <<<"$b == $c && $b < $a") )); then 
    echo "b is equal to c but less than a"
    echo "b is either not equal to c and/or not less than a"

That's helpful if you want to check if a numeric variable (integer or not) is within a numeric range.

Float a div right, without impacting on design

Try setting its position to absolute. That takes it out of the flow of the document.

Using Case/Switch and GetType to determine the object

I actually prefer the approach given as the answer here: Is there a better alternative than this to 'switch on type'?

There is however a good argument about not implementing any type comparison methids in an object oriented language like C#. You could as an alternative extend and add extra required functionality using inheritance.

This point was discussed in the comments of the authors blog here:

I found this an extremely interesting point which changed my approach in a similar situation and only hope this helps others.

Kind Regards, Wayne

Filename too long in Git for Windows

In a windows Machine

Run Command Prompt as administrator then run below command

git config --system core.longpaths true

JQuery / JavaScript - trigger button click from another button click event

this works fine, but file name does not display anymore.

$(document).ready(function(){ $("img.attach2").click(function(){ $("input.attach1").click(); return false; }); });

Getting HTTP headers with Node.js

Try to look at http.get and response headers.

var http = require("http");

var options = {
  host: '',
  port: 80,
  path: '/'

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);

  for(var item in res.headers) {
    console.log(item + ": " + res.headers[item]);
}).on('error', function(e) {
  console.log("Got error: " + e.message);

Multiline string literal in C#

It's called a verbatim string literal in C#, and it's just a matter of putting @ before the literal. Not only does this allow multiple lines, but it also turns off escaping. So for example you can do:

string query = @"SELECT foo, bar
FROM table
WHERE name = 'a\b'";

This includes the line breaks (using whatever line break your source has them as) into the string, however. For SQL, that's not only harmless but probably improves the readability anywhere you see the string - but in other places it may not be required, in which case you'd either need to not use a multi-line verbatim string literal to start with, or remove them from the resulting string.

The only bit of escaping is that if you want a double quote, you have to add an extra double quote symbol:

string quote = @"Jon said, ""This will work,"" - and it did!";

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).


At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided -

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) -

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

This can also happen if you use Windows for the Git checkout, and the Podfile.lock is created with windows (CRLF) line endings.

Convert a object into JSON in REST service by Spring MVC

Another simple solution is to add jackson-databind dependency in POM.


Keep Rest of the code as it is.

How do I open a second window from the first window in WPF?

Write your code in window1.

private void Button_Click(object sender, RoutedEventArgs e)
    window2 win2 = new window2();

How to get data from database in javascript based on the value passed to the function

The error is coming as your query is getting formed as

SELECT * FROM Employ where number = parseInt(val);

I dont know which DB you are using but no DB will understand parseInt.

What you can do is use a variable say temp and store the value of parseInt(val) in temp variable and make the query as

SELECT * FROM Employ where number = temp;

How do I query for all dates greater than a certain date in SQL Server?

To sum it all up, the correct answer is :

select * from db where Date >= '20100401'  (Format of date yyyymmdd)

This will avoid any problem with other language systems and will use the index.

Concatenate strings from several rows using Pandas groupby

For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:

df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()

PHP: check if any posted vars are empty - form: all fields required

I did it like this:

$missing = array();
 foreach ($_POST as $key => $value) { if ($value == "") { array_push($missing, $key);}}
 if (count($missing) > 0) {
  echo "Required fields found empty: ";
  foreach ($missing as $k => $v) { echo $v." ";}
  } else {
  // do your stuff here with the $_POST

What is a Windows Handle?

So at the most basic level a HANDLE of any sort is a pointer to a pointer or

#define HANDLE void **

Now as to why you would want to use it

Lets take a setup:

class Object{
   int Value;

class LargeObj{

   char * val;
      val = malloc(2048 * 1000);


void foo(Object bar){
    LargeObj lo = new LargeObj();

void main()
   Object obj = new Object();
   obj.val = 1;
   printf("%d", obj.val);

So because obj was passed by value (make a copy and give that to the function) to foo, the printf will print the original value of 1.

Now if we update foo to:

void foo(Object * bar)
    LargeObj lo = new LargeObj();

There is a chance that the printf will print the updated value of 2. But there is also the possibility that foo will cause some form of memory corruption or exception.

The reason is this while you are now using a pointer to pass obj to the function you are also allocating 2 Megs of memory, this could cause the OS to move the memory around updating the location of obj. Since you have passed the pointer by value, if obj gets moved then the OS updates the pointer but not the copy in the function and potentially causing problems.

A final update to foo of:

void foo(Object **bar){
    LargeObj lo = LargeObj();
    Object * b = &bar;

This will always print the updated value.

See, when the compiler allocates memory for pointers it marks them as immovable, so any re-shuffling of memory caused by the large object being allocated the value passed to the function will point to the correct address to find out the final location in memory to update.

Any particular types of HANDLEs (hWnd, FILE, etc) are domain specific and point to a certain type of structure to protect against memory corruption.

Insert a row to pandas dataframe

You can simply append the row to the end of the DataFrame, and then adjust the index.

For instance:

df = df.append(pd.DataFrame([[2,3,4]],columns=df.columns),ignore_index=True)
df.index = (df.index + 1) % len(df)
df = df.sort_index()

Or use concat as:

df = pd.concat([pd.DataFrame([[1,2,3,4,5,6]],columns=df.columns),df],ignore_index=True)

How to state in requirements.txt a direct github source

Normally your requirements.txt file would look something like this:


To specify a Github repo, you do not need the package-name== convention.

The examples below update package-two using a GitHub repo. The text between @ and # denotes the specifics of the package.

Specify commit hash (41b95ec in the context of updated requirements.txt):


Specify branch name (master):


Specify tag (0.1):

git+git://[email protected]#egg=package-two

Specify release (3.7.1):


Note that #egg=package-two is not a comment here, it is to explicitly state the package name

This blog post has some more discussion on the topic.

Client on Node.js: Uncaught ReferenceError: require is not defined

I confirm. We must add:

webPreferences: {
    nodeIntegration: true

For example:

mainWindow = new BrowserWindow({webPreferences: {
    nodeIntegration: true

For me, the problem has been resolved with that.

Get time difference between two dates in seconds

You can use new Date().getTime() for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms into s.

const start = new Date().getTime();
const end = new Date().getTime();

const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);

How to check Django version

Type the following command in Python shell

import django

How to find all combinations of coins when given some dollar value

# short and sweet with O(n) table memory    

#include <iostream>
#include <vector>

int count( std::vector<int> s, int n )
  std::vector<int> table(n+1,0);

  table[0] = 1;
  for ( auto& k : s )
    for(int j=k; j<=n; ++j)
      table[j] += table[j-k];

  return table[n];

int main()
  std::cout <<  count({25, 10, 5, 1}, 100) << std::endl;
  return 0;

Changing factor levels with dplyr mutate

Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be

df <- iris %>%
  mutate(Species = recode(Species, 
     setosa = "SETOSA",
     versicolor = "VERSICOLOR",
     virginica = "VIRGINICA")

How to open the second form?

On any click event (or other one):

Form2 frm2 = new Form2();

C: How to free nodes in the linked list?

struct node{
    int position;
    char name[30];
    struct node * next;

void free_list(node * list){
    node* next_node;

    printf("\n\n Freeing List: \n");
    while(list != NULL)
        next_node = list->next;
        printf("clear mem for: %s",list->name);
        list = next_node;

Bootstrap visible and hidden classes not working properly

Your mobile class Isn't correct:

.mobile {
  display: none !important;
  visibility: hidden !important; //This is what's keeping the div from showing, remove this.

Exit/save edit to sudoers file? Putty SSH

To make changes to sudo from putty/bash:

  • Type visudo and press enter.
  • Navigate to the place you wish to edit using the up and down arrow keys.
  • Press insert to go into editing mode.
  • Make your changes - for example: user ALL=(ALL) ALL.
  • Note - it matters whether you use tabs or spaces when making changes.
  • Once your changes are done press esc to exit editing mode.
  • Now type :wq to save and press enter.
  • You should now be back at bash.
  • Now you can press ctrl + D to exit the session if you wish.

How to remove part of a string?

assuming 11223344 is not constant

$string="REGISTER 11223344 here";
$s = explode(" ",$string);
$s = implode(" ",$s);
print "$s\n";