Programs & Examples On #Spuser

Represents a user in Microsoft SharePoint Foundation.

How to make a input field readonly with JavaScript?

The above answers did not work for me. The below does: document.getElementById("input_field_id").setAttribute("readonly", true);

And to remove the readonly attribute: document.getElementById("input_field_id").removeAttribute("readonly");

And for running when the page is loaded, it is worth referring to here.

What is the purpose and use of **kwargs?

  • kwargs in **kwargs is just variable name. You can very well have **anyVariableName
  • kwargs stands for "keyword arguments". But I feel they should better be called as "named arguments", as these are simply arguments passed along with names (I dont find any significance to the word "keyword" in the term "keyword arguments". I guess "keyword" usually means words reserved by programming language and hence not to be used by the programmer for variable names. No such thing is happening here in case of kwargs.). So we give names param1 and param2 to two parameter values passed to the function as follows: func(param1="val1",param2="val2"), instead of passing only values: func(val1,val2). Thus, I feel they should be appropriately called "arbitrary number of named arguments" as we can specify any number of these parameters (that is, arguments) if func has signature func(**kwargs)

So being said that let me explain "named arguments" first and then "arbitrary number of named arguments" kwargs.

Named arguments

  • named args should follow positional args
  • order of named args is not important
  • Example

    def function1(param1,param2="arg2",param3="arg3"):
        print("\n"+str(param1)+" "+str(param2)+" "+str(param3)+"\n")
    
    function1(1)                      #1 arg2 arg3   #1 positional arg
    function1(param1=1)               #1 arg2 arg3   #1 named arg
    function1(1,param2=2)             #1 2 arg3      #1 positional arg, 1 named arg
    function1(param1=1,param2=2)      #1 2 arg3      #2 named args       
    function1(param2=2, param1=1)     #1 2 arg3      #2 named args out of order
    function1(1, param3=3, param2=2)  #1 2 3         #
    
    #function1()                      #invalid: required argument missing
    #function1(param2=2,1)            #invalid: SyntaxError: non-keyword arg after keyword arg
    #function1(1,param1=11)           #invalid: TypeError: function1() got multiple values for argument 'param1'
    #function1(param4=4)              #invalid: TypeError: function1() got an unexpected keyword argument 'param4'
    

Arbitrary number of named arguments kwargs

  • Sequence of function parameters:
    1. positional parameters
    2. formal parameter capturing arbitrary number of arguments (prefixed with *)
    3. named formal parameters
    4. formal parameter capturing arbitrary number of named parameters (prefixed with **)
  • Example

    def function2(param1, *tupleParams, param2, param3, **dictionaryParams):
        print("param1: "+ param1)
        print("param2: "+ param2)
        print("param3: "+ param3)
        print("custom tuple params","-"*10)
        for p in tupleParams:
            print(str(p) + ",")
        print("custom named params","-"*10)
        for k,v in dictionaryParams.items():
            print(str(k)+":"+str(v))
    
    function2("arg1",
              "custom param1",
              "custom param2",
              "custom param3",
              param3="arg3",
              param2="arg2", 
              customNamedParam1 = "val1",
              customNamedParam2 = "val2"
              )
    
    # Output
    #
    #param1: arg1
    #param2: arg2
    #param3: arg3
    #custom tuple params ----------
    #custom param1,
    #custom param2,
    #custom param3,
    #custom named params ----------
    #customNamedParam2:val2
    #customNamedParam1:val1
    

Passing tuple and dict variables for custom args

To finish it up, let me also note that we can pass

  • "formal parameter capturing arbitrary number of arguments" as tuple variable and
  • "formal parameter capturing arbitrary number of named parameters" as dict variable

Thus the same above call can be made as follows:

tupleCustomArgs = ("custom param1", "custom param2", "custom param3")
dictCustomNamedArgs = {"customNamedParam1":"val1", "customNamedParam2":"val2"}

function2("arg1",
      *tupleCustomArgs,    #note *
      param3="arg3",
      param2="arg2", 
      **dictCustomNamedArgs     #note **
      )

Finally note * and ** in function calls above. If we omit them, we may get ill results.

Omitting * in tuple args:

function2("arg1",
      tupleCustomArgs,   #omitting *
      param3="arg3",
      param2="arg2", 
      **dictCustomNamedArgs
      )

prints

param1: arg1
param2: arg2
param3: arg3
custom tuple params ----------
('custom param1', 'custom param2', 'custom param3'),
custom named params ----------
customNamedParam2:val2
customNamedParam1:val1

Above tuple ('custom param1', 'custom param2', 'custom param3') is printed as is.

Omitting dict args:

function2("arg1",
      *tupleCustomArgs,   
      param3="arg3",
      param2="arg2", 
      dictCustomNamedArgs   #omitting **
      )

gives

dictCustomNamedArgs
         ^
SyntaxError: non-keyword arg after keyword arg

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

It has been some time since this question has been posted, but maybe it will help someone.

I am using GULP CLI 2.0.1 (installed globally) and GULP 4.0.0 (installed locally) here is how you do it without any additional plugin. I think the code is quite self-explanatory.

var cp = require('child_process'), 
{ src, dest, series, parallel, watch } = require('gulp');

// == availableTasks: log available tasks to console
function availableTasks(done) {
  var command = 'gulp --tasks-simple';
  if (process.argv.indexOf('--verbose') > -1) {
    command = 'gulp --tasks';
  }
  cp.exec(command, function(err, stdout, stderr) {
    done(console.log('Available tasks are:\n' + stdout));
  });
}
availableTasks.displayName = 'tasks';
availableTasks.description = 'Log available tasks to console as plain text list.';
availableTasks.flags = {
  '--verbose': 'Display tasks dependency tree instead of plain text list.'
};
exports.availableTasks = availableTasks;

And run from the console:

gulp availableTasks

Then run and see the differences:

gulp availableTasks --verbose

Calculate mean and standard deviation from a vector of samples in C++ using Boost

Create your own container:

template <class T>
class statList : public std::list<T>
{
    public:
        statList() : std::list<T>::list() {}
        ~statList() {}
        T mean() {
           return accumulate(begin(),end(),0.0)/size();
        }
        T stddev() {
           T diff_sum = 0;
           T m = mean();
           for(iterator it= begin(); it != end(); ++it)
               diff_sum += ((*it - m)*(*it -m));
           return diff_sum/size();
        }
};

It does have some limitations, but it works beautifully when you know what you are doing.

Collection was modified; enumeration operation may not execute in ArrayList

using ArrayList also you can try like this

ArrayList arraylist = ... // myobject data list

ArrayList temp = (ArrayList)arraylist.Clone();

foreach (var item in temp)
{
      if (...)
         arraylist.Remove(item);
}

Print newline in PHP in single quotes

No, because single-quotes even inhibit hex code replacement.

echo 'Hello, world!' . "\xA";

JavaScript backslash (\) in variables is causing an error

You have to escape each \ to be \\:

var ttt = "aa ///\\\\\\";

Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.

because you had to show a message to user that user can't give a name which has (\) character.

I think the scenario is like:

var user_input_name = document.getElementById('the_name').value;

Then the asker wants to check if user_input_name contains any [\]. If so, then alert the user.

If user enters [aa ///\] in HTML input box, then if you alert(user_input_name), you will see [aaa ///\]. You don't need to escape, i.e. replace [\] to be [\\] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.

I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:

var ttt = "aa ///\";

Hence, we assume the asker having problem with escaping.

If you want to simulate, you code must be valid at first place.

var ttt = "aa ///\\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.

alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?

Now, you only need to do is

var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
  alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
  do_something_else();
  }

Edit: I used [] to quote text to be shown, so it would be less confused than using "".

How to get textLabel of selected row in swift?

In swift 4 : by overriding method

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let storyboard = UIStoryboard(name : "Main", bundle: nil)
        let next vc = storyboard.instantiateViewController(withIdentifier: "nextvcIdentifier") as! NextViewController

       self.navigationController?.pushViewController(prayerVC, animated: true)
}

How to schedule a stored procedure in MySQL

If you're open to out-of-the-DB solution: You could set up a cron job that runs a script that will itself call the procedure.

How to iterate through property names of Javascript object?

In JavaScript 1.8.5, Object.getOwnPropertyNames returns an array of all properties found directly upon a given object.

Object.getOwnPropertyNames ( obj )

and another method Object.keys, which returns an array containing the names of all of the given object's own enumerable properties.

Object.keys( obj )

I used forEach to list values and keys in obj, same as for (var key in obj) ..

Object.keys(obj).forEach(function (key) {
      console.log( key , obj[key] );
});

This all are new features in ECMAScript , the mothods getOwnPropertyNames, keys won't supports old browser's.

How to properly create composite primary keys - MYSQL

@AlexCuse I wanted to add this as comment to your answer but gave up after making multiple failed attempt to add newlines in comments.

That said, t1ID is unique in table_1 but that doesn't makes it unique in INFO table as well.

For example:

Table_1 has:
Id Field
1 A
2 B

Table_2 has:
Id Field
1 X
2 Y

INFO then can have:
t1ID t2ID field
1 1 some
1 2 data
2 1 in-each
2 2 row

So in INFO table to uniquely identify a row you need both t1ID and t2ID

How to make Twitter Bootstrap tooltips have multiple lines?

If you are using Angular UI Bootstrap, you can use tooltip with html syntax: tooltip-html-unsafe

e.g. update to angular 1.2.10 & angular-ui-bootstrap 0.11: http://jsfiddle.net/aX2vR/1/

old one: http://jsfiddle.net/8LMwz/1/

Using a dictionary to select function to execute

def p1( ):
    print("in p1")

def p2():
    print("in p2")

myDict={
    "P1": p1,
    "P2": p2

}

name=input("enter P1 or P2")

myDictname

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I had the same error when multiline string included new line (\n) characters. Merging all lines into one (thus removing all new line characters) and sending it to a browser used to solve. But was very inconvenient to code.

Often could not understand why this was an issue in Chrome until I came across to a statement which said that the current version of JavaScript engine in Chrome doesn't support multiline strings which are wrapped in single quotes and have new line (\n) characters in them. To make it work, multiline string need to be wrapped in double quotes. Changing my code to this, resolved this issue.

I will try to find a reference to a standard or Chrome doc which proves this. Until then, try this solution and see if works for you as well.

Owl Carousel, making custom navigation

Create your custom navigation and give them classes you want, then you are ready to go. it's simple as that.

Let's see an example:

_x000D_
_x000D_
<div class="owl-carousel">_x000D_
      <div class="single_img"><img src="1.png" alt=""></div>_x000D_
      <div class="single_img"><img src="2.png" alt=""></div>_x000D_
      <div class="single_img"><img src="3.png" alt=""></div>_x000D_
      <div class="single_img"><img src="4.png" alt=""></div>_x000D_
</div>_x000D_
  _x000D_
<div class="slider_nav">_x000D_
 <button class="am-next">Next</button>_x000D_
 <button class="am-prev">Previous</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In your js file you can do the following:

_x000D_
_x000D_
 $(".owl-carousel").owlCarousel({_x000D_
    // you can use jQuery selector_x000D_
    navText: [$('.am-next'),$('.am-prev')]_x000D_
 _x000D_
});
_x000D_
 
_x000D_
_x000D_
_x000D_

$(document).ready(function() is not working

Did you load jQuery in head section? Did you load it correctly?

<head>
   <script src="scripts/jquery.js"></script>
   ...
</head>

This code assumes jquery.js is in scripts directory. (You can change file name if you like)

You can also use jQuery as hosted by Google:

<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
   ...
</head>

As per your comment:

Apparently, your web server is not configured to return jQuery-1.6.1.js on requesting /webProject/jquery-1.6.1.js. There may be numerous reasons for this, such as wrong file name, folder name, routing settings, etc. You need to create another question and describe your 404 in greater details (such as local file name, operation system, webserver name and settings).

Again, you can use jQuery as provided by Google (see above), however you still might want to find out why some local files don't get served on request.

How Do I Upload Eclipse Projects to GitHub?

While the EGit plugin for Eclipse is a good option, an even better one would be to learn to use git bash -- i.e., git from the command line. It isn't terribly difficult to learn the very basics of git, and it is often very beneficial to understand some basic operations before relying on a GUI to do it for you. But to answer your question:

First things first, download git from http://git-scm.com/. Then go to http://github.com/ and create an account and repository.

On your machine, first you will need to navigate to the project folder using git bash. When you get there you do:

git init

which initiates a new git repository in that directory.

When you've done that, you need to register that new repo with a remote (where you'll upload -- push -- your files to), which in this case will be github. This assumes you have already created a github repository. You'll get the correct URL from your repo in GitHub.

git remote add origin https://github.com/[username]/[reponame].git

You need to add you existing files to your local commit:

git add .   # this adds all the files

Then you need to make an initial commit, so you do:

