Programs & Examples On #Virtual address space

NSString with \n or line break

\n is the preferred way to break a line. \r will work too. \n\r or \r\n are overkill and may cause you issues later. Cocoa, has specific paragraph and line break characters for specific uses NSParagraphSeparatorCharacter, NSLineSeparatorCharacter. Here is my source for all the above.

How to get full path of a file?

This is naive, but I had to make it to be POSIX compliant. Requires permission to cd into the file's directory.

#!/bin/sh
if [ ${#} = 0 ]; then
  echo "Error: 0 args. need 1" >&2
  exit 1
fi


if [ -d ${1} ]; then


  # Directory


  base=$( cd ${1}; echo ${PWD##*/} )
  dir=$( cd ${1}; echo ${PWD%${base}} )

  if [ ${dir} = / ]; then
    parentPath=${dir}
  else
    parentPath=${dir%/}
  fi

  if [ -z ${base} ] || [ -z ${parentPath} ]; then
    if [ -n ${1} ]; then
      fullPath=$( cd ${1}; echo ${PWD} )
    else
      echo "Error: unsupported scenario 1" >&2
      exit 1
    fi
  fi

elif [ ${1%/*} = ${1} ]; then

  if [ -f ./${1} ]; then


    # File in current directory

    base=$( echo ${1##*/} )
    parentPath=$( echo ${PWD} )

  else
    echo "Error: unsupported scenario 2" >&2
    exit 1
  fi
elif [ -f ${1} ] && [ -d ${1%/*} ]; then


  # File in directory

  base=$( echo ${1##*/} )
  parentPath=$( cd ${1%/*}; echo ${PWD} )

else
  echo "Error: not file or directory" >&2
  exit 1
fi

if [ ${parentPath} = / ]; then
  fullPath=${fullPath:-${parentPath}${base}}
fi

fullPath=${fullPath:-${parentPath}/${base}}

if [ ! -e ${fullPath} ]; then
  echo "Error: does not exist" >&2
  exit 1
fi

echo ${fullPath}

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

How to apply style classes to td classes?

Give the table a class name and then you target the td's with the following:

table.classname td {
    font-size: 90%;
}

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

After MySQL install via Brew, I get the error - The server quit without updating PID file

I found that it was a permissions issue with the mysql folder.

chmod -R 777 /usr/local/var/mysql/ 

solved it for me.

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
    //Your stuff
});

How to create a new figure in MATLAB?

While doing "figure(1), figure(2),..." will solve the problem in most cases, it will not solve them in all cases. Suppose you have a bunch of MATLAB figures on your desktop and how many you have open varies from time to time before you run your code. Using the answers provided, you will overwrite these figures, which you may not want. The easy workaround is to just use the command "figure" before you plot.

Example: you have five figures on your desktop from a previous script you ran and you use

figure(1);
plot(...)

figure(2);
plot(...)

You just plotted over the figures on your desktop. However the code

figure;
plot(...)

figure;
plot(...)

just created figures 6 and 7 with your desired plots and left your previous plots 1-5 alone.

Jquery in React is not defined

Try add jQuery to your project, like

npm i jquery --save

or if you use bower

bower i jquery --save

then

import $ from 'jquery'; 

Scatter plots in Pandas/Pyplot: How to plot by category

This is simple to do with Seaborn (pip install seaborn) as a oneliner

sns.scatterplot(x_vars="one", y_vars="two", data=df, hue="key1") :

import seaborn as sns
import pandas as pd
import numpy as np
np.random.seed(1974)

df = pd.DataFrame(
    np.random.normal(10, 1, 30).reshape(10, 3),
    index=pd.date_range('2010-01-01', freq='M', periods=10),
    columns=('one', 'two', 'three'))
df['key1'] = (4, 4, 4, 6, 6, 6, 8, 8, 8, 8)

sns.scatterplot(x="one", y="two", data=df, hue="key1")

enter image description here

Here is the dataframe for reference:

enter image description here

Since you have three variable columns in your data, you may want to plot all pairwise dimensions with:

sns.pairplot(vars=["one","two","three"], data=df, hue="key1")

enter image description here

https://rasbt.github.io/mlxtend/user_guide/plotting/category_scatter/ is another option.

JQuery window scrolling event?

Check if the user has scrolled past the header ad, then display the footer ad.

if($(your header ad).position().top < 0) { $(your footer ad).show() }

Am I correct at what you are looking for?

How to pass parameter to a promise function

Wrap your Promise inside a function or it will start to do its job right away. Plus, you can pass parameters to the function:

var some_function = function(username, password)
{
 return new Promise(function(resolve, reject)
 {
  /*stuff using username, password*/
  if ( /* everything turned out fine */ )
  {
   resolve("Stuff worked!");
  }
  else
  {
   reject(Error("It broke"));
  }
 });
}

Then, use it:

some_module.some_function(username, password).then(function(uid)
{
 // stuff
})

 

ES6:

const some_function = (username, password) =>
{
 return new Promise((resolve, reject) =>
 {
  /*stuff using username, password*/

  if ( /* everything turned out fine */ )
  {
   resolve("Stuff worked!");
  }
  else
  {
   reject(Error("It broke"));
  }
 });
};

Use:

some_module.some_function(username, password).then(uid =>
{
 // stuff
});

Can we import XML file into another XML file?

The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:

Per http://msdn.microsoft.com/en-us/library/aa302291.aspx

Why XInclude?

The first question one may ask is "Why use XInclude instead of XML external entities?" The answer is that XML external entities have a number of well-known limitations and inconvenient implications, which effectively prevent them from being a general-purpose inclusion facility. Specifically:

  • An XML external entity cannot be a full-blown independent XML document—neither standalone XML declaration nor Doctype declaration is allowed. That effectively means an XML external entity itself cannot include other external entities.
  • An XML external entity must be well formed XML (not so bad at first glance, but imagine you want to include sample C# code into your XML document).
  • Failure to load an external entity is a fatal error; any recovery is strictly forbidden.
  • Only the whole external entity may be included, there is no way to include only a portion of a document. -External entities must be declared in a DTD or an internal subset. This opens a Pandora's Box full of implications, such as the fact that the document element must be named in Doctype declaration and that validating readers may require that the full content model of the document be defined in DTD among others.

The deficiencies of using XML external entities as an inclusion mechanism have been known for some time and in fact spawned the submission of the XML Inclusion Proposal to the W3C in 1999 by Microsoft and IBM. The proposal defined a processing model and syntax for a general-purpose XML inclusion facility.

Four years later, version 1.0 of the XML Inclusions, also known as Xinclude, is a Candidate Recommendation, which means that the W3C believes that it has been widely reviewed and satisfies the basic technical problems it set out to solve, but is not yet a full recommendation.

Another good site which provides a variety of example implementations is https://www.xml.com/pub/a/2002/07/31/xinclude.html. Below is a common use case example from their site:

<book xmlns:xi="http://www.w3.org/2001/XInclude">

  <title>The Wit and Wisdom of George W. Bush</title>

  <xi:include href="malapropisms.xml"/>

  <xi:include href="mispronunciations.xml"/>

  <xi:include href="madeupwords.xml"/>

</book>

Use dynamic variable names in JavaScript

Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).

So if you create variables like this:

var a = 1,
    b = 2,
    c = 3;

In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).

Those can get accessed by using the "dot" or "bracket" notation:

var name = window.a;

or

var name = window['a'];

This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:

function foobar() {
   this.a = 1;
   this.b = 2;

   var name = window['a']; // === undefined
   alert(name);
   name = this['a']; // === 1
   alert(name);
}

new foobar();

new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:

var a = 1,
    b = 2;

Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).

Is there a difference between /\s/g and /\s+/g?

+ means "one or more characters" and without the plus it means "one character." In your case both result in the same output.

raw_input function in Python

It presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user and returns the data input by the user in a string. See the docs for raw_input().

Example:

name = raw_input("What is your name? ")
print "Hello, %s." % name

This differs from input() in that the latter tries to interpret the input given by the user; it is usually best to avoid input() and to stick with raw_input() and custom parsing/conversion code.

Note: This is for Python 2.x

Aggregate a dataframe on a given column and display another column

A late answer, but and approach using data.table

library(data.table)
DT <- data.table(dat)

DT[, .SD[which.max(Score),], by = Group]

Or, if it is possible to have more than one equally highest score

DT[, .SD[which(Score == max(Score)),], by = Group]

Noting that (from ?data.table

.SD is a data.table containing the Subset of x's Data for each group, excluding the group column(s)

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

I suggest you do some experiments using "make". Here is a simple demo, showing the difference between = and :=.

/* Filename: Makefile*/
x := foo
y := $(x) bar
x := later

a = foo
b = $(a) bar
a = later

test:
    @echo x - $(x)
    @echo y - $(y)
    @echo a - $(a)
    @echo b - $(b)

make test prints:

x - later
y - foo bar
a - later
b - later bar

Check more elaborate explanation here

invalid types 'int[int]' for array subscript

You're trying to access a 3 dimensional array with 4 de-references

You only need 3 loops instead of 4, or int myArray[10][10][10][10];

excel plot against a date time x series

Try using an X-Y Scatter graph with datetime formatted as YYYY-MM-DD HH:MM.

This provides a reasonable graph for me (using Excel 2010).

Excel Datetime XY Scatter

MySQL root access from all hosts

Update the bind-address = 0.0.0.0 in the /etc/mysql/mysql.conf.d/mysqld.cnf and from the mysql command line allow the root user to connect from any Ip.

Below was the only commands worked for mysql-8.0 as other were failing with error syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'abcd'' at line 1

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
UPDATE mysql.user SET host='%' WHERE user='root';

Restart the mysql client

sudo service mysql restart

jQuery: set selected value of dropdown list?

UPDATED ANSWER:

Old answer, correct method nowadays is to use jQuery's .prop(). IE, element.prop("selected", true)

OLD ANSWER:

Use this instead:

$("#routetype option[value='quietest']").attr("selected", "selected");

Fiddle'd: http://jsfiddle.net/x3UyB/4/

T-SQL Format integer to 2-digit string

select right ('00'+ltrim(str( <number> )),2 )

How do I write the 'cd' command in a makefile?

Here is the pattern I've used:

.PHONY: test_py_utils
PY_UTILS_DIR = py_utils
test_py_utils:
    cd $(PY_UTILS_DIR) && black .
    cd $(PY_UTILS_DIR) && isort .
    cd $(PY_UTILS_DIR) && mypy .
    cd $(PY_UTILS_DIR) && pytest -sl .
    cd $(PY_UTILS_DIR) && flake8 .

My motivations for this pattern are:

  • The above solution is simple and readable
  • I read the classic paper "Recursive Make Considered Harmful", which discouraged me from using $(MAKE) -C some_dir all
  • I didn't want to use just one line of code (punctuated by semicolons or &&) because it is less readable, and I fear that I will make a typo when editing the make recipe.
  • I didn't want to use the .ONESHELL special target because:
    • that is a global option that affects all recipes in the makefile
    • using .ONESHELL causes all lines of the recipe to be executed even if one of the earlier lines has failed with a nonzero exit status. Workarounds like calling set -e are possible, but such workarounds would have to be implemented for every recipe in the makefile.

pip broke. how to fix DistributionNotFound error?

I was able to resolve this like so:

$ brew update
$ brew doctor
$ brew uninstall python
$ brew install python --build-from-source    # took ~5 mins
$ python --version                           # => Python 2.7.9
$ pip install --upgrade pip

I'm running w/ the following stuff (as of Jan 2, 2015):

OS X Yosemite
Version 10.10.1

$ brew -v
Homebrew 0.9.5

$ python --version
Python 2.7.9

$ ipython --version
2.2.0

$ pip --version
pip 6.0.3 from /usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-6.0.3-py2.7.egg (python 2.7)

$ which pip
/usr/local/bin/pip

Reading HTTP headers in a Spring REST controller

Instead of taking the HttpServletRequest object in every method, keep in controllers' context by auto-wiring via the constructor. Then you can access from all methods of the controller.

public class OAuth2ClientController {
    @Autowired
    private OAuth2ClientService oAuth2ClientService;

    private HttpServletRequest request;

    @Autowired
    public OAuth2ClientController(HttpServletRequest request) {
        this.request = request;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<String> createClient(@RequestBody OAuth2Client client) {
        System.out.println(request.getRequestURI());
        System.out.println(request.getHeader("Content-Type"));

        return ResponseEntity.ok();
    }
}

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

select p.name
from   person p
where  instr(p.name,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

How to run a python script from IDLE interactive shell?

I tested this and it kinda works out :

exec(open('filename').read())  # Don't forget to put the filename between ' '

How to push changes to github after jenkins build completes?

Actually, the "Checkout to specific local branch" from Claus's answer isn't needed as well.

You can just do changes, execute git commit -am "message" and then use "Git Publisher" with "Branch to push" = /refs/heads/master (or develop or whatever branch you need to push to), "Target remote name" = origin.

Create an empty data.frame

You can do it without specifying column types

df = data.frame(matrix(vector(), 0, 3,
                dimnames=list(c(), c("Date", "File", "User"))),
                stringsAsFactors=F)

How to copy a dictionary and only edit the copy

You can also just make a new dictionary with a dictionary comprehension. This avoids importing copy.

dout = dict((k,v) for k,v in mydict.items())

Of course in python >= 2.7 you can do:

dout = {k:v for k,v in mydict.items()}

But for backwards compat., the top method is better.

How to delete an SMS from the inbox in Android programmatically?

Use this function to delete specific message thread or modify according your needs:

public void delete_thread(String thread) 
{ 
  Cursor c = getApplicationContext().getContentResolver().query(
  Uri.parse("content://sms/"),new String[] { 
  "_id", "thread_id", "address", "person", "date","body" }, null, null, null);

 try {
  while (c.moveToNext()) 
      {
    int id = c.getInt(0);
    String address = c.getString(2);
    if (address.equals(thread)) 
        {
     getApplicationContext().getContentResolver().delete(
     Uri.parse("content://sms/" + id), null, null);
    }

       }
} catch (Exception e) {

  }
}

Call this function simply below:

delete_thread("54263726");//you can pass any number or thread id here

Don't forget to add android mainfest permission below:

<uses-permission android:name="android.permission.WRITE_SMS"/>

CSS: image link, change on hover

If you give generally give a span the property display:block, it'll then behave like a div, i.e you can set width and height.

You can also skip the div or span and just set the a the to display: block and apply the backgound style to it.

<a href="" class="myImage"><!----></a>


    <style>
      .myImage {display: block; width: 160px; height: 20px; margin:0 0 10px 0; background: url(image.png) center top no-repeat;}
.myImage:hover{background-image(image_hover.png);}
    </style>

Coerce multiple columns to factors at once

and, for completeness and with regards to this question asking about changing string columns only, there's mutate_if:

data <- cbind(stringVar = sample(c("foo","bar"),10,replace=TRUE),
              data.frame(matrix(sample(1:40), 10, 10, dimnames = list(1:10, LETTERS[1:10]))),stringsAsFactors=FALSE)     

factoredData = data %>% mutate_if(is.character,funs(factor(.)))

"Warning: iPhone apps should include an armv6 architecture" even with build config set

In addition to Nick's answer about Xcode 4.2, you may also need to review your info.plist file. It seems as if new projects started in Xcode 4.2 by default specify 'armv7' in the 'Required Device Capabilities'. You'll need to remove this if wanting to support devices that run armv6 (e.g. the iPhone 3G).

enter image description here

Delete armv7 from the 'Required device capabilities' in yourProjectName-Info.plist

How to get item's position in a list?

Use enumerate:

testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
    if item == 1:
        print position

Getting each individual digit from a whole integer

//this can be easily understandable for beginners     
int score=12344534;
int div;
for (div = 1; div <= score; div *= 10)
{

}
/*for (div = 1; div <= score; div *= 10); for loop with semicolon or empty body is same*/
while(score>0)
{
    div /= 10;
    printf("%d\n`enter code here`", score / div);
    score %= div;
}

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

Rather than allocating a massive array, could you try utilizing an iterator? These are delay-executed, meaning values are generated only as they're requested in an foreach statement; you shouldn't run out of memory this way:

private static IEnumerable<double> MakeRandomNumbers(int numberOfRandomNumbers) 
{
    for (int i = 0; i < numberOfRandomNumbers; i++)
    {
        yield return randomGenerator.GetAnotherRandomNumber();
    }
}


...

// Hooray, we won't run out of memory!
foreach(var number in MakeRandomNumbers(int.MaxValue))
{
    Console.WriteLine(number);
}

The above will generate as many random numbers as you wish, but only generate them as they're asked for via a foreach statement. You won't run out of memory that way.

Alternately, If you must have them all in one place, store them in a file rather than in memory.

How to pass a PHP variable using the URL

Use this easy method

  $a='Link1';
  $b='Link2';
  echo "<a href=\"pass.php?link=$a\">Link 1</a>";
  echo '<br/>';
  echo "<a href=\"pass.php?link=$b\">Link 2</a>";

Turn off enclosing <p> tags in CKEditor 3.0

MAKE THIS YOUR config.js file code

CKEDITOR.editorConfig = function( config ) {

   //   config.enterMode = 2; //disabled <p> completely
        config.enterMode = CKEDITOR.ENTER_BR // pressing the ENTER KEY input <br/>
        config.shiftEnterMode = CKEDITOR.ENTER_P; //pressing the SHIFT + ENTER KEYS input <p>
        config.autoParagraph = false; // stops automatic insertion of <p> on focus
    };

How does #include <bits/stdc++.h> work in C++?

#include <bits/stdc++.h> is an implementation file for a precompiled header.

From, software engineering perspective, it is a good idea to minimize the include. If you use it actually includes a lot of files, which your program may not need, thus increase both compile-time and program size unnecessarily. [edit: as pointed out by @Swordfish in the comments that the output program size remains unaffected. But still, it's good practice to include only the libraries you actually need, unless it's some competitive competition]

But in contests, using this file is a good idea, when you want to reduce the time wasted in doing chores; especially when your rank is time-sensitive.

It works in most online judges, programming contest environments, including ACM-ICPC (Sub-Regionals, Regionals, and World Finals) and many online judges.

The disadvantages of it are that it:

  • increases the compilation time.
  • uses an internal non-standard header file of the GNU C++ library, and so will not compile in MSVC, XCode, and many other compilers

Array of strings in groovy

Most of the time you would create a list in groovy rather than an array. You could do it like this:

names = ["lucas", "Fred", "Mary"]

Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:

names = "lucas Fred Mary".split()

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

If @papigee does solution doesn't work, maybe you don't have the permissions.

I tried @papigee solution but does't work without sudo.

I did :

sudo docker exec -it <container id or name> /bin/sh

Multiple IF statements between number ranges

It's a little tricky because of the nested IFs but here is my answer (confirmed in Google Spreadsheets):

=IF(AND(A2>=0,    A2<500),  "Less than 500", 
 IF(AND(A2>=500,  A2<1000), "Between 500 and 1000", 
 IF(AND(A2>=1000, A2<1500), "Between 1000 and 1500", 
 IF(AND(A2>=1500, A2<2000), "Between 1500 and 2000", "Undefined"))))

How to change MenuItem icon in ActionBar programmatically

Its Working

      MenuItem tourchmeMenuItem; // Declare Global .......

 public boolean onCreateOptionsMenu(Menu menu) 
 {
        getMenuInflater().inflate(R.menu.search, menu);
        menu.findItem(R.id.action_search).setVisible(false);
        tourchmeMenuItem = menu.findItem(R.id.done);
        return true;
 }

    public boolean onOptionsItemSelected(MenuItem item) {

    case R.id.done:
                       if(LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).getIsFlashLight()){
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                mScannerView.setFlash(false);
                                LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(false);
                                tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_white_32));
                            }
                        }else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                mScannerView.setFlash(true);
                                LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(true);
                                tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_cross_white_32));
                            }
                        }
                        break;

}