git commit -a -m "Initial commit" # this stages your files locally for commit. 
                                  # they haven't actually been pushed yet

Now you've created a commit in your local repo, but not in the remote one. To put it on the remote, you do the second line you posted:

git push -u origin --all

Checking if a key exists in a JavaScript object?

Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?

var obj = { key: undefined };
obj["key"] !== undefined // false, but the key exists!

You should instead use the in operator:

"key" in obj // true, regardless of the actual value

If you want to check if a key doesn't exist, remember to use parenthesis:

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // Do not do this! It is equivalent to "false in obj"

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

obj.hasOwnProperty("key") // true

For performance comparison between the methods that are in, hasOwnProperty and key is undefined, see this benchmark

Input group - two inputs close to each other

It almost never makes intuitive sense to have two inputs next to each other without labels. Here is a solution with labels mixed in, which also works quite well with just a minor modification to existing Bootstrap styles.

Preview: enter image description here

HTML:

<div class="input-group">
  <span class="input-group-addon">Between</span>
  <input type="text" class="form-control" placeholder="Type something..." />
  <span class="input-group-addon" style="border-left: 0; border-right: 0;">and</span>
  <input type="text" class="form-control" placeholder="Type something..." />
</div>

CSS:

.input-group-addon {
  border-left-width: 0;
  border-right-width: 0;
}
.input-group-addon:first-child {
  border-left-width: 1px;
}
.input-group-addon:last-child {
  border-right-width: 1px;
}

JSFiddle: http://jsfiddle.net/yLvk5mn1/31/

No module named 'pymysql'

fwiw, for a conda env:

 conda install -c anaconda pymysql 

How to create temp table using Create statement in SQL Server?

Same thing, Just start the table name with # or ##:

CREATE TABLE #TemporaryTable          -- Local temporary table - starts with single #
(
    Col1 int,
    Col2 varchar(10)
    ....
);

CREATE TABLE ##GlobalTemporaryTable   -- Global temporary table - note it starts with ##.
(
    Col1 int,
    Col2 varchar(10)
    ....
);

Temporary table names start with # or ## - The first is a local temporary table and the last is a global temporary table.

Here is one of many articles describing the differences between them.

How to create a signed APK file using Cordova command line interface?

In the current documentation we can specify a build.json with the keystore:

{
     "android": {
         "debug": {
             "keystore": "..\android.keystore",
             "storePassword": "android",
             "alias": "mykey1",
             "password" : "password",
             "keystoreType": ""
         },
         "release": {
             "keystore": "..\android.keystore",
             "storePassword": "",
             "alias": "mykey2",
             "password" : "password",
             "keystoreType": ""
         }
     }
 }

And then, execute the commando with --buildConfig argumente, this way:

cordova run android --buildConfig

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

Center Contents of Bootstrap row container

Try this, it works!

<div class="row">
    <div class="center">
        <div class="col-xs-12 col-sm-4">
            <p>hi 1!</p>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 2!</p>
        </div>
        <div class="col-xs-12 col-sm-4">
            <p>hi 3!</p>
        </div>
    </div>
</div>

Then, in css define the width of center div and center in a document:

.center {
    margin: 0 auto;
    width: 80%;
}

Java, Calculate the number of days between two dates

Java 8 and later: ChronoUnit.between

Use instances of ChronoUnit to calculate amount of time in different units (days,months, seconds).

For Example:

ChronoUnit.DAYS.between(startDate,endDate)

SELECT using 'CASE' in SQL

Try this.

SELECT 
  CASE 
     WHEN FRUIT = 'A' THEN 'APPLE'
     WHEN FRUIT = 'B' THEN 'BANANA'
     ELSE 'UNKNOWN FRUIT'
  END AS FRUIT
FROM FRUIT_TABLE;

Managing large binary files with Git

Another solution, since April 2015 is Git Large File Storage (LFS) (by GitHub).

It uses git-lfs (see git-lfs.github.com) and tested with a server supporting it: lfs-test-server:
You can store metadata only in the git repo, and the large file elsewhere.

https://cloud.githubusercontent.com/assets/1319791/7051226/c4570828-ddf4-11e4-87eb-8fc165e5ece4.gif

Select rows having 2 columns equal value

select * from test;
a1  a2  a3
1   1   2
1   2   2
2   1   2

select t1.a3 from test t1, test t2 where t1.a1 = t2.a1 and t2.a2 = t1.a2 and t1.a1 = t2.a2

a3
1

You can try same thing using Joins too..

How to call a button click event from another method

private void PictureBox1_Click(object sender, EventArgs e)
{
    MessageBox.Show("Click Succes");
}

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13)
    {
        PictureBox1_Click(sender, e); //or try this one "this.PictureBox1_Click(sender, AcceptButton);"
    }
}

How to store directory files listing into an array?

You may be tempted to use (*) but what if a directory contains the * character? It's very difficult to handle special characters in filenames correctly.

You can use ls -ls. However, it fails to handle newline characters.

# Store la -ls as an array
readarray -t files <<< $(ls -ls)
for (( i=1; i<${#files[@]}; i++ ))
{
    # Convert current line to an array
    line=(${files[$i]})
    # Get the filename, joining it together any spaces
    fileName=${line[@]:9}
    echo $fileName
}

If all you want is the file name, then just use ls:

for fileName in $(ls); do
    echo $fileName
done

See this article or this this post for more information about some of the difficulties of dealing with special characters in file names.

What is the standard Python docstring format?

The Google style guide contains an excellent Python style guide. It includes conventions for readable docstring syntax that offers better guidance than PEP-257. For example:

def square_root(n):
    """Calculate the square root of a number.

    Args:
        n: the number to get the square root of.
    Returns:
        the square root of n.
    Raises:
        TypeError: if n is not a number.
        ValueError: if n is negative.

    """
    pass

I like to extend this to also include type information in the arguments, as described in this Sphinx documentation tutorial. For example:

def add_value(self, value):
    """Add a new value.

       Args:
           value (str): the value to add.
    """
    pass

What is this: [Ljava.lang.Object;?

If you are here because of the Liquibase error saying:

Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short

and you are using

not {
  indexExists()
}

precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342

We can try to execute an above check using bare sqlCheck(Postgres):

SELECT COUNT(i.relname)
FROM
    pg_class t,
    pg_class i,
    pg_index ix
WHERE
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and t.relkind = 'r'
    and t.relname = 'tableName'
    and i.relname = 'indexName';

where tableName - is an index table name and indexName - is an index name

What issues should be considered when overriding equals and hashCode in Java?

There are two methods in super class as java.lang.Object. We need to override them to custom object.

public boolean equals(Object obj)
public int hashCode()

Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

public class Test
{
    private int num;
    private String data;
    public boolean equals(Object obj)
    {
        if(this == obj)
            return true;
        if((obj == null) || (obj.getClass() != this.getClass()))
            return false;
        // object must be Test at this point
        Test test = (Test)obj;
        return num == test.num &&
        (data == test.data || (data != null && data.equals(test.data)));
    }

    public int hashCode()
    {
        int hash = 7;
        hash = 31 * hash + num;
        hash = 31 * hash + (null == data ? 0 : data.hashCode());
        return hash;
    }

    // other methods
}

If you want get more, please check this link as http://www.javaranch.com/journal/2002/10/equalhash.html

This is another example, http://java67.blogspot.com/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html

Have Fun! @.@

How do I access my webcam in Python?

John Montgomery's, answer is great, but at least on Windows, it is missing the line

vc.release()

before

cv2.destroyWindow("preview")

Without it, the camera resource is locked, and can not be captured again before the python console is killed.

Named colors in matplotlib

I constantly forget the names of the colors I want to use and keep coming back to this question =)

The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.

I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.

enter image description here

I really didn't change much from the matplotlib example, but here is the code for completeness.

import matplotlib.pyplot as plt
from matplotlib import colors as mcolors


colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)

# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]

n = len(sorted_names)
ncols = 4
nrows = n // ncols

fig, ax = plt.subplots(figsize=(12, 10))

# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols

for i, name in enumerate(sorted_names):
    row = i % nrows
    col = i // nrows
    y = Y - (row * h) - h

    xi_line = w * (col + 0.05)
    xf_line = w * (col + 0.25)
    xi_text = w * (col + 0.3)

    ax.text(xi_text, y, name, fontsize=(h * 0.8),
            horizontalalignment='left',
            verticalalignment='center')

    ax.hlines(y + h * 0.1, xi_line, xf_line,
              color=colors[name], linewidth=(h * 0.8))

ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()

fig.subplots_adjust(left=0, right=1,
                    top=1, bottom=0,
                    hspace=0, wspace=0)
plt.show()

Additional named colors

Updated 2017-10-25. I merged my previous updates into this section.

xkcd

If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:

plt.plot([1,2], lw=4, c='xkcd:baby poop green')

Now you have access to a plethora of named colors!

enter image description here

Tableau

The default Tableau colors are available in matplotlib via the 'tab:' prefix:

plt.plot([1,2], lw=4, c='tab:green')

There are ten distinct colors:

enter image description here

HTML

You can also plot colors by their HTML hex code:

plt.plot([1,2], lw=4, c='#8f9805')

This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...


For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py.


How to install the Raspberry Pi cross compiler on my Linux host machine?

I could not compile QT5 with any of the (fairly outdated) toolchains from git://github.com/raspberrypi/tools.git. The configure script kept failing with an "could not determine architecture" error and with massive path problems for include directories. What worked for me was using the Linaro toolchain

http://releases.linaro.org/components/toolchain/binaries/4.9-2016.02/arm-linux-gnueabihf/runtime-linaro-gcc4.9-2016.02-arm-linux-gnueabihf.tar.xz

in combination with

https://raw.githubusercontent.com/riscv/riscv-poky/master/scripts/sysroot-relativelinks.py

Failing to fix the symlinks of the sysroot leads to undefined symbol errors as described here: An error building Qt libraries for the raspberry pi This happened to me when I tried the fixQualifiedLibraryPaths script from tools.git. Everthing else is described in detail in http://wiki.qt.io/RaspberryPi2EGLFS . My configure settings were:

./configure -opengl es2 -device linux-rpi3-g++ -device-option CROSS_COMPILE=/usr/local/rasp/gcc-linaro-4.9-2016.02-x86_64_arm-linux-gnueabihf/bin/arm-linux-gnueabihf- -sysroot /usr/local/rasp/sysroot -opensource -confirm-license -optimized-qmake -reduce-exports -release -make libs -prefix /usr/local/qt5pi -hostprefix /usr/local/qt5pi

with /usr/local/rasp/sysroot being the path of my local Raspberry Pi 3 Raspbian (Jessie) system copy and /usr/local/qt5pi being the path of the cross compiled QT that also has to be copied to the device. Be aware that Jessie comes with GCC 4.9.2 when you choose your toolchain.

Latest jQuery version on Google's CDN

To use the latest jquery version hosted by Google

Humans:

  1. https://developers.google.com/speed/libraries/#jquery

  2. Get the snippet:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  1. Put it in your code.
  2. Make sure it works.

Bots:

  1. Wait for a human to do it.

How to get the last character of a string in a shell?

Every answer so far implies the word "shell" in the question equates to Bash.

This is how one could do that in a standard Bourne shell:

printf $str | tail -c 1

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

If you declare your callback as mentioned by @lex82 like

callback = "callback(item.id, arg2)"

You can call the callback method in the directive scope with object map and it would do the binding correctly. Like

scope.callback({arg2:"some value"});

without requiring for $parse. See my fiddle(console log) http://jsfiddle.net/k7czc/2/

Update: There is a small example of this in the documentation:

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).

Send json post using php

You can use CURL for this purpose see the example code:

$url = "your url";    
$content = json_encode("your data to be sent");

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}


curl_close($curl);

$response = json_decode($json_response, true);

WAMP server, localhost is not working

Check Your Skype, I had the problem because skype reserved port 80 for incoming calls, I unchecked it , and it works fine.

Can't find @Nullable inside javax.annotation.*

JSR-305 is a "Java Specification Request" to extend the specification. @Nullable etc. were part of it; however it appears to be "dormant" (or frozen) ever since (See this SO question). So to use these annotations, you have to add the library yourself.

FindBugs was renamed to SpotBugs and is being developed under that name.

For maven this is the current annotation-only dependency (other integrations here):

<dependency>
  <groupId>com.github.spotbugs</groupId>
  <artifactId>spotbugs-annotations</artifactId>
  <version>4.2.0</version>
</dependency>

If you wish to use the full plugin, refer to the documentation of SpotBugs.

When to use %r instead of %s in Python?

The %s specifier converts the object using str(), and %r converts it using repr().

For some objects such as integers, they yield the same result, but repr() is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.

Here's an example, using a date:

>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'

Types for which repr() doesn't produce Python syntax include those that point to external resources such as a file, which you can't guarantee to recreate in a different context.

Map and Reduce in .NET

Linq equivalents of Map and Reduce: If you’re lucky enough to have linq then you don’t need to write your own map and reduce functions. C# 3.5 and Linq already has it albeit under different names.

  • Map is Select:

    Enumerable.Range(1, 10).Select(x => x + 2);
    
  • Reduce is Aggregate:

    Enumerable.Range(1, 10).Aggregate(0, (acc, x) => acc + x);
    
  • Filter is Where:

    Enumerable.Range(1, 10).Where(x => x % 2 == 0);
    

https://www.justinshield.com/2011/06/mapreduce-in-c/

How to convert InputStream to FileInputStream

Long story short: Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.

WPF: Setting the Width (and Height) as a Percentage Value

I use two methods for relative sizing. I have a class called Relative with three attached properties To, WidthPercent and HeightPercent which is useful if I want an element to be a relative size of an element anywhere in the visual tree and feels less hacky than the converter approach - although use what works for you, that you're happy with.

The other approach is rather more cunning. Add a ViewBox where you want relative sizes inside, then inside that, add a Grid at width 100. Then if you add a TextBlock with width 10 inside that, it is obviously 10% of 100.

The ViewBox will scale the Grid according to whatever space it has been given, so if its the only thing on the page, then the Grid will be scaled out full width and effectively, your TextBlock is scaled to 10% of the page.

If you don't set a height on the Grid then it will shrink to fit its content, so it'll all be relatively sized. You'll have to ensure that the content doesn't get too tall, i.e. starts changing the aspect ratio of the space given to the ViewBox else it will start scaling the height as well. You can probably work around this with a Stretch of UniformToFill.

Install tkinter for Python

you will need the package and its dependencies.

since you mentioned synaptic, you must be using a Debian based system. one way to get what you need:

sudo apt-get install python-tk

PHP create key => value pairs within a foreach

function createOfferUrlArray($Offer) {
    $offerArray = array();
    foreach ($Offer as $key => $value) { 
        $offerArray[$key] = $value[4];
    }
    return $offerArray;
}

or

function createOfferUrlArray($offer) {
    foreach ( $offer as &$value ) {
        $value = $value[4];
    }
    unset($value);
    return $offer;
}

Chrome says my extension's manifest file is missing or unreadable

Some permissions issue for default sample.

I wanted to see how it works, I am creating the first extension, so I downloaded a simpler one.

Downloaded 'Typed URL History' sample from
https://developer.chrome.com/extensions/examples/api/history/showHistory.zip

which can be found at
https://developer.chrome.com/extensions/samples

this worked great, hope it helps

Quickly create a large file on a Linux system

Linux & all filesystems

xfs_mkfile 10240m 10Gigfile

Linux & and some filesystems (ext4, xfs, btrfs and ocfs2)

fallocate -l 10G 10Gigfile

OS X, Solaris, SunOS and probably other UNIXes

mkfile 10240m 10Gigfile

HP-UX

prealloc 10Gigfile 10737418240

Explanation

Try mkfile <size> myfile as an alternative of dd. With the -n option the size is noted, but disk blocks aren't allocated until data is written to them. Without the -n option, the space is zero-filled, which means writing to the disk, which means taking time.

mkfile is derived from SunOS and is not available everywhere. Most Linux systems have xfs_mkfile which works exactly the same way, and not just on XFS file systems despite the name. It's included in xfsprogs (for Debian/Ubuntu) or similar named packages.

Most Linux systems also have fallocate, which only works on certain file systems (such as btrfs, ext4, ocfs2, and xfs), but is the fastest, as it allocates all the file space (creates non-holey files) but does not initialize any of it.

How to wait until WebBrowser is completely loaded in VB.NET?

I made similar function (only that works to me); sorry it is in C# but easy to translate...

private void WaitForPageLoad () {

     while (pageReady == false)
         Application.DoEvents();

     while (webBrowser1.IsBusy || webBrowser1.ReadyState != WebBrowserReadyState.Complete)
         Application.DoEvents();
}

Typescript ReferenceError: exports is not defined

I solved the issue by removing "type": "module" field from package.json.

IntelliJ: Working on multiple projects

As of release 2019.2, this is as easy as File->Attach Project.

File->Attach Project

See: https://youtrack.jetbrains.com/issue/WEB-7968

SQL SERVER: Check if variable is null and then assign statement for Where Clause

is null is the syntax I use for such things, when COALESCE is of no help.

Try:

if (@zipCode is null)
  begin
    ([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)   
  end
else 
  begin
    ([Portal].[dbo].[Address].PostalCode=@zipCode )
  end  

How do Mockito matchers work?

Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify.

Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.

/* Mockito */  verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));

Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T where Hamcrest matcher methods return Matcher objects (of type Matcher<T>).

Mockito matchers are invoked through static methods such as eq, any, gt, and startsWith on org.mockito.Matchers and org.mockito.AdditionalMatchers. There are also adapters, which have changed across Mockito versions:

  • For Mockito 1.x, Matchers featured some calls (such as intThat or argThat) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T> extended org.hamcrest.Matcher<T>, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.
  • For Mockito 2.0+, Mockito no longer has a direct dependency on Hamcrest. Matchers calls phrased as intThat or argThat wrap ArgumentMatcher<T> objects that no longer implement org.hamcrest.Matcher<T> but are used in similar ways. Hamcrest adapters such as argThat and intThat are still available, but have moved to MockitoHamcrest instead.

Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:

/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));

In the above statement: foo.setPowerLevel is a method that accepts an int. is(greaterThan(9000)) returns a Matcher<Integer>, which wouldn't work as a setPowerLevel argument. The Mockito matcher intThat wraps that Hamcrest-style Matcher and returns an int so it can appear as an argument; Mockito matchers like gt(9000) would wrap that entire expression into a single call, as in the first line of example code.

What matchers do/return

when(foo.quux(3, 5)).thenReturn(true);

When not using argument matchers, Mockito records your argument values and compares them with their equals methods.

when(foo.quux(eq(3), eq(5))).thenReturn(true);    // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different

When you call a matcher like any or gt (greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture() it stores a matcher that saves its argument instead for later inspection.

Matchers return dummy values such as zero, empty collections, or null. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer.class) or an empty List<String> for anyListOf(String.class). Because of type erasure, though, Mockito lacks type information to return any value but null for any() or argThat(...), which can cause a NullPointerException if trying to "auto-unbox" a null primitive value.

Matchers like eq and gt take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo.class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

Implementation details

Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.

Most matcher calls only add to this stack, with an exception for matchers like and, or, and not. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:

when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6]      [5]  [1]       [4] [2]     [3]

This will:

  1. Add anyInt() to the stack.
  2. Add gt(10) to the stack.
  3. Add lt(20) to the stack.
  4. Remove gt(10) and lt(20) and add and(gt(10), lt(20)).
  5. Call foo.quux(0, 0), which (unless otherwise stubbed) returns the default value false. Internally Mockito marks quux(int, int) as the most recent call.
  6. Call when(false), which discards its argument and prepares to stub method quux(int, int) identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any() matcher for its first argument and and(gt(10), lt(20)) for its second argument and clears the stack.

This demonstrates a few rules:

  • Mockito can't tell the difference between quux(anyInt(), 0) and quux(0, anyInt()). They both look like a call to quux(0, 0) with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.

  • Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.

    int between10And20 = and(gt(10), lt(20));
    /* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
    // Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
    
    public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
    /* OK */  when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
    // The helper method calls the matcher methods in the right order.
    
  • The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when or verify, but Mockito can't check that automatically. You can check manually with Mockito.validateMockitoUsage().

  • In a call to when, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values). doReturn and doAnswer (etc) do not invoke the actual method and are often a useful alternative.

  • If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq matcher), Mockito would check the stack length against that call instead, and likely fail.

  • If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.

Common problems

  • InvalidUseOfMatchersException:

    • Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when or verify call. Matchers should never be used as stubbed return values or fields/variables.

    • Check that you're not calling a mock as a part of providing a matcher argument.

    • Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.

  • NullPointerException with primitive arguments: (Integer) any() returns null while any(Integer.class) returns 0; this can cause a NullPointerException if you're expecting an int instead of an Integer. In any case, prefer anyInt(), which will return zero and also skip the auto-boxing step.

  • NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz) will actually call foo.bar(null), which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any()) skips the stubbed behavior.

General troubleshooting

  • Use MockitoJUnitRunner, or explicitly call validateMockitoUsage in your tearDown or @After method (which the runner would do for you automatically). This will help determine whether you've misused matchers.

  • For debugging purposes, add calls to validateMockitoUsage in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.

How to temporarily exit Vim and go back

Assuming terminal Vim on a flavor of *nix:

To suspend your running Vim

Ctrl + Z

will suspend the process and get back to your shell

fg

will resume (bring to foreground) your suspended Vim.

To start a new shell

Start a subshell using:

:sh

(as configured by)

:set shell?

or

:!bash

followed by:

Ctrl+D (or exit, but why type so much?)

to kill the shell and return to Vim.

What is the difference between .*? and .* regular expressions?

Let's say you have:

<a></a>

<(.*)> would match a></a where as <(.*?)> would match a. The latter stops after the first match of >. It checks for one or 0 matches of .* followed by the next expression.

The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.

jQuery: load txt file and insert into div

Try

$(".text").text(data);

Or to convert the data received to a string.

Sequelize, convert entity to plain object

Best and the simple way of doing is :

Just use the default way from Sequelize

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    },
    raw : true // <----------- Magic is here
}).success(function (sensors) {
        console.log(sensors);
});

Note : [options.raw] : Return raw result. See sequelize.query for more information.


For the nested result/if we have include model , In latest version of sequlize ,

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    },
    include : [
        { model : someModel }
    ]
    raw : true , // <----------- Magic is here
    nest : true // <----------- Magic is here
}).success(function (sensors) {
        console.log(sensors);
});

Vue JS mounted()

Abstract your initialization into a method, and call the method from mounted and wherever else you want.

new Vue({
  methods:{
    init(){
      //call API
      //Setup game
    }
  },
  mounted(){
    this.init()
  }
})

Then possibly have a button in your template to start over.

<button v-if="playerWon" @click="init">Play Again</button>

In this button, playerWon represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init.

Difference between int and double

Short answer:

int uses up 4 bytes of memory (and it CANNOT contain a decimal), double uses 8 bytes of memory. Just different tools for different purposes.

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

Replace specific characters within strings

Summarizing 2 ways to replace strings:

group<-data.frame(group=c("12357e", "12575e", "197e18", "e18947"))

1) Use gsub

group$group.no.e <- gsub("e", "", group$group)

2) Use the stringr package

group$group.no.e <- str_replace_all(group$group, "e", "")

Both will produce the desire output:

   group group.no.e
1 12357e      12357
2 12575e      12575
3 197e18      19718
4 e18947      18947

typedef fixed length array

Here's a short example of why typedef array can be confusingly inconsistent. The other answers provide a workaround.

#include <stdio.h>
typedef char type24[3];

int func(type24 a) {
        type24 b;
        printf("sizeof(a) is %zu\n",sizeof(a));
        printf("sizeof(b) is %zu\n",sizeof(b));
        return 0;
}

int main(void) {
        type24 a;
        return func(a);
}

This produces the output

sizeof(a) is 8
sizeof(b) is 3

because type24 as a parameter is a pointer. (In C, arrays are always passed as pointers.) The gcc8 compiler will issue a warning by default, thankfully.

How to rename JSON key

  1. Parse the JSON
const arr = JSON.parse(json);
  1. For each object in the JSON, rename the key:
obj.id = obj._id;
delete obj._id;
  1. Stringify the result

All together:

_x000D_
_x000D_
function renameKey ( obj, oldKey, newKey ) {
  obj[newKey] = obj[oldKey];
  delete obj[oldKey];
}

const json = `
  [
    {
      "_id":"5078c3a803ff4197dc81fbfb",
      "email":"[email protected]",
      "image":"some_image_url",
      "name":"Name 1"
    },
    {
      "_id":"5078c3a803ff4197dc81fbfc",
      "email":"[email protected]",
      "image":"some_image_url",
      "name":"Name 2"
    }
  ]
`;
   
const arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );

console.log( updatedJson );
_x000D_
_x000D_
_x000D_

CSS two divs next to each other