TypeError: 'int' object is not callable

Somewhere else in your code you have something that looks like this:

round = 42

Then when you write

round((a/b)*0.9*c)

that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.

The problem is whatever code binds an int to the name round. Find that and remove it.

How can I mark a foreign key constraint using Hibernate annotations?

@Column is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions to Question, since an instance represents a single question, and not several ones. Then create the association:

@Entity
@Table(name = "UserAnswer")
public class UserAnswer {

    // this entity needs an ID:
    @Id
    @Column(name="useranswer_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "question_id")
    private Question question;

    @Column(name = "response")
    private String response;

    //getter and setter 
}

The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.

How to have multiple CSS transitions on an element?

.nav a {
    transition: color .2s, text-shadow .2s;
}

Combine two tables for one output

You'll need to use UNION to combine the results of two queries. In your case:

SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum

Note - If you use UNION ALL as in above, it's no slower than running the two queries separately as it does no duplicate-checking.

add controls vertically instead of horizontally using flow layout

I used a BoxLayout and set its second parameter as BoxLayout.Y_AXIS and it worked for me:

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

Difference between style = "position:absolute" and style = "position:relative"

Relative positioning: The element creates its own coordinate axes, at a location offset from the viewport coordinate axis. It is Part of document flow but shifted.

Absolute positioning: An element searches for the nearest available coordinate axes among its parent elements. The element is then positioned by specifying offsets from this coordinate axis. It is removed from document normal flow.

enter image description here

Source

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

How to add a TextView to a LinearLayout dynamically in Android?

TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null);
        rowTextView.setText(text);
        layout.addView(rowTextView);

This is how I'm using this:

 private List<Tag> tags = new ArrayList<>();


if(tags.isEmpty()){
        Gson gson = new Gson();
        Type listType = new TypeToken<List<Tag>>() {
        }.getType();
        tags = gson.fromJson(tour.getTagsJSONArray(), listType);
    }



if (flowLayout != null) {
        if(!tags.isEmpty()) {
            Log.e(TAG, "setTags: "+ flowLayout.getChildCount() );
            flowLayout.removeAllViews();
            for (Tag tag : tags) {
                FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
                lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom);
                TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null);
                rowTextView.setText(tag.getLabel());
                rowTextView.setLayoutParams(lparams);
                flowLayout.addView(rowTextView);
            }
        }
        Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() );
    }

And this is my custom TextView named tag:

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"    
android:textSize="10dp"
android:textAllCaps="true"
fontPath="@string/font_light"
android:background="@drawable/tag_shape"
android:paddingLeft="11dp"
android:paddingTop="6dp"
android:paddingRight="11dp"
android:paddingBottom="6dp">

this is my tag_shape:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f2f2f2" />
<corners android:radius="15dp" />
</shape>

efect:

enter image description here

In other place I'm adding textviews with language names from dialog with listview:

enter image description here

enter image description here

Quickly reading very large tables as dataframes

I am reading data very quickly using the new arrow package. It appears to be in a fairly early stage.

Specifically, I am using the parquet columnar format. This converts back to a data.frame in R, but you can get even deeper speedups if you do not. This format is convenient as it can be used from Python as well.

My main use case for this is on a fairly restrained RShiny server. For these reasons, I prefer to keep data attached to the Apps (i.e., out of SQL), and therefore require small file size as well as speed.

This linked article provides benchmarking and a good overview. I have quoted some interesting points below.

https://ursalabs.org/blog/2019-10-columnar-perf/

File Size

That is, the Parquet file is half as big as even the gzipped CSV. One of the reasons that the Parquet file is so small is because of dictionary-encoding (also called “dictionary compression”). Dictionary compression can yield substantially better compression than using a general purpose bytes compressor like LZ4 or ZSTD (which are used in the FST format). Parquet was designed to produce very small files that are fast to read.

Read Speed

When controlling by output type (e.g. comparing all R data.frame outputs with each other) we see the the performance of Parquet, Feather, and FST falls within a relatively small margin of each other. The same is true of the pandas.DataFrame outputs. data.table::fread is impressively competitive with the 1.5 GB file size but lags the others on the 2.5 GB CSV.


Independent Test

I performed some independent benchmarking on a simulated dataset of 1,000,000 rows. Basically I shuffled a bunch of things around to attempt to challenge the compression. Also I added a short text field of random words and two simulated factors.

Data

library(dplyr)
library(tibble)
library(OpenRepGrid)

n <- 1000000

set.seed(1234)
some_levels1 <- sapply(1:10, function(x) paste(LETTERS[sample(1:26, size = sample(3:8, 1), replace = TRUE)], collapse = ""))
some_levels2 <- sapply(1:65, function(x) paste(LETTERS[sample(1:26, size = sample(5:16, 1), replace = TRUE)], collapse = ""))


test_data <- mtcars %>%
  rownames_to_column() %>%
  sample_n(n, replace = TRUE) %>%
  mutate_all(~ sample(., length(.))) %>%
  mutate(factor1 = sample(some_levels1, n, replace = TRUE),
         factor2 = sample(some_levels2, n, replace = TRUE),
         text = randomSentences(n, sample(3:8, n, replace = TRUE))
         )