Unfortunately, this is not a trivial thing to solve for the general case. The easiest thing would be to add a css-style property "float: right;" to your 200px div, however, this would also cause your "main"-div to actually be full width and any text in there would float around the edge of the 200px-div, which often looks weird, depending on the content (pretty much in all cases except if it's a floating image).

EDIT: As suggested by Dom, the wrapping problem could of course be solved with a margin. Silly me.

Error: Cannot access file bin/Debug/... because it is being used by another process

It could be too late. But, I encountered similar problem and in my case the project had self reference. Hence, deleting it from the References worked like a charm!!!

Communicating between a fragment and an activity - best practices

The suggested method for communicating between fragments is to use callbacks\listeners that are managed by your main Activity.

I think the code on this page is pretty clear: http://developer.android.com/training/basics/fragments/communicating.html

You can also reference the IO 2012 Schedule app, which is designed to be a de-facto reference app. It can be found here: http://code.google.com/p/iosched/

Also, here is a SO question with good info: How to pass data between fragments

difference between new String[]{} and new String[] in java

TL;DR

  • An array variable has to be typed T[]
    (note that T can be an arry type itself -> multidimensional arrays)
  • The length of the array must be determined either by:
    • giving it an explicit size
      (can be int constant or int expression, see n below)
    • initializing all the values inside the array
      (length is implicitly calculated from given elements)
  • Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.

Replies

1. String[] array= new String[]{}; what is the use of { } here ?

It initializes the array with the values between { }. In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0.

2. what is the diff between String array=new String[]; and String array=new String[]{};

The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:

new String[]   // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0]  // size is known, it has 0 elements, explicitly sized

3. when am writing String array=new String[10]{}; got error why ?

(Again, ignoring the missing [] before array) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}. Just make up your mind and use one of those - Java thinks.

help me i am confused

Examples

String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2

(Here, "same as" means it will construct the same array.)

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

Java multiline string

In Eclipse if you turn on the option "Escape text when pasting into a string literal" (in Preferences > Java > Editor > Typing) and paste a multi-lined string whithin quotes, it will automatically add " and \n" + for all your lines.

String str = "paste your text here";

PHP move_uploaded_file() error?

move_uploaded_file() will return:

  1. FALSE if file name is invalid
  2. FALSE and issue a warning in the error log if the apache process does not have read/write permissions to source or destination directories

PHP Error Log

My php error log was at: /var/log/httpd/error_log and had these errors:

Warning: move_uploaded_file(images/robot.jpg): failed to open stream: Permission denied in /var/www/html/mysite/mohealth.php on line 78

Warning: move_uploaded_file(): Unable to move '/tmp/phpsKD2Qm' to 'images/robot.jpg' in /var/www/html/mysite/mohealth.php on line 78

move_uploaded_file() tries to move files from a temporary directory to a destination directory. When apache process tried to move files, it could not read the temporary or write to the destination dir.

  1. Find which user is running Apache (Web Server) Check which user is running the apache service by this command: ps aux | grep httpd. The first column is the user name.

  2. Check Read Permission at Temporary Dir: Your can find the path to your temp dir by calling echo sys_get_tmp_dir(); in a php page. Then on the command line, issue ls -ld /tmp/temporary-dir to see if the apache user has access to read here

  3. Check Write Permission at Destination Dir: issue ls -ld /var/www/html/destination-directory to see if the apache user has access to write here

  4. Add permissions as necessary using chown or chgrp

  5. Restart Apache using sudo service httpd restart

Java FileOutputStream Create File if not exists

FileUtils from apache commons is a pretty good way to achieve this in a single line.

FileOutputStream s = FileUtils.openOutputStream(new File("/home/nikhil/somedir/file.txt"))

This will create parent folders if do not exist and create a file if not exists and throw a exception if file object is a directory or cannot be written to. This is equivalent to:

File file = new File("/home/nikhil/somedir/file.txt");
file.getParentFile().mkdirs(); // Will create parent directories if not exists
file.createNewFile();
FileOutputStream s = new FileOutputStream(file,false);

All the above operations will throw an exception if the current user is not permitted to do the operation.

How to remove \n from a list element?

From Python3 onwards

map no longer returns a list but a mapObject, thus the answer will look something like

>>> map(lambda x:x.strip(),l)
<map object at 0x7f00b1839fd0>

You can read more about it on What’s New In Python 3.0.

map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(...))

So now what are the ways of getting trough this?


Case 1 - The list call over map with a lambda

map returns an iterator. list is a function that can convert an iterator to a list. Hence you will need to wrap a list call around map. So the answer now becomes,

>>> l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> list(map(lambda x:x.strip(),l))
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

Very good, we get the output. Now we check the amount of time it takes for this piece of code to execute.

$ python3 -m timeit "l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n'];list(map(lambda x:x.strip(),l))"
100000 loops, best of 3: 2.22 usec per loop

2.22 microseconds. That is not so bad. But are there more efficient ways?


Case 2 - The list call over map withOUT a lambda

lambda is frowned upon by many in the Python community (including Guido). Apart from that it will greatly reduce the speed of the program. Hence we need to avoid that as much as possible. The toplevel function str.strip. Comes to our aid here.

The map can be re-written without using lambda using str.strip as

>>> list(map(str.strip,l))
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

And now for the times.

$ python3 -m timeit "l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n'];list(map(str.strip,l))"
1000000 loops, best of 3: 1.38 usec per loop

Fantastic. You can see the efficiency differences between the two ways. It is nearly 60% faster. Thus the approach without using a lambda is a better choice here.


Case 3 - Following Guidelines, The Regular way

Another important point from What’s New In Python 3.0 is that it advices us to avoid map where possible.

Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).

So we can solve this problem without a map by using a regular for loop.

The trivial way of solving (the brute-force) would be:-

>>> l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> final_list = []
>>> for i in l:
...     final_list.append(i.strip())
... 
>>> final_list
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

The timing setup

def f():
    l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
    final_list = []
    for i in l:
         final_list.append(i.strip())
import timeit
print(min(timeit.repeat("f()","from __main__ import f")))

And the result.

1.5322505849981098

As you can see the brute-force is a bit slower here. But it is definitely more readable to a common programmer than a map clause.


Case 4 - List Comprehensions

A list comprehension here is also possible and is the same as in Python2.

>>> [i.strip() for i in l]
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

Now for the timings:

$ python3 -m timeit "l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n'];[i.strip() for i in l]"
1000000 loops, best of 3: 1.28 usec per loop

As you can see the list-comprehension is more effective than map (even that without a lambda). Hence the thumb rule in Python3 is to use a list comprehension instead of map


Case 5 - In-Place mechanisms and Space Efficiency (T-M-T)

A final way is to make the changes in-place within the list itself. This will save a lot of memory space. This can be done using enumerate.

>>> l = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> for i,s in enumerate(l):
...     l[i] = s.strip()
... 
>>> l
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

The timing result would be 1.4806894720022683. But however this way is space effective.


Conclusion

A comparitive list of timings (Both Python 3.4.3 and Python 3.5.0)

----------------------------------------------------
|Case| method          | Py3.4 |Place| Py3.5 |Place|
|----|-----------------|-------|-----|-------|-----|
| 1  | map with lambda | 2.22u | 5   | 2.85u | 5   |
| 2  | map w/o lambda  | 1.38u | 2   | 2.00u | 2   |
| 3  | brute-force     | 1.53u | 4   | 2.22u | 4   |
| 4  | list comp       | 1.28u | 1   | 1.25u | 1   |
| 5  | in-place        | 1.48u | 3   | 2.14u | 3   |
----------------------------------------------------

Finally note that the list-comprehension is the best way and the map using lambda is the worst. But again --- ONLY IN PYTHON3

Using putty to scp from windows to Linux

You can use PSCP to copy files from Windows to Linux.

  1. Download PSCP from putty.org
  2. Open cmd in the directory with pscp.exe file
  3. Type command pscp source_file user@host:destination_file

Reference

Popup window in winform c#

If you mean to create a new form when a button is clicked, the below code may be of some use to you:

private void settingsButton_Click(Object sender, EventArgs e)
{
    // Create a new instance of the Form2 class
    Form2 settingsForm = new Form2();

    // Show the settings form
    settingsForm.Show();
}

From here, you could also use the 'Show Dialog' method

simple custom event

This is an easy way to create custom events and raise them. You create a delegate and an event in the class you are throwing from. Then subscribe to the event from another part of your code. You have already got a custom event argument class so you can build on that to make other event argument classes. N.B: I have not compiled this code.

public partial class Form1 : Form
{
    private TestClass _testClass;
    public Form1()
    {
        InitializeComponent();
        _testClass = new TestClass();
        _testClass.OnUpdateStatus += new TestClass.StatusUpdateHandler(UpdateStatus);
    }

    private void UpdateStatus(object sender, ProgressEventArgs e)
    {
        SetStatus(e.Status);
    }

    private void SetStatus(string status)
    {
        label1.Text = status;
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
         TestClass.Func();
    }

}

public class TestClass
{
    public delegate void StatusUpdateHandler(object sender, ProgressEventArgs e);
    public event StatusUpdateHandler OnUpdateStatus;

    public static void Func()
    {
        //time consuming code
        UpdateStatus(status);
        // time consuming code
        UpdateStatus(status);
    }

    private void UpdateStatus(string status)
    {
        // Make sure someone is listening to event
        if (OnUpdateStatus == null) return;

        ProgressEventArgs args = new ProgressEventArgs(status);
        OnUpdateStatus(this, args);
    }
}

public class ProgressEventArgs : EventArgs
{
    public string Status { get; private set; }

    public ProgressEventArgs(string status)
    {
        Status = status;
    }
}

Cannot use a leading ../ to exit above the top directory

I got same problem... and I did it.

My code before:

<link rel="stylesheet" href="../css/style.default.css" type="text/css" />

And the problem solved after I changed my code into this:

<link rel="stylesheet" href="css/style.default.css" type="text/css" />

So I think "href=../" is not allowed, because I don't have problem when I use "../" in "src=../"

Check whether specific radio button is checked

WHy bother with all of the fancy selectors? If you're using those id="" attributes properly, then 'test2' must be the only tag with that id on the page, then the .checked boolean property will tell you if it's checked or not:

if ($('test2').checked) {
    ....
}

You've also not set any values for those radio buttons, so no matter which button you select, you'll just get a blank "testGroup=" submitted to the server.

How to change maven java home

Even if you install the Oracle JDK, your $JAVA_HOME variable should refer to the path of the JRE that is inside the JDK root. You can refer to my other answer to a similar question for more details.

Formatting a Date String in React Native

The Date constructor is very picky about what it allows. The string you pass in must be supported by Date.parse(), and if it is unsupported, it will return NaN. Different versions of JavaScript do support different formats, if those formats deviate from the official ISO documentation.

See the examples here for what is supported: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

What are the sizes used for the iOS application splash screen?

As of July 2013 (iOS 6), this is what we always use:

IPHONE SPLASH 
Default.png - 320 x 480
[email protected] - 640 x 960 
[email protected] - 640 x 1096 (with status bar)
[email protected] - 640 x 1136 (without status bar)

IPAD SPLASH 
iPadImage-Appname-Portrait.png * 768w x 1004h (with status bar)
[email protected] * 1536w x 2008h (with status bar)
iPadImage-Appname-Landscape.png ** 1024w x 748h (with status bar)
[email protected] ** 2048w x 1496h (with status bar)

iPadImage-Appname-Portrait.png * 768w x 1024h (without status bar)
[email protected] * 1536w x 2048h (without status bar)
iPadImage-Appname-Landscape.png ** 1024w x 768h (without status bar)
[email protected] ** 2048w x 1536h (without status bar)

ICON
Appname-29.png
[email protected]
Appname-50.png
[email protected]
Appname-57.png
[email protected]
Appname-72.png
[email protected]
iTunesArtwork (512px x 512px)
iTunesArtwork@2x (1024px x 1024px)

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

I use a tool called Android Icon Set in the Eclipse for standard icons like Launcher, ActionBar, Tab icons and notification icons. You can launch it from File --> New --> Other.. --> Android --> Android Icon Set. The best part is that you can choose any file from your computer and it will automatically place all the images of standard sizes into your project directory.

enter image description here

Close virtual keyboard on button press

mMyTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // hide virtual keyboard
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(m_txtSearchText.getWindowToken(), 
                                      InputMethodManager.RESULT_UNCHANGED_SHOWN);
            return true;
        }
        return false;
    }
});

Which Python memory profiler is recommended?

Consider the objgraph library (see this blog post for an example use case).

Name node is in safe mode. Not able to leave

The Command did not work for me but the following did

hdfs dfsadmin -safemode leave

I used the hdfs command instead of the hadoop command.

Check out http://ask.gopivotal.com/hc/en-us/articles/200933026-HDFS-goes-into-readonly-mode-and-errors-out-with-Name-node-is-in-safe-mode- link too

findViewByID returns null

In addition of the above solutions you make sure the
tools:context=".TakeMultipleImages" in the layout is same value in the mainfest.xml file :
android:name=".TakeMultipleImages" for the same activity element. it is occur when use copy and paste to create new activity

What is the difference between prefix and postfix operators?

There are two examples illustrates difference

int a , b , c = 0 ; 
a = ++c ; 
b = c++ ;
printf (" %d %d %d " , a , b , c++);
  • Here c has value 0 c increment by 1 then assign value 1 to a so value of a = 1 and value of c = 1
  • next statement assiagn value of c = 1 to b then increment c by 1 so value of b = 1 and value of c = 2

  • in printf statement we have c++ this mean that orginal value of c which is 2 will printed then increment c by 1 so printf statement will print 1 1 2 and value of c now is 3

you can use http://pythontutor.com/c.html

int a , b , c = 0 ; 
a = ++c ; 
b = c++ ;
printf (" %d %d %d " , a , b , ++c);
  • Here in printf statement ++c will increment value of c by 1 first then assign new value 3 to c so printf statement will print 1 1 3

How to get numeric position of alphabets in java?

Another way to do this problem besides using ASCII conversions is the following:

String input = "abc".toLowerCase();
final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < input.length(); i++){
    System.out.print(alphabet.indexOf(input.charAt(i))+1);
}

Convert Float to Int in Swift

var i = 1 as Int

var cgf = CGFLoat(i)

A failure occurred while executing com.android.build.gradle.internal.tasks

Finally found a solution for this by adding this line to gradle.properties.

org.gradle.jvmargs=-Xmx4608m

Moment.js - How to convert date string into date?

If you are getting a JS based date String then first use the new Date(String) constructor and then pass the Date object to the moment method. Like:

var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

In case dateString is 15-07-2016, then you should use the moment(date:String, format:String) method

var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

How can I simulate an array variable in MySQL?

Try using FIND_IN_SET() function of MySql e.g.

SET @c = 'xxx,yyy,zzz';

SELECT * from countries 
WHERE FIND_IN_SET(countryname,@c);

Note: You don't have to SET variable in StoredProcedure if you are passing parameter with CSV values.

Open multiple Projects/Folders in Visual Studio Code

October 2017 (version 1.18):

Support for multi-root workspaces is now enabled by default in the Stable release: https://code.visualstudio.com/updates/v1_18#_support-for-multi-root-workspaces

Now we can open multiple folders in one instance, Visual studio code has named as Workspace ("Area de Trabajo"). Take a look at the images, it´s very simple.

enter image description here

enter image description here

How to find all the tables in MySQL with specific column names in them?

More simply done in one line of SQL:

SELECT * FROM information_schema.columns WHERE column_name = 'column_name';

How do I post form data with fetch api?

With fetch api it turned out that you do NOT have to include headers "Content-type": "multipart/form-data".

So the following works:

let formData = new FormData()
formData.append("nameField", fileToSend)

fetch(yourUrlToPost, {
   method: "POST",
   body: formData
})

Note that with axios I had to use the content-type.

PHP Warning Permission denied (13) on session_start()

You don't appear to have write permission to the /tmp directory on your server. This is a bit weird, but you can work around it. Before the call to session_start() put in a call to session_save_path() and give it the name of a directory writable by the server. Details are here.

'any' vs 'Object'

Object is more restrictive than any. For example:

let a: any;
let b: Object;

a.nomethod(); // Transpiles just fine
b.nomethod(); // Error: Property 'nomethod' does not exist on type 'Object'.

The Object class does not have a nomethod() function, therefore the transpiler will generate an error telling you exactly that. If you use any instead you are basically telling the transpiler that anything goes, you are providing no information about what is stored in a - it can be anything! And therefore the transpiler will allow you to do whatever you want with something defined as any.

So in short

  • any can be anything (you can call any method etc on it without compilation errors)
  • Object exposes the functions and properties defined in the Object class.

How to update data in one table from corresponding data in another table in SQL Server 2005

UPDATE table1
SET column1 = (SELECT expression1
               FROM table2
               WHERE conditions)
[WHERE conditions];

How to get only the date value from a Windows Forms DateTimePicker control?

Try this

var store = dtpDateTimePicker.Value.Date;

store can be anything entity object etc.

T-SQL substring - separating first and last name

validate last name is blank

SELECT  
person.fullName,
(CASE WHEN 0 = CHARINDEX(' ', person.fullName) 
    then  person.fullName 
    ELSE SUBSTRING(person.fullName, 1, CHARINDEX(' ', person.fullName)) end) as first_name,  
(CASE WHEN 0 = CHARINDEX(' ', person.fullName) 
    THEN ''  
    ELSE SUBSTRING(person.fullName,CHARINDEX(' ', person.fullName), LEN(person.fullName) )end) last_name

FROM person

Nth word in a string variable

Using awk

echo $STRING | awk -v N=$N '{print $N}'

Test

% N=3
% STRING="one two three four"
% echo $STRING | awk -v N=$N '{print $N}'
three

XML to CSV Using XSLT

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'&quot;'" />
  <xsl:param name="break" select="'&#xA;'" />

  <xsl:template match="/">
    <xsl:apply-templates select="projects/project" />
  </xsl:template>

  <xsl:template match="project">
    <xsl:apply-templates />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$break" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="*">
    <!-- remove normalize-space() if you want keep white-space at it is --> 
    <xsl:value-of select="concat($quote, normalize-space(), $quote)" />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$delim" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="text()" />
</xsl:stylesheet>

How to Convert a Text File into a List in Python

Maybe:

crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

How to format DateTime columns in DataGridView?

I used these code Hope it could help

dataGridView2.Rows[n].Cells[3].Value = item[2].ToString();
dataGridView2.Rows[n].Cells[3].Value = Convert.ToDateTime(item[2].ToString()).ToString("d");

How to use Lambda in LINQ select statement

Why not just use all Lambda syntax?

database.Stores.Where(s => s.CompanyID == curCompany.ID)
               .Select(s => new SelectListItem
                   {
                       Value = s.Name,
                       Text = s.ID
                   });

Using Chrome, how to find to which events are bound to an element

findEventHandlers is a jquery plugin, the raw code is here: https://raw.githubusercontent.com/ruidfigueiredo/findHandlersJS/master/findEventHandlers.js

Steps

  1. Paste the raw code directely into chrome's console(note:must have jquery loaded already)

  2. Use the following function call: findEventHandlers(eventType, selector);
    to find the corresponding's selector specified element's eventType handler.

Example:

findEventHandlers("click", "#clickThis");

Then if any, the available event handler will show bellow, you need to expand to find the handler, right click the function and select show function definition

See: https://blinkingcaret.wordpress.com/2014/01/17/quickly-finding-and-debugging-jquery-event-handlers/

Move top 1000 lines from text file to a new file using Unix shell commands

head -1000 file.txt > first100lines.txt
tail --lines=+1001 file.txt > restoffile.txt

How to print matched regex pattern using awk?

This is the very basic

awk '/pattern/{ print $0 }' file

ask awk to search for pattern using //, then print out the line, which by default is called a record, denoted by $0. At least read up the documentation.

If you only want to get print out the matched word.

awk '{for(i=1;i<=NF;i++){ if($i=="yyy"){print $i} } }' file

Search for string and get count in vi editor

(similar as Gustavo said, but additionally: )

For any previously search, you can do simply:

:%s///gn

A pattern is not needed, because it is already in the search-register (@/).

"%" - do s/ in the whole file
"g" - search global (with multiple hits in one line)
"n" - prevents any replacement of s/ -- nothing is deleted! nothing must be undone!
(see: :help s_flag for more informations)

(This way, it works perfectly with "Search for visually selected text", as described in vim-wikia tip171)

ImportError: No module named tensorflow

with python2

pip show tensorflow to check install

python test.py to run test

with python3

pip3 show tensorflow to check install

python3 test.py to run test

test.py

import tensorflow as tf
import numpy as np

c = np.array([[3.,4], [5.,6], [6.,7]])
step = tf.reduce_mean(c, 1)                                                                                 
with tf.Session() as sess:
    print(sess.run(step))

Or, if you haven't install tensorflow yet, try the offical document

How to get last 7 days data from current datetime to last 7 days in sql server

Hope this will help,

select id,    
NewsHeadline as news_headline,    
NewsText as news_text,    
state,    
CreatedDate as created_on      
from News    
WHERE CreatedDate >= cast(dateadd(day, -7, GETDATE()) as date)
and CreatedDate < cast(GETDATE()+1 as date) order by CreatedDate desc

Using textures in THREE.js

In version r75 of three.js, you should use:

var loader = new THREE.TextureLoader();
loader.load('texture.png', function ( texture ) {
  var geometry = new THREE.SphereGeometry(1000, 20, 20);
  var material = new THREE.MeshBasicMaterial({map: texture, overdraw: 0.5});
  var mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);
});

How to get all groups that a user is a member of?

If you cannot get Get-ADPrincipalGroupMembership to work for you could try logging in as that user then use.

$id = [Security.Principal.WindowsIdentity]::GetCurrent()
$groups = $id.Groups | foreach-object {$_.Translate([Security.Principal.NTAccount])}
$groups | select *

__FILE__ macro shows full path

#include <algorithm>
#include <string>
using namespace std;
string f( __FILE__ );
f = string( (find(f.rbegin(), f.rend(), '/')+1).base() + 1, f.end() );

// searches for the '/' from the back, transfers the reverse iterator 
// into a forward iterator and constructs a new sting with both

PHP refresh window? equivalent to F5 page reload?

with php you can use two redirections. It works same as refresh in some issues.