Read and Write

Writing the data is easy.

library(arrow)

write_parquet(test_data , "test_data.parquet")

# you can also mess with the compression
write_parquet(test_data, "test_data2.parquet", compress = "gzip", compression_level = 9)

Reading the data is also easy.

read_parquet("test_data.parquet")

# this option will result in lightning fast reads, but in a different format.
read_parquet("test_data2.parquet", as_data_frame = FALSE)

I tested reading this data against a few of the competing options, and did get slightly different results than with the article above, which is expected.

benchmarking

This file is nowhere near as large as the benchmark article, so maybe that is the difference.

Tests

  • rds: test_data.rds (20.3 MB)
  • parquet2_native: (14.9 MB with higher compression and as_data_frame = FALSE)
  • parquet2: test_data2.parquet (14.9 MB with higher compression)
  • parquet: test_data.parquet (40.7 MB)
  • fst2: test_data2.fst (27.9 MB with higher compression)
  • fst: test_data.fst (76.8 MB)
  • fread2: test_data.csv.gz (23.6MB)
  • fread: test_data.csv (98.7MB)
  • feather_arrow: test_data.feather (157.2 MB read with arrow)
  • feather: test_data.feather (157.2 MB read with feather)

Observations

For this particular file, fread is actually very fast. I like the small file size from the highly compressed parquet2 test. I may invest the time to work with the native data format rather than a data.frame if I really need the speed up.

Here fst is also a great choice. I would either use the highly compressed fst format or the highly compressed parquet depending on if I needed the speed or file size trade off.

Center text in div?

Adding line height helps too.

text-align: center;
line-height: 18px; /* for example. */

Completely cancel a rebase

In the case of a past rebase that you did not properly aborted, you now (Git 2.12, Q1 2017) have git rebase --quit

See commit 9512177 (12 Nov 2016) by Nguy?n Thái Ng?c Duy (pclouds). (Merged by Junio C Hamano -- gitster -- in commit 06cd5a1, 19 Dec 2016)

rebase: add --quit to cleanup rebase, leave everything else untouched

There are occasions when you decide to abort an in-progress rebase and move on to do something else but you forget to do "git rebase --abort" first. Or the rebase has been in progress for so long you forgot about it. By the time you realize that (e.g. by starting another rebase) it's already too late to retrace your steps. The solution is normally

rm -r .git/<some rebase dir>

and continue with your life.
But there could be two different directories for <some rebase dir> (and it obviously requires some knowledge of how rebase works), and the ".git" part could be much longer if you are not at top-dir, or in a linked worktree. And "rm -r" is very dangerous to do in .git, a mistake in there could destroy object database or other important data.

Provide "git rebase --quit" for this use case, mimicking a precedent that is "git cherry-pick --quit".


Before Git 2.27 (Q2 2020), The stash entry created by "git merge --autostash" to keep the initial dirty state were discarded by mistake upon "git rebase --quit", which has been corrected.

See commit 9b2df3e (28 Apr 2020) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 3afdeef, 29 Apr 2020)

rebase: save autostash entry into stash reflog on --quit

Signed-off-by: Denton Liu

In a03b55530a ("merge: teach --autostash option", 2020-04-07, Git v2.27.0 -- merge listed in batch #5), the --autostash option was introduced for git merge.

(See "Can “git pull” automatically stash and pop pending changes?")

Notably, when git merge --quit is run with an autostash entry present, it is saved into the stash reflog.

This is contrasted with the current behaviour of git rebase --quit where the autostash entry is simply just dropped out of existence.

Adopt the behaviour of git merge --quit in git rebase --quit and save the autostash entry into the stash reflog instead of just deleting it.

How to sort with lambda in Python

You're trying to use key functions with lambda functions.

Python and other languages like C# or F# use lambda functions.

Also, when it comes to key functions and according to the documentation

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

...

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.

So, key functions have a parameter key and it can indeed receive a lambda function.

In Real Python there's a nice example of its usage. Let's say you have the following list

ids = ['id1', 'id100', 'id2', 'id22', 'id3', 'id30']

and want to sort through its "integers". Then, you'd do something like

sorted_ids = sorted(ids, key=lambda x: int(x[2:])) # Integer sort

and printing it would give

['id1', 'id2', 'id3', 'id22', 'id30', 'id100']

In your particular case, you're only missing to write key= before lambda. So, you'd want to use the following

a = sorted(a, key=lambda x: x.modified, reverse=True)

How to use Redirect in the new react-router-dom of Reactjs

The problem I run into is I have an existing IIS machine. I then deploy a static React app to it. When you use router, the URL that displays is actually virtual, not real. If you hit F5 it goes to IIS, not index.js, and your return will be 404 file not found. How I resolved it was simple. I have a public folder in my react app. In that public folder I created the same folder name as the virtual routing. In this folder, I have an index.html with the following code:

<script>
  {
    localStorage.setItem("redirect", "/ansible/");
    location.href = "/";
  }
</script>

Now what this does is for this session, I'm adding the "routing" path I want it to go. Then inside my App.js I do this (Note ... is other code but too much to put here for a demo):

import React, { Component } from "react";
import { Route, Link } from "react-router-dom";
import { BrowserRouter as Router } from "react-router-dom";
import { Redirect } from 'react-router';
import Ansible from "./Development/Ansible";
import Code from "./Development/Code";
import Wood from "./WoodWorking";
import "./App.css";

class App extends Component {
  render() {
    const redirect = localStorage.getItem("redirect");

    if(redirect) {
      localStorage.removeItem("redirect");
    }

    return (
      <Router>
        {redirect ?<Redirect to={redirect}/> : ""}
        <div className="App">
        ...
          <Link to="/">
            <li>Home</li>
          </Link>
          <Link to="/dev">
            <li>Development</li>
          </Link>
          <Link to="/wood">
            <li>Wood Working</li>
          </Link>
        ...
          <Route
            path="/"
            exact
            render={(props) => (
              <Home {...props} />
            )}
          />
          <Route
            path="/dev"
            render={(props) => (
              <Code {...props} />
            )}
          />
          <Route
            path="/wood"
            render={(props) => (
              <Wood {...props} />
            )}
          />
          <Route
            path="/ansible/"
            exact
            render={(props) => (
              <Ansible {...props} checked={this.state.checked} />
            )}
          />
          ...
      </Router>
    );
  }
}

export default App;

Actual usage: chizl.com

jQuery click event not working after adding class

Here is the another solution as well, the bind method.

$(document).bind('click', ".intro", function() {
    var liId = $(this).parent("li").attr("id");
    alert(liId);        
});

Cheers :)

python: order a list of numbers without built-in sort, min, max function

You could do it easily by using min() function

`def asc(a):
    b=[]
    l=len(a)
    for i in range(l):
        x=min(a)
        b.append(x)
        a.remove(x)
    return b
 print asc([2,5,8,7,44,54,23])`

How do I remove the blue styling of telephone numbers on iPhone/iOS?

iOS makes phone numbers clickable by defaults (for obvious reasons). Of course, that adds an extra tag which is overriding your styling if your phone number isn’t already a link.

To fix it, try adding this to your stylesheet: a[href^=tel] { color: inherit; text-decoration: none; }

That should keep your phone numbers styled as you expect without adding extra markup.

How to debug .htaccess RewriteRule not working

To answer the first question of the three asked, a simple way to see if the .htaccess file is working or not is to trigger a custom error at the top of the .htaccess file:

ErrorDocument 200 "Hello. This is your .htaccess file talking."
RewriteRule ^ - [L,R=200]

On to your second question, if the .htaccess file is not being read it is possible that the server's main Apache configuration has AllowOverride set to None. Apache's documentation has troubleshooting tips for that and other cases that may be preventing the .htaccess from taking effect.

Finally, to answer your third question, if you need to debug specific variables you are referencing in your rewrite rule or are using an expression that you want to evaluate independently of the rule you can do the following:

Output the variable you are referencing to make sure it has the value you are expecting:

ErrorDocument 200 "Request: %{THE_REQUEST} Referrer: %{HTTP_REFERER} Host: %{HTTP_HOST}"
RewriteRule ^ - [L,R=200]

Test the expression independently by putting it in an <If> Directive. This allows you to make sure your expression is written properly or matching when you expect it to:

<If "%{REQUEST_URI} =~ /word$/">
    ErrorDocument 200 "Your expression is priceless!"
    RewriteRule ^ - [L,R=200]
</If>

Happy .htaccess debugging!

__FILE__, __LINE__, and __FUNCTION__ usage in C++

FYI: g++ offers the non-standard __PRETTY_FUNCTION__ macro. Until just now I did not know about C99 __func__ (thanks Evan!). I think I still prefer __PRETTY_FUNCTION__ when it's available for the extra class scoping.

PS:

static string  getScopedClassMethod( string thePrettyFunction )
{
  size_t index = thePrettyFunction . find( "(" );
  if ( index == string::npos )
    return thePrettyFunction;  /* Degenerate case */

  thePrettyFunction . erase( index );

  index = thePrettyFunction . rfind( " " );
  if ( index == string::npos )
    return thePrettyFunction;  /* Degenerate case */

  thePrettyFunction . erase( 0, index + 1 );

  return thePrettyFunction;   /* The scoped class name. */
}

How to make a new List in Java

List list = new ArrayList();

Or with generics

List<String> list = new ArrayList<String>();

You can, of course, replace string with any type of variable, such as Integer, also.

Throw away local commits in Git

For those interested in the Visual Studio solution, here is the drill:

  1. In the Team Explorer window, connect to the target repo.
  2. Then from Branches, right-click the branch of interest and select View history.
  3. Right-click a commit in the History window and choose Reset -> Delete changes (--hard).

That will throw away your local commits and reset the state of your repo to the selected commit. I.e. Your changes after you pulled the repo will be lost.

Making a drop down list using swift?

You have to be sure to use UIPickerViewDataSource and UIPickerViewDelegate protocols or it will throw an AppDelegate error as of swift 3

Also please take note of the change in syntax:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int

is now:

public func numberOfComponents(in pickerView: UIPickerView) -> Int

The following below worked for me.

import UIkit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    @IBOutlet weak var textBox: UITextField!
    @IBOutlet weak var dropDown: UIPickerView!

    var list = ["1", "2", "3"]

    public func numberOfComponents(in pickerView: UIPickerView) -> Int{
        return 1
    }

    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{

        return list.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        self.view.endEditing(true)
        return list[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        self.textBox.text = self.list[row]
        self.dropDown.isHidden = true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

        if textField == self.textBox {
            self.dropDown.isHidden = false
            //if you don't want the users to se the keyboard type:

            textField.endEditing(true)
        }
    }
}

How to provide a mysql database connection in single file in nodejs

I think that you should use a connection pool instead of share a single connection. A connection pool would provide a much better performance, as you can check here.

As stated in the library documentation, it occurs because the MySQL protocol is sequential (this means that you need multiple connections to execute queries in parallel).

Connection Pool Docs

java: use StringBuilder to insert at the beginning

StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
    sb.insert(0, Integer.toString(i));
}

Warning: It defeats the purpose of StringBuilder, but it does what you asked.


Better technique (although still not ideal):

  1. Reverse each string you want to insert.
  2. Append each string to a StringBuilder.
  3. Reverse the entire StringBuilder when you're done.

This will turn an O(n²) solution into O(n).

How to delete files/subfolders in a specific directory at the command prompt in Windows

@ECHO OFF
rem next line removes all files in temp folder
DEL /A /F /Q /S "%temp%\*.*"
rem next line cleans up the folder's content
FOR /D %%p IN ("%temp%\*.*") DO RD "%%p" /S /Q

How to convert Map keys to array?

You can use the spread operator to convert Map.keys() iterator in an Array.

_x000D_
_x000D_
let myMap = new Map().set('a', 1).set('b', 2).set(983, true)_x000D_
let keys = [...myMap.keys()]_x000D_
console.log(keys)
_x000D_
_x000D_
_x000D_

How to insert values in two dimensional array programmatically?

String[][] shades = new String[intSize][intSize];
 // print array in rectangular form
 for (int r=0; r<shades.length; r++) {
     for (int c=0; c<shades[r].length; c++) {
         shades[r][c]="hello";//your value
     }
 }

Java: Instanceof and Generics

Two options for runtime type checking with generics:

Option 1 - Corrupt your constructor

Let's assume you are overriding indexOf(...), and you want to check the type just for performance, to save yourself iterating the entire collection.

Make a filthy constructor like this:

public MyCollection<T>(Class<T> t) {

    this.t = t;
}