you can use a page redirect.php and post your last url to it by GET method (for example). then in redirect.php you can change header to location you`ve sent to it by GET method.

like this: your page:

<?php
header("location:redirec.php?ref=".$your_url);
?>

redirect.php:

<?php
$ref_url=$_GET["ref"];
header("location:redirec.php?ref=".$ref_url);
?>

that worked for me good.

Mail multipart/alternative vs multipart/mixed

I hit this issue. This architecture (from Lain's answer) worked for me. Here is the solution in Python.

  • mixed
    • alternative
      • text
      • related
        • html
        • inline image
        • inline image
    • attachment
    • attachment

Here is the main email creation function:

def create_message_with_attachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message_alternative = MIMEMultipart('alternative')
    message_related = MIMEMultipart('related')

    message_related.attach(MIMEText(msgHtml, 'html'))
    message_alternative.attach(MIMEText(msgPlain, 'plain'))
    message_alternative.attach(message_related)

    message.attach(message_alternative)

    print "create_message_with_attachment: file:", attachmentFile
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}

Here is the full code for sending an email containing html/text/attachment:

import httplib2
import os
import oauth2client
from oauth2client import client, tools
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from apiclient import errors, discovery
import mimetypes
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase

SCOPES = 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE1 = 'client_secret.json'
location = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))
CLIENT_SECRET_FILE = os.path.join(location, CLIENT_SECRET_FILE1)
APPLICATION_NAME = 'Gmail API Python Send Email'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-python-email-send.json')
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store)
        print 'Storing credentials to ' + credential_path
    return credentials

def SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    message1 = create_message_with_attachment(sender, to, subject, msgHtml, msgPlain, attachmentFile)
    SendMessageInternal(service, "me", message1)

def SendMessageInternal(service, user_id, message):
    try:
        message = (service.users().messages().send(userId=user_id, body=message).execute())
        print 'Message Id: %s' % message['id']
        return message
    except errors.HttpError, error:
        print 'An error occurred: %s' % error
        return "error"

def create_message_with_attachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message_alternative = MIMEMultipart('alternative')
    message_related = MIMEMultipart('related')

    message_related.attach(MIMEText(msgHtml, 'html'))
    message_alternative.attach(MIMEText(msgPlain, 'plain'))
    message_alternative.attach(message_related)

    message.attach(message_alternative)

    print "create_message_with_attachment: file:", attachmentFile
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}


def main():
    to = "[email protected]"
    sender = "[email protected]"
    subject = "subject"
    msgHtml = "Hi<br/>Html Email"
    msgPlain = "Hi\nPlain Email"
    attachment = "/path/to/file.pdf"
    SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachment)

if __name__ == '__main__':
    main()

Difference between webdriver.get() and webdriver.navigate()

There are some differences between webdriver.get() and webdriver.navigate() method.


get()

As per the API Docs get() method in the WebDriver interface extends the SearchContext and is defined as:

/**
 * Load a new web page in the current browser window. This is done using an HTTP POST operation,
 * and the method will block until the load is complete.
 * This will follow redirects issued either by the server or as a meta-redirect from within the
 * returned HTML.
 * Synonym for {@link org.openqa.selenium.WebDriver.Navigation#to(String)}.
 */
void get(String url);
    
  • Usage:

    driver.get("https://www.google.com/");
    

navigate()

On the other hand, navigate() is the abstraction which allows the WebDriver instance i.e. the driver to access the browser's history as well as to navigate to a given URL. The methods along with the usage are as follows:

  • to(java.lang.String url): Load a new web page in the current browser window.

    driver.navigate().to("https://www.google.com/");
    
  • to(java.net.URL url): Overloaded version of to(String) that makes it easy to pass in a URL.

  • refresh(): Refresh the current page.

    driver.navigate().refresh();
    
  • back(): Move back a single "item" in the browser's history.

    driver.navigate().back();
    
  • forward(): Move a single "item" forward in the browser's history.

    driver.navigate().forward();
    

How can I create a correlation matrix in R?

An example,

 d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
cor(d) # get correlations (returns matrix)

How can you get the Manifest Version number from the App's (Layout) XML variables?

You can use the versionName in XML resources, such as activity layouts. First create a string resource in the app/build.gradle with the following snippet in the android node:

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

So the whole build.gradle file contents may look like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0 rc3'
    defaultConfig {
        applicationId 'com.example.myapplication'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 17
        versionName '0.2.3'
        jackOptions {
            enabled true
        }
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
} 

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:support-v4:23.3.0'
}

Then you can use @string/versionName in the XML. Android Studio will mark it red, but the app will compile without issues. For example, this may be used like this in app/src/main/res/xml/preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title="About"
        android:key="pref_key_about">

        <Preference
            android:key="pref_about_build"
            android:title="Build version"
            android:summary="@string/versionName" />

    </PreferenceCategory>


</PreferenceScreen>

SQL Server - copy stored procedures from one db to another

use

select * from sys.procedures

to show all your procedures;

sp_helptext @objname = 'Procedure_name'

to get the code

and your creativity to build something to loop through them all and generate the export code :)

NodeJS/express: Cache and 304 status code

  • Operating system: Windows
  • Browser: Chrome

I used Ctrl + F5 keyboard combination. By doing so, instead of reading from cache, I wanted to get a new response. The solution is to do hard refresh the page.

On MDN Web Docs:

"The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource."

Git says local branch is behind remote branch, but it's not

The solution is very simple and worked for me.

Try this :

git pull --rebase <url>

then

git push -u origin master

Android button onClickListener

This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent) which belongs to your Activity class.

An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.

Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html

public void startActivity (Intent intent) -- Used to launch a new activity.

So suppose you have two Activity class --

  1. PresentActivity -- This is your current activity from which you want to go the second activity.

  2. NextActivity -- This is your next Activity on which you want to move.

So the Intent would be like this

Intent(PresentActivity.this, NextActivity.class)

Finally this will be the complete code

public class PresentActivity extends Activity {
  protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.content_layout_id);

    final Button button = (Button) findViewById(R.id.button_id);
    button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
              // Perform action on click   
              Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);

              // currentContext.startActivity(activityChangeIntent);

              PresentActivity.this.startActivity(activityChangeIntent);
            }
          });
  }
}

Is it possible to make a Tree View with Angular?

You can use angular-recursion-injector for that: https://github.com/knyga/angular-recursion-injector

Allows you to do unlimited depth nesting with conditioning. Does recompilation only if needed and compiles only right elements. No magic in code.

<div class="node">
  <span>{{name}}</span>

  <node--recursion recursion-if="subNode" ng-model="subNode"></node--recursion>
</div>

One of the things that allows it to work faster and simpler then the other solutions is "--recursion" suffix.

What is the difference between Views and Materialized Views in Oracle?

Views are essentially logical table-like structures populated on the fly by a given query. The results of a view query are not stored anywhere on disk and the view is recreated every time the query is executed. Materialized views are actual structures stored within the database and written to disk. They are updated based on the parameters defined when they are created.

How to export html table to excel or pdf in php

Easiest way to export Excel to Html table

$file_name ="file_name.xls";
$excel_file="Your Html Table Code";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file_name");
echo $excel_file;

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

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

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

Add CSS to <head> with JavaScript?

Edit: As Atspulgs comment suggest, you can achieve the same without jQuery using the querySelector:

document.querySelector('head').innerHTML += '<link rel="stylesheet" href="styles.css" type="text/css"/>';

Older answer below.


You could use the jQuery library to select your head element and append HTML to it, in a manner like:

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');

You can find a complete tutorial for this problem here

Gets last digit of a number

Another interesting way to do it which would also allow more than just the last number to be taken would be:

int number = 124454;
int overflow = (int)Math.floor(number/(1*10^n))*10^n;

int firstDigits = number - overflow;
//Where n is the number of numbers you wish to conserve</code>

In the above example if n was 1 then the program would return: 4

If n was 3 then the program would return 454

Run a single migration file

If you want to run a specific migration, do

$ rake db:migrate:up VERSION=20080906120000

If you want to run migrations multiple times, do

# use the STEP parameter if you need to go more than one version back
$ rake db:migrate:redo STEP=3

If you want to run a single migration multiple times, do

# this is super useful
$ rake db:migrate:redo VERSION=20080906120000

(you can find the version number in the filename of your migration)


Edit: You can also simply rename your migration file, Eg:

20151013131830_my_migration.rb -> 20151013131831_my_migration.rb

Then migrate normally, this will treat the migration as a new one (usefull if you want to migrate on a remote environment (such as staging) on which you have less control.

Edit 2: You can also just nuke the migration entry in the database. Eg:

rails_c> q = "delete from schema_migrations where version = '20151013131830'"
rails_c> ActiveRecord::Base.connection.execute(q)

rake db:migrate will then rerun the up method of the nuked migrations.

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Do I even need a for loop to create a list?

No, you can (and in general circumstances should) use the built-in function range():

>>> range(1,5)
[1, 2, 3, 4]

i.e.

def naturalNumbers(n):
    return range(1, n + 1)

Python 3's range() is slightly different in that it returns a range object and not a list, so if you're using 3.x wrap it all in list(): list(range(1, n + 1)).

How do I get unique elements in this array?

Instead of using an Array, consider using either a Hash or a Set.

Sets behave similar to an Array, only they contain unique values only, and, under the covers, are built on Hashes. Sets don't retain the order that items are put into them unlike Arrays. Hashes don't retain the order either but can be accessed via a key so you don't have to traverse the hash to find a particular item.

I favor using Hashes. In your application the user_id could be the key and the value would be the entire object. That will automatically remove any duplicates from the hash.

Or, only extract unique values from the database, like John Ballinger suggested.

How to create dispatch queue in Swift 3

Since the OP question has already been answered above I just want to add some speed considerations:

It makes a lot of difference what priority class you assign to your async function in DispatchQueue.global.

I don't recommend running tasks with the .background thread priority especially on the iPhone X where the task seems to be allocated on the low power cores.

Here is some real data from a computationally intensive function that reads from an XML file (with buffering) and performs data interpolation:

Device name / .background / .utility / .default / .userInitiated / .userInteractive

  1. iPhone X: 18.7s / 6.3s / 1.8s / 1.8s / 1.8s
  2. iPhone 7: 4.6s / 3.1s / 3.0s / 2.8s / 2.6s
  3. iPhone 5s: 7.3s / 6.1s / 4.0s / 4.0s / 3.8s

Note that the data set is not the same for all devices. It's the biggest on the iPhone X and the smallest on the iPhone 5s.

SVG drop shadow using css3

Easiest way I've found is with feDropShadow.

<filter id="shadow" x="0" y="0" width="200%" height="200%">
  <feDropShadow dx="40" dy="40" stdDeviation="35" flood-color="#ff0000" flood-opacity="1" />
</filter>

On the element:

<path d="..." filter="url(#shadow)"/>

Tomcat: How to find out running tomcat version

Though this is not recent, I thought, my answer can still help others:

cd tomcat/lib 
java -cp catalina.jar org.apache.catalina.util.ServerInfo

and that's it.

Server version: Apache Tomcat/7.0.30
Server built:   May 23 2013 02:54:10
Server number:  7.0.30.0
OS Name:        Linux
OS Version:     3.13.0-36-generic
Architecture:   amd64
JVM Version:    1.7.0_65-b32
JVM Vendor:     Oracle Corporation

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

Open a new tab on button click in AngularJS

Proper HTML way: just surround your button with anchor element and add attribute target="_blank". It is as simple as that:

<a ng-href="{{yourDynamicURL}}" target="_blank">
    <h1>Open me in new Tab</h1>
</a>

where you can set in the controller:

$scope.yourDynamicURL = 'https://stackoverflow.com';

Set initially selected item in Select list in Angular2

Update to angular 4.X.X, there is a new way to mark an option selected:

<select [compareWith]="byId" [(ngModel)]="selectedItem">
  <option *ngFor="let item of items" [ngValue]="item">{{item.name}}
  </option>
</select>

byId(item1: ItemModel, item2: ItemModel) {
  return item1.id === item2.id;
}

Some tutorial here

Disable Scrolling on Body

Set height and overflow:

html, body {margin: 0; height: 100%; overflow: hidden}

http://jsfiddle.net/q99hvawt/

What does the percentage sign mean in Python

Modulus operator; gives the remainder of the left value divided by the right value. Like:

3 % 1 would equal zero (since 3 divides evenly by 1)

3 % 2 would equal 1 (since dividing 3 by 2 results in a remainder of 1).

Assigning the return value of new by reference is deprecated

I recently moved a site using SimplePie (http://simplepie.org/) from a server that was using PHP 5.2.17 to one that is using PHP 5.3.2. It was after this move that I began receiving a list of error messages such as this one:

Deprecated: Assigning the return value of new by reference is deprecated in .../php/simplepie.inc on line 738

After reviewing several discussions of this issue, I cleared things up by replacing all the instances of =& new with = new in the simplepie.inc file.

I'm not experienced enough to know if this will work in all instances where these error messages are received but it worked in this particular case and it may be worth trying.

Why split the <script> tag when writing it with document.write()?

The </script> inside the Javascript string litteral is interpreted by the HTML parser as a closing tag, causing unexpected behaviour (see example on JSFiddle).

To avoid this, you can place your javascript between comments (this style of coding was common practice, back when Javascript was poorly supported among browsers). This would work (see example in JSFiddle):

<script type="text/javascript">
    <!--
    if (jQuery === undefined) {
        document.write('<script type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></script>');
    }
    // -->
</script>

...but to be honest, using document.write is not something I would consider best practice. Why not manipulating the DOM directly?

<script type="text/javascript">
    <!--
    if (jQuery === undefined) {
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', 'http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js');
        document.body.appendChild(script);
    }
    // -->
</script>

Oracle: how to set user password unexpire?

While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE

Let check the parameter value.
If in Case it is :

SQL> show parameter resource_limit
NAME                                 TYPE        VALUE
------------------------------------ ----------- ---------
resource_limit                       boolean     FALSE
Its mean resource limit is off,we ist have to enable it. 

Use the ALTER SYSTEM statement to turn on resource limits. 

SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.

Homebrew: Could not symlink, /usr/local/bin is not writable

For me the solution was to run brew update.

So, DO THIS FIRST.

This might be normal practice for people familiar with homebrew, but I'm not one of those people.

Edit: I discovered that I needed to update by running brew doctor as suggested by @kinnth's answer to this same question.

A general troubleshooting workflow might look like this: 1. run brew update 2. if that doesn't help run brew doctor and follow its directions 3. if that doesn't help check stack overflow

Resize UIImage by keeping Aspect ratio and width

If you don't happen to know if the image will be portrait or landscape (e.g user takes pic with camera), I created another method that takes max width and height parameters.

Lets say you have a UIImage *myLargeImage which is a 4:3 ratio.

UIImage *myResizedImage = [ImageUtilities imageWithImage:myLargeImage 
                                        scaledToMaxWidth:1024 
                                               maxHeight:1024];

The resized UIImage will be 1024x768 if landscape; 768x1024 if portrait. This method will also generate higher res images for retina display.

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size {
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]);
    } else {
        UIGraphicsBeginImageContext(size);
    }
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();

    return newImage;
}

+ (UIImage *)imageWithImage:(UIImage *)image scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height {
    CGFloat oldWidth = image.size.width;
    CGFloat oldHeight = image.size.height;

    CGFloat scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;

    CGFloat newHeight = oldHeight * scaleFactor;
    CGFloat newWidth = oldWidth * scaleFactor;
    CGSize newSize = CGSizeMake(newWidth, newHeight);

    return [ImageUtilities imageWithImage:image scaledToSize:newSize];
}

Append text using StreamWriter

Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.

http://logging.apache.org/log4net/

How do I use JDK 7 on Mac OSX?

How about Netbeans, here is an article how to set it up with NB7:

http://netbeanside61.blogspot.com/2011/06/downloading-openjdk7-binary-for-mac-os.html

Maybe similar steps for Eclipse.

PHP: How to check if a date is today, yesterday or tomorrow

First. You have mistake in using function strtotime see PHP documentation

int strtotime ( string $time [, int $now = time() ] )

You need modify your code to pass integer timestamp into this function.

Second. You use format d.m.Y H:i that includes time part. If you wish to compare only dates, you must remove time part, e.g. `$date = date("d.m.Y");``

Third. I am not sure if it works in the same way for you, but my PHP doesn't understand date format from $timestamp and returns 01.01.1970 02:00 into $match_date

$timestamp = "2014.09.02T13:34";
date('d.m.Y H:i', strtotime($timestamp)) === "01.01.1970 02:00";

You need to check if strtotime($timestamp) returns correct date string. If no, you need to specify format which is used in $timestamp variable. You can do this using one of functions date_parse_from_format or DateTime::createFromFormat