Then you can use isAssignableFrom to check the type.

public int indexOf(Object o) {

    if (
        o != null &&

        !t.isAssignableFrom(o.getClass())

    ) return -1;

//...

Each time you instantiate your object you would have to repeat yourself:

new MyCollection<Apples>(Apples.class);

You might decide it isn't worth it. In the implementation of ArrayList.indexOf(...), they do not check that the type matches.

Option 2 - Let it fail

If you need to use an abstract method that requires your unknown type, then all you really want is for the compiler to stop crying about instanceof. If you have a method like this:

protected abstract void abstractMethod(T element);

You can use it like this:

public int indexOf(Object o) {

    try {

        abstractMethod((T) o);

    } catch (ClassCastException e) {

//...

You are casting the object to T (your generic type), just to fool the compiler. Your cast does nothing at runtime, but you will still get a ClassCastException when you try to pass the wrong type of object into your abstract method.

NOTE 1: If you are doing additional unchecked casts in your abstract method, your ClassCastExceptions will get caught here. That could be good or bad, so think it through.

NOTE 2: You get a free null check when you use instanceof. Since you can't use it, you may need to check for null with your bare hands.

How can I calculate the difference between two ArrayLists?

EDIT: Original question did not specify language. My answer is in C#.

You should instead use HashSet for this purpose. If you must use ArrayList, you could use the following extension methods:

var a = arrayListA.Cast<DateTime>();
var b = arrayListB.Cast<DateTime>();    
var c = b.Except(a);

var arrayListC = new ArrayList(c.ToArray());

using HashSet...

var a = new HashSet<DateTime>(); // ...and fill it
var b = new HashSet<DateTime>(); // ...and fill it
b.ExceptWith(a); // removes from b items that are in a

Creating Accordion Table with Bootstrap

For anyone who came here looking for how to get the true accordion effect and only allow one row to be expanded at a time, you can add an event handler for show.bs.collapse like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified this example to do so here: http://jsfiddle.net/QLfMU/116/

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Python: How to convert datetime format?

@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))

html button to send email

This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto link/action is sparsely supported, but maybe this can help...

HTML:

<form id="fr1">
    <input type="text" id="tb1" />
    <input type="text" id="tb2" />
    <input type="button" id="bt1" value="click" />
</form>

JavaScript (with jQuery):

$(document).ready(function() {
    $('#bt1').click(function() {
        $('#fr1').attr('action',
                       'mailto:[email protected]?subject=' +
                       $('#tb1').val() + '&body=' + $('#tb2').val());
        $('#fr1').submit();
    });
});

Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit type, it's just a button type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.

It's working in so much as it submits the form to a mailto action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.

HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.

How do I add a linker or compile flag in a CMake file?

Suppose you want to add those flags (better to declare them in a constant):

SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS    "-lgcov")

There are several ways to add them:

  1. The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):

    add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
    
  2. Appending to corresponding CMake variables:

    SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
    SET(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
    
  3. Using target properties, cf. doc CMake compile flag target property and need to know the target name.

    get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
    if(TEMP STREQUAL "TEMP-NOTFOUND")
      SET(TEMP "") # Set to empty string
    else()
      SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
    endif()
    # Append our values
    SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
    set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
    

Right now I use method 2.

Mergesort with Python

def merge(l1, l2, out=[]):
    if l1==[]: return out+l2
    if l2==[]: return out+l1
    if l1[0]<l2[0]: return merge(l1[1:], l2, out+l1[0:1])
    return merge(l1, l2[1:], out+l2[0:1])
def merge_sort(l): return (lambda h: l if h<1 else merge(merge_sort(l[:h]), merge_sort(l[h:])))(len(l)/2)
print(merge_sort([1,4,6,3,2,5,78,4,2,1,4,6,8]))

Optimistic vs. Pessimistic locking

In addition to what's been said already:

  • It should be said that optimistic locking tends to improve concurrency at the expense of predictability.
  • Pessimistic locking tends to reduce concurrency, but is more predictable. You pay your money, etc ...

Difference between document.addEventListener and window.addEventListener?

The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.

<p>Some paragraph.</p>
<script>
  window.addEventListener("click", () => {
    console.log("Test");
  });
</script>

Following points should be noted before select window or document to addEventListners

  1. Most of the events are same for window or document but some events like resize, and other events related to loading, unloading, and opening/closing should all be set on the window.
  2. Since window has the document it is good practice to use document to handle (if it can handle) since event will hit document first.
  3. Internet Explorer doesn't respond to many events registered on the window,so you will need to use document for registering event.

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

A solution which worked in my case is:
  1. Go to the module having Main class.
  2. Right click on pom.xml under this module.
  3. Select "Run Maven" -> "UpdateSnapshots"

How to replace ${} placeholders in a text file?

I found this thread while wondering the same thing. It inspired me to this (careful with the backticks)

$ echo $MYTEST
pass!
$ cat FILE
hello $MYTEST world
$ eval echo `cat FILE`
hello pass! world

How do I do redo (i.e. "undo undo") in Vim?

Vim documentation

<Undo>      or                  *undo* *<Undo>* *u*
u           Undo [count] changes.  {Vi: only one level}

                            *:u* *:un* *:undo*
:u[ndo]         Undo one change.  {Vi: only one level}

                            *CTRL-R*
CTRL-R          Redo [count] changes which were undone.  {Vi: redraw screen}

                            *:red* *:redo* *redo*
:red[o]         Redo one change which was undone.  {Vi: no redo}

                            *U*
U           Undo all latest changes on one line.  {Vi: while not
            moved off of it}

jquery ajax function not working

For the sake of documentation. I spent two days working out an ajax problem and this afternoon when I started testing, my PHP ajax handler wasn't getting called....

Extraordinarily frustrating.

The solution to my problem (which might help others) is the priority of the add_action.

add_action ('wp_ajax_(my handler), array('class_name', 'static_function'), 1);

recalling that the default priority = 10

I was getting a return code of zero and none of my code was being called.

...noting that this wasn't a WordPress problem, I probably misspoke on this question. My apologies.

How to pause in C?

you can put

getchar();

before the return from the main function. That will wait for a character input before exiting the program.

Alternatively you could run your program from a command line and the output would be visible.

Is there a way to collapse all code blocks in Eclipse?

The question is a bit old, but let me add a different approach. In addition to the above hot-key approaches, there are default preference settings that can be toggled.

As of Eclipse Galileo (and definitely in my Eclipse Version: Indigo Service Release 2 Build id: 20120216-1857) language specific preferences can open up new files to edit which are already collapsed or expanded.

Here is a link to Eclipse Galileo online docs showing the feature for C/C++: http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.cdt.doc.user/reference/cdt_u_c_editor_folding.htm .

In my Eclipse Indigo I can open the Folding Preferences window via : menu/ Window/ Preferences/ Java/ Editor/ Folding and set all options on so I can open files by default that are completely collapsed.

how to convert numeric to nvarchar in sql command

select convert(nvarchar(255), 4343)

Should do the trick.

Test if registry value exists

The -not test should fire if a property doesn't exist:

$prop = (Get-ItemProperty $regkey).$name
if (-not $prop)
{
   New-ItemProperty -Path $regkey -Name $name -Value "X"
}

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

This error also happens if you're using a self-signed certificate with a keyUsage missing the value keyCertSign.

android pinch zoom

In honeycomb, API level 11, it is possible, We can use setScalaX and setScaleY with pivot point
I have explained it here
Zooming a view completely
Pinch Zoom to view completely

Django - how to create a file and save it to a model's FileField?

Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.

Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).

Django 1.4.1

Python 2.7.3

#Model
class MonthEnd(models.Model):
    report = models.FileField(db_index=True, upload_to='not_used')

import csv
from os.path import join

#build and store the file
def write_csv():
    path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
    f = open(path, "w+b")

    #wipe the existing content
    f.truncate()

    csv_writer = csv.writer(f)
    csv_writer.writerow(('col1'))

    for num in range(3):
        csv_writer.writerow((num, ))

    month_end_file = MonthEnd()
    month_end_file.report.name = path
    month_end_file.save()

from my_app.models import MonthEnd

#serve it up as a download
def get_report(request):
    month_end = MonthEnd.objects.get(file_criteria=criteria)

    response = HttpResponse(month_end.report, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=report.csv'

    return response

Find length of 2D array Python

Like this:

numrows = len(input)    # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example

Assuming that all the sublists have the same length (that is, it's not a jagged array).

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

OK - all answers provided above are correct to some extend, but did not resolve this issue for me. I'm using Xcode5.

There are lots of threads around this general error but from what I read this is a bug in Xcode dating back to 3.x versions that can randomly create conflicts with your Keychain.

I was able to resolve this by doing the following:

  1. Open Xcode -> preferences -> Accounts: delete your developer account

  2. Open Keychain: Select Keys, delete all iOS keys; Select My Certificates, delete all iPhone certificates

  3. Navigate to '/Users//Library/MobileDevice/Provisioning Profiles', delete all files (this is where Xcode stores mobile profiles)

  4. Open Xcode -> preferences -> Accounts: re-add your developer account

  5. Navigate to Project properties, Target, General Tab and you should see the following enter image description here

  6. Click 'Revoke and Request' (I tried this, it may take a few min) or 'Import Developer Profile' (or download from Apple developer portal and import this way, should be faster..)

  7. FINALLY: you can go over to Build Settings and set 'Provisioning Profile' and 'Signing Settings' as described by everyone here..

Doing this and only this resolved this error for me.

python NameError: name 'file' is not defined

file() is not supported in Python 3

Use open() instead; see Built-in Functions - open().

Cannot use Server.MapPath

Try adding System.Web as a reference to your project.

Change a HTML5 input's placeholder color with CSS

try this code for different input element different style

your css selector::-webkit-input-placeholder { /*for webkit */
    color:#909090;
    opacity:1;
}
 your css selector:-moz-placeholder { /*for mozilla */
    color:#909090;
    opacity:1;
}
 your css selector:-ms-input-placeholder { /*for for internet exprolar */ 
   color:#909090;
   opacity:1;
}

example 1:

input[type="text"]::-webkit-input-placeholder { /*for webkit */
    color: red;
    opacity:1;
}
 input[type="text"]:-moz-placeholder { /*for mozilla */
    color: red;
    opacity:1;
}
 input[type="text"]:-ms-input-placeholder { /*for for internet exprolar */ 
   color: red;
   opacity:1;
}

example 2:

input[type="email"]::-webkit-input-placeholder { /*for webkit */
    color: gray;
    opacity:1;
}
 input[type="email"]:-moz-placeholder { /*for mozilla */
    color: gray;
    opacity:1;
}
 input[type="email"]:-ms-input-placeholder { /*for for internet exprolar */ 
   color: gray;
   }

PHP upload image

  <?php 
 $target_dir = "images/";
    echo $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $post_tmp_img = $_FILES["image"]["tmp_name"];
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    $post_imag = $_FILES["image"]["name"];
        move_uploaded_file($post_tmp_img,"../images/$post_imag");
 ?>

How to validate an email address in JavaScript

for email validation you can create your custom function and use regex syntax for validate email:

function validateEmail(email){
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

       //your custom code here to check your email address 

}

How do you scroll up/down on the console of a Linux VM

Shift+Fn+ UP or DOWN on a Macbook will allow you to scroll.

Retrieve data from website in android app

You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.

Get a JSON object from a HTTP response

This is not the exact answer for your question, but this may help you

public class JsonParser {

    private static DefaultHttpClient httpClient = ConnectionManager.getClient();

    public static List<Club> getNearestClubs(double lat, double lon) {
        // YOUR URL GOES HERE
        String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);

        List<Club> ret = new ArrayList<Club>();

        HttpResponse response = null;
        HttpGet getMethod = new HttpGet(getUrl);
        try {
            response = httpClient.execute(getMethod);

            // CONVERT RESPONSE TO STRING
            String result = EntityUtils.toString(response.getEntity());

            // CONVERT RESPONSE STRING TO JSON ARRAY
            JSONArray ja = new JSONArray(result);

            // ITERATE THROUGH AND RETRIEVE CLUB FIELDS
            int n = ja.length();
            for (int i = 0; i < n; i++) {
                // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
                JSONObject jo = ja.getJSONObject(i);

                // RETRIEVE EACH JSON OBJECT'S FIELDS
                long id = jo.getLong("id");
                String name = jo.getString("name");
                String address = jo.getString("address");
                String country = jo.getString("country");
                String zip = jo.getString("zip");
                double clat = jo.getDouble("lat");
                double clon = jo.getDouble("lon");
                String url = jo.getString("url");
                String number = jo.getString("number");

                // CONVERT DATA FIELDS TO CLUB OBJECT
                Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
                ret.add(c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // RETURN LIST OF CLUBS
        return ret;
    }

}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:

JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");

Differences between key, superkey, minimal superkey, candidate key and primary key

SUPER KEY:

Attribute or set of attributes used to uniquely identify tuples in the database.

CANDIDATE KEY:

  1. Minimal super key is the candidate key
  2. Can be one or many
  3. Potential primary keys
  4. not null
  5. attribute or set of attributes to uniquely identify records in DB

PRIMARY KEY:

  1. one of the candidate key which is used to identify records in DB uniquely

  2. not null

Split string on whitespace in Python

The str.split() method without an argument splits on whitespace:

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']

How do I find out what is hammering my SQL Server?

I assume due diligence here that you confirmed the CPU is actually consumed by SQL process (perfmon Process category counters would confirm this). Normally for such cases you take a sample of the relevant performance counters and you compare them with a baseline that you established in normal load operating conditions. Once you resolve this problem I recommend you do establish such a baseline for future comparisons.

You can find exactly where is SQL spending every single CPU cycle. But knowing where to look takes a lot of know how and experience. Is is SQL 2005/2008 or 2000 ? Fortunately for 2005 and newer there are a couple of off the shelf solutions. You already got a couple good pointer here with John Samson's answer. I'd like to add a recommendation to download and install the SQL Server Performance Dashboard Reports. Some of those reports include top queries by time or by I/O, most used data files and so on and you can quickly get a feel where the problem is. The output is both numerical and graphical so it is more usefull for a beginner.

I would also recommend using Adam's Who is Active script, although that is a bit more advanced.

And last but not least I recommend you download and read the MS SQL Customer Advisory Team white paper on performance analysis: SQL 2005 Waits and Queues.

My recommendation is also to look at I/O. If you added a load to the server that trashes the buffer pool (ie. it needs so much data that it evicts the cached data pages from memory) the result would be a significant increase in CPU (sounds surprising, but is true). The culprit is usually a new query that scans a big table end-to-end.

GIT clone repo across local file system in windows

You can specify the remote’s URL by applying the UNC path to the file protocol. This requires you to use four slashes:

git clone file:////<host>/<share>/<path>

For example, if your main machine has the IP 192.168.10.51 and the computer name main, and it has a share named code which itself is a git repository, then both of the following commands should work equally:

git clone file:////main/code
git clone file:////192.168.10.51/code

If the Git repository is in a subdirectory, simply append the path:

git clone file:////main/code/project-repository
git clone file:////192.168.10.51/code/project-repository

How to empty the message in a text area with jquery?

//since you are using AJAX, I believe that you can't rely in here with the submit //empty the action, you can include charset utf-8 as jQuery POST method uses that as well I think

HTML

<input name="user" id="nick" value="admin" type="hidden">

<p class="messagelabel"><label class="messagelabel">Message</label>

<textarea id="message" name="message" rows="2" cols="40"></textarea>

<input disabled="disabled" id="send" value="Sending..." type="submit">

JAVACRIPT

                            //reset the form to it's original state
            $.fn.reset = function () {

                              $(this).each (function() { 
                                this.reset();
                                 });
                                                    //any logic that you want to add besides the regular javascript reset
                                                /*$("select#select2").multiselect('refresh');    
                                                $("select").multiselect('destroy');
                                                redo();
                                                */
                            }


//start of jquery based function
 jQuery(function($)
 {
 //useful variable definitions




var page_action = 'index.php/admin/messages/insertShoutBox';

 var the_form_click=$("#form input[type='submit']");

 //useful in case that we want to make reference to it and update

 var just_the_form=$('#form');

 //bind to the events instead of the submit action


the_form_click.on('click keypress', function(event){

//original code, removed the submit event handler.. //$("#form").submit(function(){

if(checkForm()){

    //var nick = inputUser.attr("value");
    //var message = inputMessage.attr("value");

    //seems more adequate for your form, not tested
    var nick = $('#form input[type="text"]:first').attr('value');
    var message = $('#form input[type="textarea"]').attr('value');


    //we deactivate submit button while sending
     //$("#send").attr({ disabled:true, value:"Sending..." });

    //This is more convenient here, we remove the attribute disabled for the submit button and we change it's value

    the_form_click.removeAttr('disabled')
    //.val("Sending...");
    //not sure why this is here so lonely, when it's the same element.. instead trigger it to avoid any issues later
    .val("Sending...").trigger('blur');


  //$("#send").blur();


    //send the post to shoutbox.php
    $.ajax({
        type: "POST", 
        //see you were calling it at the form, on submit, but it's here where you update the url
        //url: "index.php/admin/dashboard/insertShoutBox", 


        url: page_action,

        //data: $('#form').serialize(),
        //Serialize the form data
        data: just_the_form.serialize(),

       // complete: function(data){
       //on complete we should just instead use console log, but I;m using alert to test
       complete: function(data){
       alert('Hurray on Complete triggered with AJAX here');
       },
       success: function(data){
            messageList.html(data.responseText);
            updateShoutbox();

      var timeset='750';
                setTimeout(" just_the_form.reset(); ",timeset); 
                //reset the form once again, the send button will return to disable false, and value will be submit

             //$('#message').val('').empty();
            //maybe you want to reset the form instead????

            //reactivate the send button
            //$("#send").attr({ disabled:false, value:"SUBMIT !" });
        }
     });
}
else alert("Please fill all fields!");


//we prevent the refresh of the page after submitting the form
//return false;

//we prevented it by removing the action at the form and adding return false there instead

event.preventDefault();
});   //end of function

}); //end jQuery function

</script>

Using BufferedReader.readLine() in a while loop properly

In case if you are still stumbling over this question. Nowadays things look nicer with Java 8:

try {
  Files.lines(Paths.get(targetsFile)).forEach(
    s -> {
      System.out.println(s);
      // do more stuff with s
    }
  );
} catch (IOException exc) {
  exc.printStackTrace();
}

How to convert array into comma separated string in javascript

Use the join method from the Array type.

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

AngularJS - Animate ng-view transitions

Check this code:

Javascript:

app.config( ["$routeProvider"], function($routeProvider){
    $routeProvider.when("/part1", {"templateUrl" : "part1"});
    $routeProvider.when("/part2", {"templateUrl" : "part2"});
    $routeProvider.otherwise({"redirectTo":"/part1"});
  }]
);

function HomeFragmentController($scope) {
    $scope.$on("$routeChangeSuccess", function (scope, next, current) {
        $scope.transitionState = "active"
    });
}

CSS:

.fragmentWrapper {
    overflow: hidden;
}

.fragment {
    position: relative;
    -moz-transition-property: left;
    -o-transition-property: left;
    -webkit-transition-property: left;
    transition-property: left;
    -moz-transition-duration: 0.1s;
    -o-transition-duration: 0.1s;
    -webkit-transition-duration: 0.1s;
    transition-duration: 0.1s
}

.fragment:not(.active) {
    left: 540px;
}

.fragment.active {
    left: 0px;
}

Main page HTML:

<div class="fragmentWrapper" data-ng-view data-ng-controller="HomeFragmentController">
</div>

Partials HTML example:

<div id="part1" class="fragment {{transitionState}}">
</div>

Negative matching using grep (match lines that do not contain foo)

In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.

find /home/baumerf/public_html/ -mmin -60 -not -name error_log

If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:

find /home/baumerf/public_html/ -mmin -60 -not -name \*.log

How to remove CocoaPods from a project?

enter image description here

pictorial representation detailed

Can we update primary key values of a table?

You can as long as

  • The value is unique
  • No existing foreign keys are violated

How to generate random number in Bash?

Reading from /dev/random or /dev/urandom character special files is the way to go.

These devices return truly random numbers when read and are designed to help application software choose secure keys for encryption. Such random numbers are extracted from an entropy pool that is contributed by various random events. {LDD3, Jonathan Corbet, Alessandro Rubini, and Greg Kroah-Hartman]

These two files are interface to kernel randomization, in particular

void get_random_bytes_arch(void* buf, int nbytes)

which draws truly random bytes from hardware if such function is by hardware implemented (usually is), or it draws from entropy pool (comprised of timings between events like mouse and keyboard interrupts and other interrupts that are registered with SA_SAMPLE_RANDOM).

dd if=/dev/urandom count=4 bs=1 | od -t d

This works, but writes unneeded output from dd to stdout. The command below gives just the integer I need. I can even get specified number of random bits as I need by adjustment of the bitmask given to arithmetic expansion:

me@mymachine:~/$ x=$(head -c 1 /dev/urandom > tmp && hexdump 
                         -d tmp | head -n 1 | cut -c13-15) && echo $(( 10#$x & 127 ))

Java 8 - Difference between Optional.flatMap and Optional.map

  • Optional.map():

Takes every element and if the value exists, it is passed to the function:

Optional<T> optionalValue = ...;
Optional<Boolean> added = optionalValue.map(results::add);

Now added has one of three values: true or false wrapped into an Optional , if optionalValue was present, or an empty Optional otherwise.

If you don't need to process the result you can simply use ifPresent(), it doesn't have return value:

optionalValue.ifPresent(results::add); 
  • Optional.flatMap():

Works similar to the same method of streams. Flattens out the stream of streams. With the difference that if the value is presented it is applied to function. Otherwise, an empty optional is returned.

You can use it for composing optional value functions calls.

Suppose we have methods:

public static Optional<Double> inverse(Double x) {
    return x == 0 ? Optional.empty() : Optional.of(1 / x);
}

public static Optional<Double> squareRoot(Double x) {
    return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
}

Then you can compute the square root of the inverse, like:

Optional<Double> result = inverse(-4.0).flatMap(MyMath::squareRoot);

or, if you prefer:

Optional<Double> result = Optional.of(-4.0).flatMap(MyMath::inverse).flatMap(MyMath::squareRoot);

If either the inverse() or the squareRoot() returns Optional.empty(), the result is empty.

Authenticating against Active Directory with Java on Linux

If all you want to do is authenticate against AD using Kerberos, then a simple http://spnego.sourceforge.net/HelloKDC.java program should do it.

Take a look at the project's "pre-flight" documentation which talks about the HelloKDC.java program.

Python datetime strptime() and strftime(): how to preserve the timezone information

Try this:

import pytz
import datetime

fmt = '%Y-%m-%d %H:%M:%S %Z'

d = datetime.datetime.now(pytz.timezone("America/New_York"))
d_string = d.strftime(fmt)
d2 = pytz.timezone('America/New_York').localize(d.strptime(d_string,fmt), is_dst=None)
print(d_string)
print(d2.strftime(fmt))

JavaScript: Parsing a string Boolean value?

last but not least, a simple and efficient way to do it with a default value :

ES5

function parseBool(value, defaultValue) {
    return (value == 'true' || value == 'false' || value === true || value === false) && JSON.parse(value) || defaultValue;
}

ES6 , a shorter one liner

const parseBool = (value, defaultValue) => ['true', 'false', true, false].includes(value) && JSON.parse(value) || defaultValue

JSON.parse is efficient to parse booleans

Text File Parsing with Python

I would use a for loop to iterate over the lines in the text file:

for line in my_text:
    outputfile.writelines(data_parser(line, reps))

If you want to read the file line-by-line instead of loading the whole thing at the start of the script you could do something like this:

inputfile = open('test.dat')
outputfile = open('test.csv', 'w')

# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'

# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }

for i in range(4): inputfile.next() # skip first four lines
for line in inputfile:
    outputfile.writelines(data_parser(line, reps))

inputfile.close()
outputfile.close()

How do I delete unpushed git commits?

Don't delete it: for just one commit git cherry-pick is enough.

But if you had several commits on the wrong branch, that is where git rebase --onto shines:

Suppose you have this:

 x--x--x--x <-- master
           \
            -y--y--m--m <- y branch, with commits which should have been on master

, then you can mark master and move it where you would want to be:

 git checkout master
 git branch tmp
 git checkout y
 git branch -f master

 x--x--x--x <-- tmp
           \
            -y--y--m--m <- y branch, master branch

, reset y branch where it should have been:

 git checkout y
 git reset --hard HEAD~2 # ~1 in your case, 
                         # or ~n, n = number of commits to cancel

 x--x--x--x <-- tmp
           \
            -y--y--m--m <- master branch
                ^
                |
                -- y branch

, and finally move your commits (reapply them, making actually new commits)

 git rebase --onto tmp y master
 git branch -D tmp


 x--x--x--x--m'--m' <-- master
           \
            -y--y <- y branch

How to access pandas groupby dataframe by key

I was looking for a way to sample a few members of the GroupBy obj - had to address the posted question to get this done.

create groupby object based on some_key column

grouped = df.groupby('some_key')

pick N dataframes and grab their indices

sampled_df_i  = random.sample(grouped.indices, N)

grab the groups

df_list  = map(lambda df_i: grouped.get_group(df_i), sampled_df_i)

optionally - turn it all back into a single dataframe object

sampled_df = pd.concat(df_list, axis=0, join='outer')

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Show loading gif after clicking form submit using jQuery

Better and clean example using JS only

Reference: TheDeveloperBlog.com

Step 1 - Create your java script and place it in your HTML page.

<script type="text/javascript">
    function ShowLoading(e) {
        var div = document.createElement('div');
        var img = document.createElement('img');
        img.src = 'loading_bar.GIF';
        div.innerHTML = "Loading...<br />";
        div.style.cssText = 'position: fixed; top: 5%; left: 40%; z-index: 5000; width: 422px; text-align: center; background: #EDDBB0; border: 1px solid #000';
        div.appendChild(img);
        document.body.appendChild(div);
        return true;
        // These 2 lines cancel form submission, so only use if needed.
        //window.event.cancelBubble = true;
        //e.stopPropagation();
    }
</script>

in your form call the java script function on submit event.

<form runat="server"  onsubmit="ShowLoading()">
</form>

Soon after you submit the form, it will show you the loading image.

Get skin path in Magento?

First note that

Mage::getBaseDir('skin')

returns only path to skin directory of your Magento install (/your/magento/dir/skin).

You can access absolute path to currently used skin directory using:

Mage::getDesign()->getSkinBaseDir()

This method accepts an associative array as optional parameter to modify result.

Following keys are recognized:

  • _area frontend (default) or adminhtml
  • _package your package
  • _theme your theme
  • _relative when this is set (as an key) path relative to Mage::getBaseDir('skin') is returned.

So in your case correct answer would be:

require(Mage::getDesign()->getSkinBaseDir().DS.'myfunc.php');

Best approach to real time http streaming to HTML5 video client

One way to live-stream a RTSP-based webcam to a HTML5 client (involves re-encoding, so expect quality loss and needs some CPU-power):

  • Set up an icecast server (could be on the same machine you web server is on or on the machine that receives the RTSP-stream from the cam)
  • On the machine receiving the stream from the camera, don't use FFMPEG but gstreamer. It is able to receive and decode the RTSP-stream, re-encode it and stream it to the icecast server. Example pipeline (only video, no audio):

    gst-launch-1.0 rtspsrc location=rtsp://192.168.1.234:554 user-id=admin user-pw=123456 ! rtph264depay ! avdec_h264 ! vp8enc threads=2 deadline=10000 ! webmmux streamable=true ! shout2send password=pass ip=<IP_OF_ICECAST_SERVER> port=12000 mount=cam.webm
    

=> You can then use the <video> tag with the URL of the icecast-stream (http://127.0.0.1:12000/cam.webm) and it will work in every browser and device that supports webm

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

Facebook API "This app is in development mode"

I know its a little bit late but someone may find this useful in future.

STEP 1:

Login to facebook Developer -> Your App

In Settings -> Basic -> Contact Email. (Give any email)

STEP 2:

And in 'App Review' Tab : change

Do you want to make this app and all its live features available to the general public? Yes

And you app will be live now ..

Is there a library function for Root mean square error (RMSE) in python?

You can't find RMSE function directly in SKLearn. But , instead of manually doing sqrt , there is another standard way using sklearn. Apparently, Sklearn's mean_squared_error itself contains a parameter called as "squared" with default value as true .If we set it to false ,the same function will return RMSE instead of MSE.

# code changes implemented by Esha Prakash
from sklearn.metrics import mean_squared_error
rmse = mean_squared_error(y_true, y_pred , squared=False)

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

How should I load files into my Java application?

public static String loadTextFile(File f) {
    try {
        BufferedReader r = new BufferedReader(new FileReader(f));
        StringWriter w = new StringWriter();

        try {
            String line = reader.readLine();
            while (null != line) {
                w.append(line).append("\n");
                line = r.readLine();
            }

            return w.toString();
        } finally {
            r.close();
            w.close();
        }
    } catch (Exception ex) {
        ex.printStackTrace();

        return "";
    }
}

How do I use arrays in cURL POST requests

You are just creating your array incorrectly. You could use http_build_query:

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );
$fields_string = http_build_query($fields);

So, the entire code that you could use would be:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>

SQL Server: combining multiple rows into one row

There's a convenient method for this in MySql called GROUP_CONCAT. An equivalent for SQL Server doesn't exist, but you can write your own using the SQLCLR. Luckily someone already did that for you.

Your query then turns into this (which btw is a much nicer syntax):

SELECT CUSTOMFIELD, ISSUE, dbo.GROUP_CONCAT(STRINGVALUE)
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534 AND ISSUE = 19602
GROUP BY CUSTOMFIELD, ISSUE

But please note that this method is good for at the most 100 rows within a group. Beyond that, you'll have major performance problems. SQLCLR aggregates have to serialize any intermediate results and that quickly piles up to quite a lot of work. Keep this in mind!

Interestingly the FOR XML doesn't suffer from the same problem but instead uses that horrendous syntax.

Connecting to local SQL Server database using C#

I like to use the handy process outlined here to build connection strings using a .udl file. This allows you to test them from within the udl file to ensure that you can connect before you run any code.

Hope that helps.

How do I clear this setInterval inside a function?

the_int=window.clearInterval(the_int);

How to print React component on click of a button?

Just sharing what worked in my case as someone else might find it useful. I have a modal and just wanted to print the body of the modal which could be several pages on paper.

Other solutions I tried just printed one page and only what was on screen. Emil's accepted solution worked for me:

https://stackoverflow.com/a/30137174/3123109

This is what the component ended up looking like. It prints everything in the body of the modal.

import React, { Component } from 'react';
import {
    Button,
    Modal,
    ModalBody,
    ModalHeader
} from 'reactstrap';

export default class TestPrint extends Component{
    constructor(props) {
        super(props);
        this.state = {
            modal: false,
            data: [
                'test', 'test', 'test', 'test', 'test', 'test', 
                'test', 'test', 'test', 'test', 'test', 'test', 
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test'            
            ]
        }
        this.toggle = this.toggle.bind(this);
        this.print = this.print.bind(this);
    }

    print() {
        var content = document.getElementById('printarea');
        var pri = document.getElementById('ifmcontentstoprint').contentWindow;
        pri.document.open();
        pri.document.write(content.innerHTML);
        pri.document.close();
        pri.focus();
        pri.print();
    }

    renderContent() {
        var i = 0;
        return this.state.data.map((d) => {
            return (<p key={d + i++}>{i} - {d}</p>)
        });
    }

    toggle() {
        this.setState({
            modal: !this.state.modal
        })
    }

    render() {
        return (
            <div>
                <Button 
                    style={
                        {
                            'position': 'fixed',
                            'top': '50%',
                            'left': '50%',
                            'transform': 'translate(-50%, -50%)'
                        }
                    } 
                    onClick={this.toggle}
                >
                    Test Modal and Print
                </Button>         
                <Modal 
                    size='lg' 
                    isOpen={this.state.modal} 
                    toggle={this.toggle} 
                    className='results-modal'
                >  
                    <ModalHeader toggle={this.toggle}>
                        Test Printing
                    </ModalHeader>
                    <iframe id="ifmcontentstoprint" style={{
                        height: '0px',
                        width: '0px',
                        position: 'absolute'
                    }}></iframe>      
                    <Button onClick={this.print}>Print</Button>
                    <ModalBody id='printarea'>              
                        {this.renderContent()}
                    </ModalBody>
                </Modal>
            </div>
        )
    }
}

Note: However, I am having difficulty getting styles to be reflected in the iframe.

How to check if an integer is within a range of numbers in PHP?

You could whip up a little helper function to do this:

/**
 * Determines if $number is between $min and $max
 *
 * @param  integer  $number     The number to test
 * @param  integer  $min        The minimum value in the range
 * @param  integer  $max        The maximum value in the range
 * @param  boolean  $inclusive  Whether the range should be inclusive or not
 * @return boolean              Whether the number was in the range
 */
function in_range($number, $min, $max, $inclusive = FALSE)
{
    if (is_int($number) && is_int($min) && is_int($max))
    {
        return $inclusive
            ? ($number >= $min && $number <= $max)
            : ($number > $min && $number < $max) ;
    }

    return FALSE;
}

And you would use it like so:

var_dump(in_range(5, 0, 10));        // TRUE
var_dump(in_range(1, 0, 1));         // FALSE
var_dump(in_range(1, 0, 1, TRUE));   // TRUE
var_dump(in_range(11, 0, 10, TRUE)); // FALSE

// etc...

Get the current file name in gulp.src()

If you want to use @OverZealous' answer (https://stackoverflow.com/a/21806974/1019307) in Typescript, you need to import instead of require:

import * as debug from 'gulp-debug';

...

    return gulp.src('./examples/*.html')
        .pipe(debug({title: 'example src:'}))
        .pipe(gulp.dest('./build'));

(I also added a title).

Good font for code presentations?

I'm personally very fond of Inconsolata

How can I get a vertical scrollbar in my ListBox?

The problem with your solution is you're putting a scrollbar around a ListBox where you probably want to put it inside the ListBox.

If you want to force a scrollbar in your ListBox, use the ScrollBar.VerticalScrollBarVisibility attached property.

<ListBox 
    ItemsSource="{Binding}" 
    ScrollViewer.VerticalScrollBarVisibility="Visible">
</ListBox>

Setting this value to Auto will popup the scrollbar on an as needed basis.

Error in plot.window(...) : need finite 'xlim' values

The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA) values. Here's an example:

> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf

In your example this means that in your line plot(costs,pseudor2,type="l"), costs is completely NA. You have to figure out why this is, but that's the explanation of your error.


From comments:

Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.

stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x))

Reading in from System.in - Java

You probably looking for something like this.

FileInputStream in = new FileInputStream("inputFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));

Can I set enum start value in Java?

If you use very big enum types then, following can be useful;

public enum deneme {

    UPDATE, UPDATE_FAILED;

    private static Map<Integer, deneme> ss = new TreeMap<Integer,deneme>();
    private static final int START_VALUE = 100;
    private int value;

    static {
        for(int i=0;i<values().length;i++)
        {
            values()[i].value = START_VALUE + i;
            ss.put(values()[i].value, values()[i]);
        }
    }

    public static deneme fromInt(int i) {
        return ss.get(i);
    }

    public int value() {
    return value;
    }
}

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

For install with zsh and Homebrew:

brew install nvm

Then Add the following to ~/.zshrc or your desired shell configuration file:

export NVM_DIR="$HOME/.nvm"
. "/usr/local/opt/nvm/nvm.sh"

Then install a node version and use it.

nvm install 7.10.1
nvm use 7.10.1

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

I got this error but it is resolved interesting. As first, i got this error at api level 17. When i call a thread (AsyncTask or others) without progress dialog then i call an other thread method again using progress dialog, i got that crash and the reason is about usage of progress dialog.

In my case, there are two results that;

  • I took show(); method of progress dialog before first thread starts then i took dismiss(); method of progress dialog before last thread ends.

So :

ProgresDialog progressDialog = new ...

//configure progressDialog 

progressDialog.show();

start firstThread {
...
}

...

start lastThread {
...
} 

//be sure to finish threads

progressDialog.dismiss();
  • This is so strange but that error has an ability about destroy itself at least for me :)

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

use jQuery to get values of selected checkboxes

var voyageId = new Array(); 
$("input[name='voyageId[]']:checked:enabled").each(function () {
   voyageId.push($(this).val());
});      

Call a function from another file?

You can call the function from a different directory as well, in case you cannot or do not want to have the function in the same directory you are working. You can do this in two ways (perhaps there are more alternatives, but these are the ones that have worked for me).

Alternative 1 Temporarily change your working directory

import os

os.chdir("**Put here the directory where you have the file with your function**")

from file import function

os.chdir("**Put here the directory where you were working**")

Alternative 2 Add the directory where you have your function to sys.path

import sys

sys.path.append("**Put here the directory where you have the file with your function**")

from file import function

Naming conventions for Java methods that return boolean

The convention is to ask a question in the name.

Here are a few examples that can be found in the JDK:

isEmpty()

hasChildren()

That way, the names are read like they would have a question mark on the end.

Is the Collection empty?
Does this Node have children?

And, then, true means yes, and false means no.

Or, you could read it like an assertion:

The Collection is empty.
The node has children

Note:
Sometimes you may want to name a method something like createFreshSnapshot?. Without the question mark, the name implies that the method should be creating a snapshot, instead of checking to see if one is required.

In this case you should rethink what you are actually asking. Something like isSnapshotExpired is a much better name, and conveys what the method will tell you when it is called. Following a pattern like this can also help keep more of your functions pure and without side effects.

If you do a Google Search for isEmpty() in the Java API, you get lots of results.

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

this works for me:

myTuple= tuple(myList)
sql="select fooid from foo where bar in "+str(myTuple)
cursor.execute(sql)

pandas get column average/mean

you can use

df.describe() 

you will get basic statistics of the dataframe and to get mean of specific column you can use

df["columnname"].mean()

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

This problem can also come up when you don't have your constructor immediately call super.

So this will work:

  public Employee(String name, String number, Date date)
  {
    super(....)
  }

But this won't:

  public Employee(String name, String number, Date date)
  {
    // an example of *any* code running before you call super.
    if (number < 5)
    {
       number++;
    }

    super(....)
  }

The reason the 2nd example fails is because java is trying to implicitely call

super(name,number,date)

as the first line in your constructor.... So java doesn't see that you've got a call to super going on later in the constructor. It essentially tries to do this:

  public Employee(String name, String number, Date date)
  {
    super(name, number, date);

    if (number < 5)
    {
       number++;
    }

    super(....)
  }

So the solution is pretty easy... Just don't put code before your super call ;-) If you need to initialize something before the call to super, do it in another constructor, and then call the old constructor... Like in this example pulled from this StackOverflow post:

public class Foo
{
    private int x;

    public Foo()
    {
        this(1);
    }

    public Foo(int x)
    {
        this.x = x;
    }
}

Laravel Fluent Query Builder Join with subquery

I think what you looking for is "joinSub". It's supported from laravel ^5.6. If you using laravel version below 5.6 you can also register it as macro in your app service provider file. like this https://github.com/teamtnt/laravel-scout-tntsearch-driver/issues/171#issuecomment-413062522

$subquery = DB::table('catch-text')
            ->select(DB::raw("user_id,MAX(created_at) as MaxDate"))
            ->groupBy('user_id');

$query = User::joinSub($subquery,'MaxDates',function($join){
          $join->on('users.id','=','MaxDates.user_id');
})->select(['users.*','MaxDates.*']);

Forcing a postback

No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.

Python convert decimal to hex

def tohex(dec):
    x = (dec%16)
    igits = "0123456789ABCDEF"
    digits = list(igits)
    rest = int(dec/16)
    if (rest == 0):
        return digits[x]
    return tohex(rest) + digits[x]

numbers = [0,16,32,48,46,2,55,887]
hex_ = ["0x"+tohex(i) for i in numbers]
print(hex_)

How do I install cURL on cygwin?

apt-cyg is a great installer similar to apt-get to easily install any packages for Cygwin.

$ apt-cyg install curl

Note: apt-cyg should be first installed. You can do this from Windows command line:

cd c:\cygwin
cygwinsetup.exe -q -P wget,tar,qawk, bzip2,vim,lynx

Close Windows cmd, and open Cygwin Bash.

$ lynx -source rawgit.com/transcode-open/apt-cyg/master/apt-cyg > apt-cyg install apt-cyg /bin
$ chmod +x /bin/apt-cyg

"SSL certificate verify failed" using pip to install packages

I had same issue. I was trying to install mysqlclient for my Django project.

In my case the system date/time wasn't up-to date (Windows 8). That's causing the error. So, updated my system date time and ran the command pip install mysqlclient again. And it did the work.

Hope this would be helpful for those people who're executing all the commands out there (suggesting in other answers) without checking their system date/time.

JavaScript style.display="none" or jQuery .hide() is more efficient?

Talking about efficiency:

document.getElementById( 'elemtId' ).style.display = 'none';

What jQuery does with its .show() and .hide() methods is, that it remembers the last state of an element. That can come in handy sometimes, but since you asked about efficiency that doesn't matter here.

How do I get the old value of a changed cell in Excel VBA?

Place the following in the CODE MODULE of a WORKSHEET to track the last value for every cell in the used range:

Option Explicit

Private r As Range
Private Const d = "||"

Public Function ValueLast(r As Range)
    On Error Resume Next
    ValueLast = Split(r.ID, d)(1)
End Function

Private Sub Worksheet_Activate()
    For Each r In Me.UsedRange: Record r: Next
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    For Each r In Target: Record r: Next
End Sub

Private Sub Record(r)
    r.ID = r.Value & d & Split(r.ID, d)(0)
End Sub

And that's it.

This solution uses the obscure and almost never used Range.ID property, which allows the old values to persist when the workbook is saved and closed.

At any time you can get at the old value of a cell and it will indeed be different than a new current value:

With Sheet1
    MsgBox .[a1].Value
    MsgBox .ValueLast(.[a1])
End With

How can I confirm a database is Oracle & what version it is using SQL?

Run this SQL:

select * from v$version;

And you'll get a result like:

BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production
PL/SQL Release 10.2.0.3.0 - Production
CORE    10.2.0.3.0      Production
TNS for Solaris: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production

What's the difference between OpenID and OAuth?

I am currently working on OAuth 2.0 and OpenID connect spec. So here is my understanding: Earlier they were:

  1. OpenID was proprietary implementation of Google allowing third party applications like for newspaper websites you can login using google and comment on an article and so on other usecases. So essentially, no password sharing to newspaper website. Let me put up a definition here, this approach in enterprise approach is called Federation. In Federation, You have a server where you authenticate and authorize (called IDP, Identity Provider) and generally the keeper of User credentials. the client application where you have business is called SP or Service Provider. If we go back to same newspaper website example then newspaper website is SP here and Google is IDP. In enterprise this problem was earlier solved using SAML. that time XML used to rule the software industry. So from webservices to configuration, everything used to go to XML so we have SAML, a complete Federation protocol
  2. OAuth: OAuth saw it's emergence as an standard looking at all these kind of proprietary approaches and so we had OAuth 1.o as standard but addressing only authorization. Not many people noticed but it kind of started picking up. Then we had OAuth 2.0 in 2012. CTOs, Architects really started paying attention as world is moving towards Cloud computing and with computing devices moving towards mobile and other such devices. OAuth kind of looked upon as solving major problem where software customers might give IDP Service to one company and have many services from different vendors like salesforce, SAP, etc. So integration here really looks like federation scenario bit one big problem, using SAML is costly so let's explore OAuth 2.o. Ohh, missed one important point that during this time, Google sensed that OAuth actually doesn't address Authentication, how will IDP give user data to SP (which is actually wonderfully addressed in SAML) and with other loose ends like:

    a. OAuth 2.o doesn't clearly say, how client registration will happen b. it doesn't mention anything about the interaction between SP (Resource Server) and client application (like Analytics Server providing data is Resource Server and application displaying that data is Client)

There are already wonderful answers given here technically, I thought of giving of giving brief evolution perspective

"Object doesn't support this property or method" error in IE11

Best way to solve this until a fix is available (if a fix comes) is to force IE compatibility mode on the user.

Use <META http-equiv="X-UA-Compatible" content="IE=9"> ideally in the masterpage so all pages in your site get the workaround.

How to load image to WPF in runtime?

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...

I think the C# source code goes like this...

Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;

and XAML should be

<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" 
       Name="image1" Stretch="Fill" VerticalAlignment="Top" 
       Source="../Bilder/sas.png"
       Width="350" />  

EDIT

Dynamically I think XAML would provide best way to load Images ...

<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
       x:Name="MyImage"/>

where image.DataContext is string path.

MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";

public class MyImageSourceConverter : IValueConverter
{
    public object Convert(object value_, Type targetType_, 
    object parameter_, System.Globalization.CultureInfo culture_)
    {
        return (new ImageSourceConverter()).ConvertFromString (value.ToString());
    }

    public object ConvertBack(object value, Type targetType, 
    object parameter, CultureInfo culture)
    {
          throw new NotImplementedException();
    }
}

Now as you set a different data context, Image would be automatically loaded at runtime.

What's the difference between SoftReference and WeakReference in Java?

This article can be super helpful to understand strong, soft, weak and phantom references.


To give you a summary,

If you only have weak references to an object (with no strong references), then the object will be reclaimed by GC in the very next GC cycle.

If you only have soft references to an object (with no strong references), then the object will be reclaimed by GC only when JVM runs out of memory.


So you can say that, strong references have ultimate power (can never be collected by GC)

Soft references are powerful than weak references (as they can escape GC cycle until JVM runs out of memory)

Weak references are even less powerful than soft references (as they cannot excape any GC cycle and will be reclaimed if object have no other strong reference).


Restaurant Analogy

  • Waiter - GC
  • You - Object in heap
  • Restaurant area/space - Heap space
  • New Customer - New object that wants table in restaurant

Now if you are a strong customer (analogous to strong reference), then even if a new customer comes in the restaurant or what so ever happnes, you will never leave your table (the memory area on heap). The waiter has no right to tell you (or even request you) to leave the restaurant.

If you are a soft customer (analogous to soft reference), then if a new customer comes in the restaurant, the waiter will not ask you to leave the table unless there is no other empty table left to accomodate the new customer. (In other words the waiter will ask you to leave the table only if a new customer steps in and there is no other table left for this new customer)

If you are a weak customer (analogous to weak reference), then waiter, at his will, can (at any point of time) ask you to leave the restaurant :P

Parsing JSON using C

I used JSON-C for a work project and would recommend it. Lightweight and is released with open licensing.

Documentation is included in the distribution. You basically have *_add functions to create JSON objects, equivalent *_put functions to release their memory, and utility functions that convert types and output objects in string representation.

The licensing allows inclusion with your project. We used it in this way, compiling JSON-C as a static library that is linked in with the main build. That way, we don't have to worry about dependencies (other than installing Xcode).

JSON-C also built for us under OS X (x86 Intel) and Linux (x86 Intel) without incident. If your project needs to be portable, this is a good start.

Meaning of delta or epsilon argument of assertEquals for double values

Which version of JUnit is this? I've only ever seen delta, not epsilon - but that's a side issue!

From the JUnit javadoc:

delta - the maximum delta between expected and actual for which both numbers are still considered equal.

It's probably overkill, but I typically use a really small number, e.g.

private static final double DELTA = 1e-15;

@Test
public void testDelta(){
    assertEquals(123.456, 123.456, DELTA);
}

If you're using hamcrest assertions, you can just use the standard equalTo() with two doubles (it doesn't use a delta). However if you want a delta, you can just use closeTo() (see javadoc), e.g.

private static final double DELTA = 1e-15;

@Test
public void testDelta(){
    assertThat(123.456, equalTo(123.456));
    assertThat(123.456, closeTo(123.456, DELTA));
}

FYI the upcoming JUnit 5 will also make delta optional when calling assertEquals() with two doubles. The implementation (if you're interested) is:

private static boolean doublesAreEqual(double value1, double value2) {
    return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2);
}

Python 2.7: %d, %s, and float()

Try the following:

print "First is: %f" % (first)
print "Second is: %f" % (second)

I am unsure what answer is. But apart from that, this will be:

print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)

There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:

If you try this:

print "First is: %s" % (first)

It converts the float value in first to a string. So that would work as well.

Best way to Bulk Insert from a C# DataTable

This is going to be largely dependent on the RDBMS you're using, and whether a .NET option even exists for that RDBMS.

If you're using SQL Server, use the SqlBulkCopy class.

For other database vendors, try googling for them specifically. For example a search for ".NET Bulk insert into Oracle" turned up some interesting results, including this link back to Stack Overflow: Bulk Insert to Oracle using .NET.

How do I add a bullet symbol in TextView?

You have to use the right character encoding to accomplish this effect. You could try with &#8226;


Update

Just to clarify: use setText("\u2022 Bullet"); to add the bullet programmatically. 0x2022 = 8226

Single controller with multiple GET methods in ASP.NET Web API

I am not sure if u have found the answer, but I did this and it works

public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

// GET /api/values/5
public string Get(int id)
{
    return "value";
}

// GET /api/values/5
[HttpGet]
public string GetByFamily()
{
    return "Family value";
}

Now in global.asx

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapHttpRoute(
    name: "DefaultApi2",
    routeTemplate: "api/{controller}/{action}",
    defaults: new { id = RouteParameter.Optional }
);

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

SSL peer shut down incorrectly in Java

please close the android studio and remove the file

.gradle

and

.idea

file form your project .Hope so it is helpful

Location:Go to Android studio projects->your project ->see both file remove (.gradle & .idea)

How to force a line break in a long word in a DIV?

As mentioned in @davidcondrey's reply, there is not just the ZWSP, but also the SHY &#173; &shy; that can be used in very long, constructed words (think German or Dutch) that have to be broken on the spot you want it to be. Invisible, but it gives a hyphen the moment it's needed, thus keeping both word connected and line filled to the utmost.

That way the word luchthavenpolitieagent might be noted as lucht&shy;haven&shy;politie&shy;agent which gives longer parts than the syllables of the word.
Though I never read anything official about it, these soft hyphens manage to get higher priority in browsers than the official hyphens in the single words of the construct (if they have some extension for it at all).
In practice, no browser is capable of breaking such a long, constructed word by itself; on smaller screens resulting in a new line for it, or in some cases even a one-word-line (like when two of those constructed words follow up).

FYI: it's Dutch for airport police officer

Rendering raw html with reactjs

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.

It is better/safer to sanitise your raw HTML (using e.g., DOMPurify) before injecting it into the DOM via dangerouslySetInnerHTML.

DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks.

Example:

import React from 'react'
import createDOMPurify from 'dompurify'
import { JSDOM } from 'jsdom'

const window = (new JSDOM('')).window
const DOMPurify = createDOMPurify(window)

const rawHTML = `
<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
  </ul>
</div>
`

const YourComponent = () => (
  <div>
    { <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(rawHTML) }} /> }
  </div>
)