This is a work example:

$timestamp = "2014.09.02T13:34";

$today = new DateTime(); // This object represents current date/time
$today->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison

$match_date = DateTime::createFromFormat( "Y.m.d\\TH:i", $timestamp );
$match_date->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison

$diff = $today->diff( $match_date );
$diffDays = (integer)$diff->format( "%R%a" ); // Extract days count in interval

switch( $diffDays ) {
    case 0:
        echo "//Today";
        break;
    case -1:
        echo "//Yesterday";
        break;
    case +1:
        echo "//Tomorrow";
        break;
    default:
        echo "//Sometime";
}

Getting rid of all the rounded corners in Twitter Bootstrap

There is a very easy way to customize Bootstrap:

  1. Just go to http://getbootstrap.com/customize/
  2. Find all "radius" and modify them as you wish.
  3. Click "Compile and Download" and enjoy your own version of Bootstrap.

Get img src with PHP

$imgTag = <<< LOB
<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />
<img border="0" src="/images/not_match_image.jpg" alt="Image" width="100" height="100" />
LOB;

preg_match('%<img.*?src=["\'](.*?)["\'].*?/>%i', $imgTag, $matches);
$imgSrc = $matches[1];

DEMO


NOTE: You should use an HTML Parser like DOMDocument and NOT a regex.

JTable won't show column headers

The main difference between this answer and the accepted answer is the use of setViewportView() instead of add().

How to put JTable in JScrollPane using Eclipse IDE:

  1. Create JScrollPane container via Design tab.
  2. Stretch JScrollPane to desired size (applies to Absolute Layout).
  3. Drag and drop JTable component on top of JScrollPane (Viewport area).

In Structure > Components, table should be a child of scrollPane. enter image description here

The generated code would be something like this:

JScrollPane scrollPane = new JScrollPane();
...

JTable table = new JTable();
scrollPane.setViewportView(table);

How do I reset a jquery-chosen select option with jQuery?

In Chrome version 49

you need always this code

$("select option:first").prop('selected', true)

How to update a single library with Composer?

To install doctrine/doctrine-fixtures-bundle with version 2.1.* and minimum stability @dev use this:

composer require doctrine/doctrine-fixtures-bundle:2.1.*@dev

then to update only this single package:

composer update doctrine/doctrine-fixtures-bundle

Evaluate if list is empty JSTL

There's also the function tags, a bit more flexible:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">

And here's the tag documentation.

how to toggle (hide/show) a table onClick of <a> tag in java script

inside your function toggleTable when you do this line

document.getElementById("loginLink").onclick = toggleTable(....

you are actually calling the function again. so toggleTable gets called again, and again and again, you're falling in an infinite recursive call.

make it simple.

function toggleTable()
{
     var elem=document.getElementById("loginTable");
     var hide = elem.style.display =="none";
     if (hide) {
         elem.style.display="table";
    } 
    else {
       elem.style.display="none";
    }
}

see this fiddle

What is JSON and why would I use it?

In the Java context, one reason why JSON might want to be used, is that it provides a very good alternative to Java's Serialization framework, which has been shown (historically) to be subject to some fairly serious vulnerabilities.

Joshua Bloch discusses this in depth in Item 85 "Prefer Alternatives to Java Serialization" (Effective Java 3rd Edition)

Java's Serialization was initially meant to translate data structures into a format that could be easily transmitted or stored. JSON meets this requirement, without the serious exploits referred to above.

Access Control Request Headers, is added to header in AJAX request with jQuery

Because you send custom headers so your CORS request is not a simple request, so the browser first sends a preflight OPTIONS request to check that the server allows your request.

Enter image description here

If you turn on CORS on the server then your code will work. You can also use JavaScript fetch instead (here)

_x000D_
_x000D_
let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=My-First-Header,My-Second-Header';_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
    type: 'POST',_x000D_
    url: url,_x000D_
    headers: {_x000D_
        "My-First-Header":"first value",_x000D_
        "My-Second-Header":"second value"_x000D_
    }_x000D_
}).done(function(data) {_x000D_
    alert(data[0].request.httpMethod + ' was send - open chrome console> network to see it');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Here is an example configuration which turns on CORS on nginx (nginx.conf file):

_x000D_
_x000D_
location ~ ^/index\.php(/|$) {_x000D_
   ..._x000D_
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;_x000D_
    add_header 'Access-Control-Allow-Credentials' 'true' always;_x000D_
    if ($request_method = OPTIONS) {_x000D_
        add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)_x000D_
        add_header 'Access-Control-Allow-Credentials' 'true';_x000D_
        add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days_x000D_
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';_x000D_
        add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';_x000D_
        add_header 'Content-Length' 0;_x000D_
        add_header 'Content-Type' 'text/plain charset=UTF-8';_x000D_
        return 204;_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Here is an example configuration which turns on CORS on Apache (.htaccess file)

_x000D_
_x000D_
# ------------------------------------------------------------------------------_x000D_
# | Cross-domain Ajax requests                                                 |_x000D_
# ------------------------------------------------------------------------------_x000D_
_x000D_
# Enable cross-origin Ajax requests._x000D_
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity_x000D_
# http://enable-cors.org/_x000D_
_x000D_
# <IfModule mod_headers.c>_x000D_
#    Header set Access-Control-Allow-Origin "*"_x000D_
# </IfModule>_x000D_
_x000D_
#Header set Access-Control-Allow-Origin "http://example.com:3000"_x000D_
#Header always set Access-Control-Allow-Credentials "true"_x000D_
_x000D_
Header set Access-Control-Allow-Origin "*"_x000D_
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"_x000D_
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
_x000D_
_x000D_
_x000D_

wget can't download - 404 error

Wget 404 error also always happens if you want to download the pages from Wordpress-website by typing

wget -r http://somewebsite.com

If this website is built using Wordpress you'll get such an error:

ERROR 404: Not Found.

There's no way to mirror Wordpress-website because the website content is stored in the database and wget is not able to grab .php files. That's why you get Wget 404 error.

I know it's not this question's case, because Sam only wants to download a single picture, but it can be helpful for others.

Angularjs on page load call function

It's not the angular way, remove the function from html body and use it in controller, or use

angular.element(document).ready

More details are available here: https://stackoverflow.com/a/18646795/4301583

Text to speech(TTS)-Android

https://drive.google.com/open?id=0BzBKpZ4nzNzUR05nVUI1aVF6N1k

package com.keshav.speechtotextexample;

import java.util.ArrayList;
import java.util.Locale;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

   private TextView txtSpeechInput;
   private ImageButton btnSpeak;
   private final int REQ_CODE_SPEECH_INPUT = 100;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
      btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

      // hide the action bar
      getActionBar().hide();

      btnSpeak.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View v) {
            promptSpeechInput();
         }
      });

   }

   /**
    * Showing google speech input dialog
    * */
   private void promptSpeechInput() {
      Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
      intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
      intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
      intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            getString(R.string.speech_prompt));
      try {
         startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
      } catch (ActivityNotFoundException a) {
         Toast.makeText(getApplicationContext(),
               getString(R.string.speech_not_supported),
               Toast.LENGTH_SHORT).show();
      }
   }

   /**
    * Receiving speech input
    * */
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);

      switch (requestCode) {
      case REQ_CODE_SPEECH_INPUT: {
         if (resultCode == RESULT_OK && null != data) {

            ArrayList<String> result = data
                  .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            txtSpeechInput.setText(result.get(0));
         }
         break;
      }

      }
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}


====================================================

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_gradient"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txtSpeechInput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:textColor="@color/white"
        android:textSize="26dp"
        android:textStyle="normal" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="60dp"
        android:gravity="center"
        android:orientation="vertical">

        <ImageButton
            android:id="@+id/btnSpeak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            android:src="@drawable/ico_mic" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="@string/tap_on_mic"
            android:textColor="@color/white"
            android:textSize="15dp"
            android:textStyle="normal" />
    </LinearLayout>

</RelativeLayout>
===============================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Speech To Text</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="speech_prompt">Say something&#8230;</string>
    <string name="speech_not_supported">Sorry! Your device doesn\'t support speech input</string>
    <string name="tap_on_mic">Tap on mic to speak</string>

</resources>
===============================================================
<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

</resources>

Python: Get relative path from comparing two absolute paths

os.path.relpath:

Return a relative filepath to path either from the current directory or from an optional start point.

>>> from os.path import relpath
>>> relpath('/usr/var/log/', '/usr/var')
'log'
>>> relpath('/usr/var/log/', '/usr/var/sad/')
'../log'

So, if relative path starts with '..' - it means that the second path is not descendant of the first path.

In Python3 you can use PurePath.relative_to:

Python 3.5.1 (default, Jan 22 2016, 08:54:32)
>>> from pathlib import Path

>>> Path('/usr/var/log').relative_to('/usr/var/log/')
PosixPath('.')

>>> Path('/usr/var/log').relative_to('/usr/var/')
PosixPath('log')

>>> Path('/usr/var/log').relative_to('/etc/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/pathlib.py", line 851, in relative_to
    .format(str(self), str(formatted)))
ValueError: '/usr/var/log' does not start with '/etc'

Check play state of AVPlayer

To get notification for reaching the end of an item (via Apple):