export default YourComponent

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

Pattern to match at least 1 upper case character, 1 digit and any special characters and the length between 8 to 63.

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d\\W]{8,63}$"

This pattern was used for JAVA programming.

Read specific columns from a csv file with csv module?

To fetch column name, instead of using readlines() better use readline() to avoid loop & reading the complete file & storing it in the array.

with open(csv_file, 'rb') as csvfile:

    # get number of columns

    line = csvfile.readline()

    first_item = line.split(',')

Responsive table handling in Twitter Bootstrap

If you are using Bootstrap 3 and Less you could apply the responsive tables to all resolutions by updatingthe file:

tables.less

or overwriting this part:

@media (max-width: @screen-xs) {
  .table-responsive {
    width: 100%;
    margin-bottom: 15px;
    overflow-y: hidden;
    overflow-x: scroll;
    border: 1px solid @table-border-color;

    // Tighten up spacing and give a background color
    > .table {
      margin-bottom: 0;
      background-color: #fff;

      // Ensure the content doesn't wrap
      > thead,
      > tbody,
      > tfoot {
        > tr {
          > th,
          > td {
            white-space: nowrap;
          }
        }
      }
    }

    // Special overrides for the bordered tables
    > .table-bordered {
      border: 0;

      // Nuke the appropriate borders so that the parent can handle them
      > thead,
      > tbody,
      > tfoot {
        > tr {
          > th:first-child,
          > td:first-child {
            border-left: 0;
          }
          > th:last-child,
          > td:last-child {
            border-right: 0;
          }
        }
        > tr:last-child {
          > th,
          > td {
            border-bottom: 0;
          }
        }
      }
    }
  }
}

With:

@media (max-width: @screen-lg) {
  .table-responsive {
    width: 100%;
...

Note how I changed the first line @screen-XX value.

I know making all tables responsive may not sound that good, but I found it extremely useful to have this enabled up to LG on large tables (lots of columns).

Hope it helps someone.

Java HTTPS client certificate authentication

Given a p12 file with both the certificate and the private key (generated by openssl, for example), the following code will use that for a specific HttpsURLConnection:

    KeyStore keyStore = KeyStore.getInstance("pkcs12");
    keyStore.load(new FileInputStream(keyStorePath), keystorePassword.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keystorePassword.toCharArray());
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(kmf.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = ctx.getSocketFactory();

    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setSSLSocketFactory(sslSocketFactory);

The SSLContext takes some time to initialize, so you might want to cache it.

How to use the DropDownList's SelectedIndexChanged event

I think this is the culprit:

cmd = new SqlCommand(query, con);

DataTable dt = Select(query);

cmd.ExecuteNonQuery();

ddtype.DataSource = dt;

I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":

cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();

Or you can create a DataTable as explained here:

cmd = new SqlCommand(query, con);

SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);

ddtype.DataSource = listTable;

git ignore vim temporary files

In myy case the temporary files are already commited by previous actions, so modifying .gitignore will not affect those commited files..., you have to git rm files_to_be_ignored --cache first, then commit, then DONE.

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

If you have Cygwin installed (which I strongly recommend for a variety of reasons), you could use the 'file' utility on the DLL

file <filename>

which would give an output like this:

icuuc36.dll: MS-DOS executable PE  for MS Windows (DLL) (GUI) Intel 80386 32-bit

How to Reload ReCaptcha using JavaScript?

grecaptcha.reset(opt_widget_id)

Resets the reCAPTCHA widget. An optional widget id can be passed, otherwise the function resets the first widget created. (from Google's web page)

How do I remove documents using Node.js Mongoose?

If you don't feel like iterating, try FBFriendModel.find({ id:333 }).remove( callback ); or FBFriendModel.find({ id:333 }).remove().exec();

mongoose.model.find returns a Query, which has a remove function.

Update for Mongoose v5.5.3 - remove() is now deprecated. Use deleteOne(), deleteMany() or findOneAndDelete() instead.

How can I use iptables on centos 7?

I modified the /etc/sysconfig/ip6tables-config file changing:

IP6TABLES_SAVE_ON_STOP="no"

To:

IP6TABLES_SAVE_ON_STOP="yes"

And this:

IP6TABLES_SAVE_ON_RESTART="no"

To:

IP6TABLES_SAVE_ON_RESTART="yes"

This seemed to save the changes I made using the iptables commands through a reboot.

2 "style" inline css img tags?

You should use :

<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="25"/>

That should work!!

If you want to create class then :

.size {
width:100px;
height:100px;
}

and then apply it like :

<img src="http://img705.imageshack.us/img705/119/original120x75.png" class="size" alt="25"/>

by creating a class you can use it at multiple places.

If you want to use only at one place then use inline CSS. Also Inline CSS overrides other CSS.

How to debug apk signed for release?

Add the following to your app build.gradle and select the specified release build variant and run

signingConfigs {
        config {
            keyAlias 'keyalias'
            keyPassword 'keypwd'
            storeFile file('<<KEYSTORE-PATH>>.keystore')
            storePassword 'pwd'
        }
    }
    buildTypes {
      release {
          debuggable true
          signingConfig signingConfigs.config
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

How to Troubleshoot Intermittent SQL Timeout Errors

Like the other posters have suggested, it sounds like you have a lock contention issue. We faced a similar issue a few weeks back; however, ours was much more intermittent, and often cleared up before we could get a DBA onto the server to run sp_who2 to trace down the issue.

What we ended up doing was implement an e-mail notification if a lock exceeded a certain threshold. Once we put this in place, we were able to identify the processes that were locking, and change the isolation level to read uncommitted where appropriate to fix the issue.

Here's an article that provides an overview of how to configure this type of notification.

If locking turns out to be the issue, and if you're not already doing so, I would suggest looking into configuring row versioning-based isolation levels.

why are there two different kinds of for loops in java?

The second for loop is any easy way to iterate over the contents of an array, without having to manually specify the number of items in the array(manual enumeration). It is much more convenient than the first when dealing with arrays.

Is it possible to set a custom font for entire of application?

I would like to improve weston's answer for API 21 Android 5.0.

Cause

Under API 21, most of the text styles include fontFamily setting, like:

<style name="TextAppearance.Material">
     <item name="fontFamily">@string/font_family_body_1_material</item>
</style>

Which applys the default Roboto Regular font:

<string name="font_family_body_1_material">sans-serif</string>

The original answer fails to apply monospace font, because android:fontFamily has greater priority to android:typeface attribute (reference). Using Theme.Holo.* is a valid workaround, because there is no android:fontFamily settings inside.

Solution

Since Android 5.0 put system typeface in static variable Typeface.sSystemFontMap (reference), we can use the same reflection technique to replace it:

protected static void replaceFont(String staticTypefaceFieldName,
        final Typeface newTypeface) {
    if (isVersionGreaterOrEqualToLollipop()) {
        Map<String, Typeface> newMap = new HashMap<String, Typeface>();
        newMap.put("sans-serif", newTypeface);
        try {
            final Field staticField = Typeface.class
                    .getDeclaredField("sSystemFontMap");
            staticField.setAccessible(true);
            staticField.set(null, newMap);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    } else {
        try {
            final Field staticField = Typeface.class
                    .getDeclaredField(staticTypefaceFieldName);
            staticField.setAccessible(true);
            staticField.set(null, newTypeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

How to remove focus border (outline) around text/input boxes? (Chrome)

Solution

*:focus {
    outline: 0;
}

PS: Use outline:0 instead of outline:none on focus. It's valid and better practice.

What is the difference between README and README.md in GitHub projects?

README.md or .mkdn or .markdown denotes that the file is markdown formatted. Markdown is a markup language. With it you can easily display headers or have italic words, or bold or almost anything that can be done to text

angularjs to output plain text instead of html

from https://docs.angularjs.org/api/ng/function/angular.element

angular.element

wraps a raw DOM element or HTML string as a jQuery element (If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.")

So you simply could do:

angular.module('myApp.filters', []).
  filter('htmlToPlaintext', function() {
    return function(text) {
      return angular.element(text).text();
    }
  }
);

Usage:

<div>{{myText | htmlToPlaintext}}</div>

How to center and crop an image to always appear in square shape with CSS?

With the caveat of it not working in IE and some older mobile browsers, a simple object-fit: cover; is often the best option.

.cropper {
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;
}
.cropper img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

Without the object-fit: cover support, the image will be stretched oddly to fit the box so, if support for IE is needed, I'd recommend using one of the other answers' approach with -100% top, left, right and bottom values as a fallback.

http://caniuse.com/#feat=object-fit

Is there a wikipedia API just for retrieve content summary?

This url will return summary in xml format.

http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=Agra&MaxHits=1

I have created a function to fetch description of a keyword from wikipedia.

function getDescription($keyword){
    $url='http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString='.urlencode($keyword).'&MaxHits=1';
    $xml=simplexml_load_file($url);
    return $xml->Result->Description;
}
echo getDescription('agra');

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

How to get random value out of an array?

You get a random number out of an array as follows:

$randomValue = $rand[array_rand($rand,1)];

How do I split a string with multiple separators in JavaScript?

Another simple but effective method is to use split + join repeatedly.

"a=b,c:d".split('=').join(',').split(':').join(',').split(',')

Essentially doing a split followed by a join is like a global replace so this replaces each separator with a comma then once all are replaced it does a final split on comma

The result of the above expression is:

['a', 'b', 'c', 'd']

Expanding on this you could also place it in a function:

function splitMulti(str, tokens){
        var tempChar = tokens[0]; // We can use the first token as a temporary join character
        for(var i = 1; i < tokens.length; i++){
            str = str.split(tokens[i]).join(tempChar);
        }
        str = str.split(tempChar);
        return str;
}

Usage:

splitMulti('a=b,c:d', ['=', ',', ':']) // ["a", "b", "c", "d"]

If you use this functionality a lot it might even be worth considering wrapping String.prototype.split for convenience (I think my function is fairly safe - the only consideration is the additional overhead of the conditionals (minor) and the fact that it lacks an implementation of the limit argument if an array is passed).

Be sure to include the splitMulti function if using this approach to the below simply wraps it :). Also worth noting that some people frown on extending built-ins (as many people do it wrong and conflicts can occur) so if in doubt speak to someone more senior before using this or ask on SO :)

    var splitOrig = String.prototype.split; // Maintain a reference to inbuilt fn
    String.prototype.split = function (){
        if(arguments[0].length > 0){
            if(Object.prototype.toString.call(arguments[0]) == "[object Array]" ) { // Check if our separator is an array
                return splitMulti(this, arguments[0]);  // Call splitMulti
            }
        }
        return splitOrig.apply(this, arguments); // Call original split maintaining context
    };

Usage:

var a = "a=b,c:d";
    a.split(['=', ',', ':']); // ["a", "b", "c", "d"]

// Test to check that the built-in split still works (although our wrapper wouldn't work if it didn't as it depends on it :P)
        a.split('='); // ["a", "b,c:d"] 

Enjoy!