[[NSNotificationCenter defaultCenter] 
      addObserver:<self>
      selector:@selector(<#The selector name#>)
      name:AVPlayerItemDidPlayToEndTimeNotification 
      object:<#A player item#>];

And to track playing you can:

"track changes in the position of the playhead in an AVPlayer object" by using addPeriodicTimeObserverForInterval:queue:usingBlock: or addBoundaryTimeObserverForTimes:queue:usingBlock:.

Example is from Apple:

// Assume a property: @property (retain) id playerObserver;

Float64 durationSeconds = CMTimeGetSeconds([<#An asset#> duration]);
CMTime firstThird = CMTimeMakeWithSeconds(durationSeconds/3.0, 1);
CMTime secondThird = CMTimeMakeWithSeconds(durationSeconds*2.0/3.0, 1);
NSArray *times = [NSArray arrayWithObjects:[NSValue valueWithCMTime:firstThird], [NSValue valueWithCMTime:secondThird], nil];

self.playerObserver = [<#A player#> addBoundaryTimeObserverForTimes:times queue:NULL usingBlock:^{
    // Passing NULL for the queue specifies the main queue.

    NSString *timeDescription = (NSString *)CMTimeCopyDescription(NULL, [self.player currentTime]);
    NSLog(@"Passed a boundary at %@", timeDescription);
    [timeDescription release];
}];

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

To use aliases on eloquent models modify your code like this:

Item
    ::from( 'items as items_alias' )
    ->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
    ->select( DB::raw( 'items_alias.*' ) )
    ->get();

This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result. Adding DB::raw prevents laravel from adding table prefixes to aliases.

Fastest way to determine if record exists

SELECT TOP 1 products.id FROM products WHERE products.id = ?; will outperform all of your suggestions as it will terminate execution after it finds the first record.

Array Length in Java

  int arr[]={4,7,2,21321,657,12321};
  int length =arr.length;
  System.out.println(length); // will return 6

  int arr2[] = new int[10];
   arr2[3] = 4;
  int length2 =arr2.length;
  System.out.println(length2); // // will return 10. all other digits will be 0 initialize because staic memory initialization

How to make Bitmap compress without change the bitmap size?

i think you use this method to compress the bitmap

BitmapFactory.Option imageOpts = new BitmapFactory.Options ();
imageOpts.inSampleSize = 2;   // for 1/2 the image to be loaded
Bitmap thumb = Bitmap.createScaledBitmap (BitmapFactory.decodeFile(photoPath, imageOpts), 96, 96, false);

Text editor to open big (giant, huge, large) text files

Tips and tricks

less

Why are you using editors to just look at a (large) file?

Under *nix or Cygwin, just use less. (There is a famous saying – "less is more, more or less" – because "less" replaced the earlier Unix command "more", with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.

There is a Win32 port of GNU less. See the "less" section of the answer above.

Perl

Perl is good for quick scripts, and its .. (range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.

For example:

$ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less

This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.

Another example:

$ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less

This starts printing when the "regular expression one" finds something, and stops when the "regular expression two" find the end of an interesting block. It may find multiple blocks. Sift the output...

logparser

This is another useful tool you can use. To quote the Wikipedia article:

logparser is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a "data processing pipeline", by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.

Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.

Example usage:

C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line > 1000 and line < 2000"
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'"

The relativity of sizes

100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print & mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.

And more...

Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...

Missing maven .m2 folder

Use mvn -X or mvn --debug to find out from which different locations Maven reads settings.xml. This switch activates debug logging. Just check the first lines of mvn --debug | findstr /i /c:using /c:reading.


Right, Maven uses the Java system property user.home as location for the .m2 folder.

But user.home does not always resolve to %USERPROFILE%\.m2. If you have moved the location of your Desktop folder to another place, user.home might resolve to the parent directory of this new Desktop folder. This happens when using Windows Vista or a more recent Windows together with Java 7 or any older Java version.

The blog post Java’s “user.home” is Wrong on Windows describes it very well and gives links to the official bug reports. The bug is marked as resolved in Java 8. The comment of the blog's visitor Lars proposes a nice workaround.

How to sort List<Integer>?

You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.

Sorting a list in ascending order can be performed as default operation on this way:

Collections.sort(list);

Sorting a list in descending order can be performed on this way:

Collections.reverse(list);

According to these facts, your solution has to be written like this:

public class tes 
{
    public static void main(String args[])
    {
        List<Integer> lList = new ArrayList<Integer>();
        lList.add(4);
        lList.add(1);
        lList.add(7);
        lList.add(2);
        lList.add(9);
        lList.add(1);
        lList.add(5);

        Collections.sort(lList);
        for(int i=0; i<lList.size();i++ )
        {
            System.out.println(lList.get(i));
        }
     }
}

More about Collections you can read here.

Read a HTML file into a string variable in memory

You can do it the simple way:

string pathToHTMLFile = @"C:\temp\someFile.html";
string htmlString = File.ReadAllText(pathToHTMLFile);

Or you could stream it in with FileStream/StreamReader:

using (FileStream fs = File.Open(pathToHTMLFile, FileMode.Open, FileAccess.ReadWrite))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        htmlString = sr.ReadToEnd();
    }
}

This latter method allows you to open the file while still permitting others to perform Read/Write operations on the file. I can't imagine an HTML file being very big, but it has the added benefit of streaming the file instead of capturing it as one large chunk like the first method.

How to make type="number" to positive numbers only

It depends on how precise you want to be. It you want to accept only integers, than:

_x000D_
_x000D_
<input type="number" min="1" step="1">
_x000D_
_x000D_
_x000D_

If you want floats with, for example, two digits after decimal point:

_x000D_
_x000D_
<input type="number" min="0.01" step="0.01">
_x000D_
_x000D_
_x000D_

Making a triangle shape using xml definitions?

For those who want a right triangle arrow, here you go:

STEP 1: Create a drawable XML file, copy and paste the following XML content into your drawable XML. (Please be informed that you can use any name for your drawable XML file. For my case, I name it "v_right_arrow")

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item >
        <rotate
            android:fromDegrees="45"
            android:toDegrees="-45"
            android:pivotX="15%"
            android:pivotY="-36%" >
            <shape
                android:shape="rectangle"  >
                <stroke android:color="@android:color/transparent" android:width="1dp"/>
                <solid
                    android:color="#000000"  />
            </shape>
        </rotate>
    </item>
</layer-list>

STEP 2: In your layout's XML, create a View and bind its background to the drawable XML that you have just created in STEP 1. For my case, I bind v_right_arrow to my View's background property.

<View
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:background="@drawable/v_right_arrow">
</View>

Sample output:

enter image description here

Hope this helps, good luck!

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

How in node to split string by newline ('\n')?

The first one should work:

> "a\nb".split("\n");
[ 'a', 'b' ]
> var a = "test.js\nagain.js"
undefined
> a.split("\n");
[ 'test.js', 'again.js' ]

Read file content from S3 bucket with boto3

boto3 offers a resource model that makes tasks like iterating through objects easier. Unfortunately, StreamingBody doesn't provide readline or readlines.

s3 = boto3.resource('s3')
bucket = s3.Bucket('test-bucket')
# Iterates through all the objects, doing the pagination for you. Each obj
# is an ObjectSummary, so it doesn't contain the body. You'll need to call
# get to get the whole body.
for obj in bucket.objects.all():
    key = obj.key
    body = obj.get()['Body'].read()

How to vertically align a html radio button to it's label?

While I agree tables shouldn't be used for design layouts contrary to popular belief they do pass validation. i.e. the table tag is not deprecated. The best way to align radio buttons is using the vertical align middle CSS with margins adjusted on the input elements.

List all employee's names and their managers by manager name using an inner join

You have an incorrect ON clause at the join, this works:

inner join Employees m on e.mgr = m.EmpId;

The mgr column references the EmpId column.

DEMO

Notification bar icon turns white in Android 5 Lollipop

Notifications are greyscale as explained below. They are not black-and-white, despite what others have written. You have probably seen icons with multiple shades, like network strength bars.

Prior to API 21 (Lollipop 5.0), colour icons work. You could force your application to target API 20, but that limits the features available to your application, so it is not recommended. You could test the running API level and set either a colour icon or a greyscale icon appropriately, but this is likely not worthwhile. In most cases, it is best to go with a greyscale icon.

Images have four channels, RGBA (red / green / blue / alpha). For notification icons, Android ignores the R, G, and B channels. The only channel that counts is Alpha, also known as opacity. Design your icon with an editor that gives you control over the Alpha value of your drawing colours.

How Alpha values generate a greyscale image:

  • Alpha = 0 (transparent) — These pixels are transparent, showing the background colour.
  • Alpha = 255 (opaque) — These pixels are white.
  • Alpha = 1 ... 254 — These pixels are exactly what you would expect, providing the shades between transparent and white.

Changing it up with setColor:

  • Call NotificationCompat.Builder.setColor(int argb). From the documentation for Notification.color:

    Accent color (an ARGB integer like the constants in Color) to be applied by the standard Style templates when presenting this notification. The current template design constructs a colorful header image by overlaying the icon image (stenciled in white) atop a field of this color. Alpha components are ignored.

    My testing with setColor shows that Alpha components are not ignored; instead, they still provide greyscale. Higher Alpha values turn a pixel white. Lower Alpha values turn a pixel to the background colour (black on my device) in the notification area, or to the specified colour in the pull-down notification. (It seems others have reported slightly different behavior, so be aware!)

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

It happen if there are two more ContextLoaderListener exist in your project.

For ex: in my case 2 ContextLoaderListener was exist using

  1. java configuration
  2. web.xml

So, remove any one ContextLoaderListener from your project and run your application.

Powershell script does not run via Scheduled Tasks

NOTE: Please ensure that you select Create a Basic task Action and NOT the Create Task Action.

I found the following solution:

1) Make powershell.exe run as administrator for this

  1. right-click on the powershell.exe icon
  2. click on properties under the shortcut key menu
  3. click on the advance button; check that "run as administrator" is checked.

2) in the task scheduler window under the action pane add the following script as a new command

%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -ExecutionPolicy Bypass -noexit -File "C:\ps1\BackUp.ps1"

enter image description here

RecyclerView onClick

The RecyclerView does not have a OnClickListener and will have to implement it ourselves.

I like to add a OnItemClickListener interface in Adapter with an onClick method invoked when you click on the item view from the ViewHolder. Thus the responsibility of managing the click on an item is outside the ViewHolder and Adapter. Will the activity or fragment which will decide what to do

Add an interface to the listener and the listener object.

public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ViewHolder> {

  ...

  private static OnItemClickListener onItemClickListener;

  ...

  public static interface OnItemClickListener {
      public void onItemClick(View view, int position);
  }

  ...
}

We capture the click of the root view of the item and when the callback is triggered onClick listener call on the adapter .

public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ViewHolder> {

  ...

  private static OnItemClickListener onItemClickListener;

  ...

  public static interface OnItemClickListener {
      public void onItemClick(View view, int position);
  }

  ...

  public static class ViewHolder extends RecyclerView.ViewHolder {
      public ImageView imageView;

      public ViewHolder(View itemRootView) {
          super(itemRootView);
          imageView = (ImageView) itemRootView.findViewById(R.id.itemImage);

          itemRootView.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  int position  = ViewHolder.super.getAdapterPosition();
                  onItemClickListener.onItemClick(view,position);
              }
          });
      }
  }
}

Since the activity or fragment , fragment in our case , we assign a listener to the adapter and the onClick callback we will get the selected item by position and opened a detailed activity of item.

public class ItemsFragment extends Fragment {
    ...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       ...    
        ((ItemsAdapter) adapter).setOnItemClickListener(new ItemsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //Do something when an item has been clicked
            }
        });
        ...
    }
...
}

How to detect simple geometric shapes using OpenCV

If you have only these regular shapes, there is a simple procedure as follows :

  1. Find Contours in the image ( image should be binary as given in your question)
  2. Approximate each contour using approxPolyDP function.
  3. First, check number of elements in the approximated contours of all the shapes. It is to recognize the shape. For eg, square will have 4, pentagon will have 5. Circles will have more, i don't know, so we find it. ( I got 16 for circle and 9 for half-circle.)
  4. Now assign the color, run the code for your test image, check its number, fill it with corresponding colors.

Below is my example in Python:

import numpy as np
import cv2

img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print len(approx)
    if len(approx)==5:
        print "pentagon"
        cv2.drawContours(img,[cnt],0,255,-1)
    elif len(approx)==3:
        print "triangle"
        cv2.drawContours(img,[cnt],0,(0,255,0),-1)
    elif len(approx)==4:
        print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255),-1)
    elif len(approx) == 9:
        print "half-circle"
        cv2.drawContours(img,[cnt],0,(255,255,0),-1)
    elif len(approx) > 15:
        print "circle"
        cv2.drawContours(img,[cnt],0,(0,255,255),-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Below is the output:

enter image description here

Remember, it works only for regular shapes.

Alternatively to find circles, you can use houghcircles. You can find a tutorial here.

Regarding iOS, OpenCV devs are developing some iOS samples this summer, So visit their site : www.code.opencv.org and contact them.

You can find slides of their tutorial here : http://code.opencv.org/svn/gsoc2012/ios/trunk/doc/CVPR2012_OpenCV4IOS_Tutorial.pdf

I can't understand why this JAXB IllegalAnnotationException is thrown

One of the following may cause the exception:

  1. Add an empty public constructor to your Fields class, JAXB uses reflection to load your classes, that's why the exception is thrown.
  2. Add separate getter and setter for your list.

How to send 100,000 emails weekly?

Here is what I did recently in PHP on one of my bigger systems:

  1. User inputs newsletter text and selects the recipients (which generates a query to retrieve the email addresses for later).

  2. Add the newsletter text and recipients query to a row in mysql table called *email_queue*

    • (The table email_queue has the columns "to" "subject" "body" "priority")
  3. I created another script, which runs every minute as a cron job. It uses the SwiftMailer class. This script simply:

    • during business hours, sends all email with priority == 0

    • after hours, send other emails by priority

Depending on the hosts settings, I can now have it throttle using standard swiftmailers plugins like antiflood and throttle...

$mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(50, 30));

and

$mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin( 100, Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE ));

etc, etc..

I have expanded it way beyond this pseudocode, with attachments, and many other configurable settings, but it works very well as long as your server is setup correctly to send email. (Probably wont work on shared hosting, but in theory it should...) Swiftmailer even has a setting

$message->setReturnPath

Which I now use to track bounces...

Happy Trails! (Happy Emails?)

How to make a phone call using intent in Android?

For making a call activity using intents, you should request the proper permissions.

For that you include uses permissions in AndroidManifest.xml file.

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

Then include the following code in your activity

if (ActivityCompat.checkSelfPermission(mActivity,
        Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
    //Creating intents for making a call
    Intent callIntent = new Intent(Intent.ACTION_CALL);
    callIntent.setData(Uri.parse("tel:123456789"));
    mActivity.startActivity(callIntent);

}else{
    Toast.makeText(mActivity, "You don't assign permission.", Toast.LENGTH_SHORT).show();
}

How to extract numbers from string in c?

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
        // Found a number
        long val = strtol(p, &p, 10); // Read number
        printf("%ld\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        p++;
    }
}

Link to ideone.

How to run python script in webpage

In order for your code to show, you need several things:

Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.

Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.

Setting this up can be quite the hassle, so be prepared.

jQuery select child element by class with unknown path

According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector) is the fastest and most efficient way to do this.

regular expression to validate datetime format (MM/DD/YYYY)

var pattern = new RegExp((0|1)[0-9]\/[0-3][0-9]\/(19|20)[0-9]{2});
if(!testdate.match(pattern))
   return false;
else return true;

Why number 9 in kill -9 command in unix?

why kill -9 : the number 9 in the list of signals has been chosen to be SIGKILL in reference to "kill the 9 lives of a cat".

PHP shell_exec() vs exec()

shell_exec - Execute command via shell and return the complete output as a string

exec - Execute an external program.

The difference is that with shell_exec you get output as a return value.

How do I set up IntelliJ IDEA for Android applications?

The 5th step in "New Project' has apparently changed slightly since.

Where it says android sdk then has the drop down menu that says none, there is no longer a 'new' button.

  • 5.)

    • a.)click the ... to the right of none.
    • b.)click the + in the top left of new window dialog. (Add new Sdk)
    • c.)click android sdk from drop down menu
    • d.)select home directory for your android sdk
    • e.)select java sdk version you want to use
    • f.)select android build target.
    • g.)hit ok!