Programs & Examples On #Svn export

Questions regarding SVN export operations.

Do a "git export" (like "svn export")?

If you're not excluding files with .gitattributes export-ignore then try git checkout

mkdir /path/to/checkout/
git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout -f -q

-f
When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

and

-q
Avoid verbose

Additionally you can get any Branch or Tag or from a specific Commit Revision like in SVN just adding the SHA1 (SHA1 in Git is the equivalent to the Revision Number in SVN)

mkdir /path/to/checkout/
git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout 2ef2e1f2de5f3d4f5e87df7d8 -f -q -- ./

The /path/to/checkout/ must be empty, Git will not delete any file, but will overwrite files with the same name without any warning

UPDATE: To avoid the beheaded problem or to leave intact the working repository when using checkout for export with tags, branches or SHA1, you need to add -- ./ at the end

The double dash -- tells git that everything after the dashes are paths or files, and also in this case tells git checkout to not change the HEAD

Examples:

This command will get just the libs directory and also the readme.txt file from that exactly commit

git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout fef2e1f2de5f3d4f5e87df7d8 -f -q -- ./libs ./docs/readme.txt

This will create(overwrite) my_file_2_behind_HEAD.txt two commits behind the head HEAD^2

git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout HEAD^2 -f -q -- ./my_file_2_behind_HEAD.txt

To get the export of another branch

git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout myotherbranch -f -q -- ./

Notice that ./ is relative to the root of the repository

What is the difference between an expression and a statement in Python?

Statements before could change the state of our Python program: create or update variables, define function, etc.

And expressions just return some value can't change the global state or local state in a function.

But now we got :=, it's an alien!

Should I add the Visual Studio .suo and .user files to source control?

These files are user-specific options, which should be independent of the solution itself. Visual Studio will create new ones as necessary, so they do not need to be checked in to source control. Indeed, it would probably be better not to as this allows individual developers to customize their environment as they see fit.

Malformed String ValueError ast.literal_eval() with String representation of Tuple

Use eval() instead of ast.literal_eval() if the input is trusted (which it is in your case).

raw_data = userfile.read().split('\n')
for a in raw_data : 
    print a
    btc_history.append(eval(a))

This works for me in Python 3.6.0

How do I plot only a table in Matplotlib?

If you just wanted to change the example and put the table at the top, then loc='top' in the table declaration is what you need,

the_table = ax.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='top')

Then adjusting the plot with,

plt.subplots_adjust(left=0.2, top=0.8)

A more flexible option is to put the table in its own axis using subplots,

import numpy as np
import matplotlib.pyplot as plt


fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')

axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()

which looks like this,

enter image description here

You are then free to adjust the locations of the axis as required.

Why does JPA have a @Transient annotation?

As others have said, @Transient is used to mark fields which shouldn't be persisted. Consider this short example:

public enum Gender { MALE, FEMALE, UNKNOWN }

@Entity
public Person {
    private Gender g;
    private long id;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

    public Gender getGender() { return g; }    
    public void setGender(Gender g) { this.g = g; }

    @Transient
    public boolean isMale() {
        return Gender.MALE.equals(g);
    }

    @Transient
    public boolean isFemale() {
        return Gender.FEMALE.equals(g);
    }
}

When this class is fed to the JPA, it persists the gender and id but doesn't try to persist the helper boolean methods - without @Transient the underlying system would complain that the Entity class Person is missing setMale() and setFemale() methods and thus wouldn't persist Person at all.

Add a row number to result set of a SQL query

SELECT
    t.A,
    t.B,
    t.C,
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t

See working example at SQLFiddle

Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1)) for, e.g., OVER (ORDER BY t.C), like in a normal ORDER BY clause.

MySQL order by before group by

Just use the max function and group function

    select max(taskhistory.id) as id from taskhistory
            group by taskhistory.taskid
            order by taskhistory.datum desc

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

On Mac it works for below command. (hope your .Dockerfile is in your root directory).

docker build -t docker-whale -f .Dockerfile .

How to shuffle an ArrayList

Use this method and pass your array in parameter

Collections.shuffle(arrayList);

This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.

You can now use arraylist which is shuffled.

CRON job to run on the last day of the month

For a safer method in a crontab based on @Indie solution (use absolute path to date + $() does not works on all crontab systems):

0 23 28-31 * * [ `/bin/date -d +1day +\%d` -eq 1 ] && myscript.sh

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

How do I see the extensions loaded by PHP?

Are you looking for a particular extension? In your phpinfo();, just hit Ctrl+F in your web browser, type in the first 3-4 letters of the extension you're looking for, and it should show you whether or not its loaded.

Usually in phpinfo() it doesn't show you all the loaded extensions in one location, it has got a separate section for each loaded extension where it shows all of its variables, file paths, etc, so if there is no section for your extension name it probably means it isn't loaded.

Alternatively you can open your php.ini file and use the Ctrl+F method to find your extension, and see if its been commented out (usually by a semicolon near the start of the line).

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

Spring @Value is not resolving to value from property file

I also found the reason @value was not working is, @value requires PropertySourcesPlaceholderConfigurer instead of a PropertyPlaceholderConfigurer. i did the same changes and it worked for me, i am using spring 4.0.3 release. I configured this using below code in my configuration file -

@Bean 
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

Finally, it happened GitHub has officially announced their new CLI for all the core features.

check here: https://cli.github.com/

To install via HomeBrew: brew install gh for other Ways : https://github.com/cli/cli#installation

then

gh repo create

Other available features.

$ gh --help

Work seamlessly with GitHub from the command line.

USAGE
  gh <command> <subcommand> [flags]

CORE COMMANDS
  gist:       Create gists
  issue:      Manage issues
  pr:         Manage pull requests
  release:    Manage GitHub releases
  repo:       Create, clone, fork, and view repositories

ADDITIONAL COMMANDS
  alias:      Create command shortcuts
  api:        Make an authenticated GitHub API request
  auth:       Login, logout, and refresh your authentication
  completion: Generate shell completion scripts
  config:     Manage configuration for gh
  help:       Help about any command

FLAGS
  --help      Show help for command
  --version   Show gh version

EXAMPLES
  $ gh issue create
  $ gh repo clone cli/cli
  $ gh pr checkout 321

ENVIRONMENT VARIABLES
  See 'gh help environment' for the list of supported environment variables.

LEARN MORE
  Use 'gh <command> <subcommand> --help' for more information about a command.
  Read the manual at https://cli.github.com/manual

FEEDBACK
  Open an issue using 'gh issue create -R cli/cli'

So now you can create repo from your terminal.

how to get domain name from URL

Just for knowledge:

'http://api.livreto.co/books'.replace(/^(https?:\/\/)([a-z]{3}[0-9]?\.)?(\w+)(\.[a-zA-Z]{2,3})(\.[a-zA-Z]{2,3})?.*$/, '$3$4$5');

# returns livreto.co 

jquery beforeunload when closing (not leaving) the page?

Try javascript into your Ajax

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Reference link

Example 2:

document.getElementsByClassName('eStore_buy_now_button')[0].onclick = function(){
    window.btn_clicked = true;
};
window.onbeforeunload = function(){
    if(!window.btn_clicked){
        return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
    }
};

Here it will alert the user every time he leaves the page, until he clicks on the button.

DEMO: http://jsfiddle.net/DerekL/GSWbB/show/

Simulate limited bandwidth from within Chrome?

As suggested on the Chrome Mobile Emulation page, you can use Clumsy on Windows, Network Link Conditioner on Mac OS X and dummynet on Linux.

"Multiple definition", "first defined here" errors

I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format

<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here

I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!

How to remove the Flutter debug banner?

You can give simply hide this by giving a boolean parameter-----> debugShowCheckedModeBanner: false,

void main() {
  Bloc.observer = SimpleBlocDelegate();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Prescription Writing Software',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: Colors.white,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: SplashScreen(),
    );
  }
}

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

As a supplement to the question and above answers there is also an important difference between plt.subplots() and plt.subplot(), notice the missing 's' at the end.

One can use plt.subplots() to make all their subplots at once and it returns the figure and axes (plural of axis) of the subplots as a tuple. A figure can be understood as a canvas where you paint your sketch.

# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)

Whereas, you can use plt.subplot() if you want to add the subplots separately. It returns only the axis of one subplot.

fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1) 
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)

However, plt.subplots() is preferred because it gives you easier options to directly customize your whole figure

# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)

Shared axes whereas, with plt.subplot(), one will have to specify individually for each axis which can become cumbersome.

How do I block comment in Jupyter notebook?

I tried this on Mac OSX with Chrome 42.0.2311.90 (64-bit) and this works by using CMD + /

The version of the notebook server is 3.1.0-cbccb68 and is running on:
Python 2.7.9 |Anaconda 2.1.0 (x86_64)| (default, Dec 15 2014, 10:37:34) 
[GCC 4.2.1 (Apple Inc. build 5577)]

Could it be a browser related problem? Did you try Firefox or IE?

Make child visible outside an overflow:hidden parent

Neither of the posted answers worked for me. Setting position: absolute for the child element did work however.

Combining node.js and Python

Update 2019

There are several ways to achieve this and here is the list in increasing order of complexity

  1. Python Shell, you will write streams to the python console and it will write back to you
  2. Redis Pub Sub, you can have a channel listening in Python while your node js publisher pushes data
  3. Websocket connection where Node acts as the client and Python acts as the server or vice-versa
  4. API connection with Express/Flask/Tornado etc working separately with an API endpoint exposed for the other to query

Approach 1 Python Shell Simplest approach

source.js file

const ps = require('python-shell')
// very important to add -u option since our python script runs infinitely
var options = {
    pythonPath: '/Users/zup/.local/share/virtualenvs/python_shell_test-TJN5lQez/bin/python',
    pythonOptions: ['-u'], // get print results in real-time
    // make sure you use an absolute path for scriptPath
    scriptPath: "./subscriber/",
    // args: ['value1', 'value2', 'value3'],
    mode: 'json'
};

const shell = new ps.PythonShell("destination.py", options);

function generateArray() {
    const list = []
    for (let i = 0; i < 1000; i++) {
        list.push(Math.random() * 1000)
    }
    return list
}

setInterval(() => {
    shell.send(generateArray())
}, 1000);

shell.on("message", message => {
    console.log(message);
})

destination.py file

import datetime
import sys
import time
import numpy
import talib
import timeit
import json
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

size = 1000
p = 100
o = numpy.random.random(size)
h = numpy.random.random(size)
l = numpy.random.random(size)
c = numpy.random.random(size)
v = numpy.random.random(size)

def get_indicators(values):
    # Return the RSI of the values sent from node.js
    numpy_values = numpy.array(values, dtype=numpy.double) 
    return talib.func.RSI(numpy_values, 14)

for line in sys.stdin:
    l = json.loads(line)
    print(get_indicators(l))
    # Without this step the output may not be immediately available in node
    sys.stdout.flush()

Notes: Make a folder called subscriber which is at the same level as source.js file and put destination.py inside it. Dont forget to change your virtualenv environment

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Syntax:

CASE value WHEN [compare_value] THEN result 
[WHEN [compare_value] THEN result ...] 
[ELSE result] 
END

Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]

mysql> SELECT CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END; 
+-------------------------------------------------------------+
| CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
+-------------------------------------------------------------+
| this is false                                               | 
+-------------------------------------------------------------+

I am use:

SELECT  act.*,
    CASE 
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
        WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
    END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = act.id AND  lises.session_date >= now()
LEFT JOIN session AS ses ON  ses.activity_id = act.id AND  ses.session_date >= now()
WHERE act.id

Installing NumPy via Anaconda in Windows

Move path\to\anaconda in the PATH above path\to\python

Update value of a nested dictionary of varying depth

Same solution as the accepted one, but clearer variable naming, docstring, and fixed a bug where {} as a value would not override.

import collections


def deep_update(source, overrides):
    """
    Update a nested dictionary or similar mapping.
    Modify ``source`` in place.
    """
    for key, value in overrides.iteritems():
        if isinstance(value, collections.Mapping) and value:
            returned = deep_update(source.get(key, {}), value)
            source[key] = returned
        else:
            source[key] = overrides[key]
    return source

Here are a few test cases:

def test_deep_update():
    source = {'hello1': 1}
    overrides = {'hello2': 2}
    deep_update(source, overrides)
    assert source == {'hello1': 1, 'hello2': 2}

    source = {'hello': 'to_override'}
    overrides = {'hello': 'over'}
    deep_update(source, overrides)
    assert source == {'hello': 'over'}

    source = {'hello': {'value': 'to_override', 'no_change': 1}}
    overrides = {'hello': {'value': 'over'}}
    deep_update(source, overrides)
    assert source == {'hello': {'value': 'over', 'no_change': 1}}

    source = {'hello': {'value': 'to_override', 'no_change': 1}}
    overrides = {'hello': {'value': {}}}
    deep_update(source, overrides)
    assert source == {'hello': {'value': {}, 'no_change': 1}}

    source = {'hello': {'value': {}, 'no_change': 1}}
    overrides = {'hello': {'value': 2}}
    deep_update(source, overrides)
    assert source == {'hello': {'value': 2, 'no_change': 1}}

This functions is available in the charlatan package, in charlatan.utils.

How to get progress from XMLHttpRequest

The only way to do that with pure javascript is to implement some kind of polling mechanism. You will need to send ajax requests at fixed intervals (each 5 seconds for example) to get the number of bytes received by the server.

A more efficient way would be to use flash. The flex component FileReference dispatchs periodically a 'progress' event holding the number of bytes already uploaded. If you need to stick with javascript, bridges are available between actionscript and javascript. The good news is that this work has been already done for you :)

swfupload

This library allows to register a javascript handler on the flash progress event.

This solution has the hudge advantage of not requiring aditionnal resources on the server side.

Writing to a new file if it doesn't exist, and appending to a file if it does

Using the pathlib module (python's object-oriented filesystem paths)

Just for kicks, this is perhaps the latest pythonic version of the solution.

from pathlib import Path 

path = Path(f'{player}.txt')
path.touch()  # default exists_ok=True
with path.open('a') as highscore:
   highscore.write(f'Username:{player}')

Method Call Chaining; returning a pointer vs a reference?

The difference between pointers and references is quite simple: a pointer can be null, a reference can not.

Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).

Here it looks like references are more appropriate.

How to detect shake event with android?

Since SensorListener is deprecated so use the following code:

/* put this into your activity class */
private SensorManager mSensorManager;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity

private final SensorEventListener mSensorListener = new SensorEventListener() {

  public void onSensorChanged(SensorEvent se) {
    float x = se.values[0];
    float y = se.values[1];
    float z = se.values[2];
    mAccelLast = mAccelCurrent;
    mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
    float delta = mAccelCurrent - mAccelLast;
    mAccel = mAccel * 0.9f + delta; // perform low-cut filter
  }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {
  }
};

@Override
protected void onResume() {
  super.onResume();
  mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onPause() {
  mSensorManager.unregisterListener(mSensorListener);
  super.onPause();
}

Then:

/* do this in onCreate */
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;

The question with full details could be found here:

Android: I want to shake it

What is the "continue" keyword and how does it work in Java?

continue is kind of like goto. Are you familiar with break? It's easier to think about them in contrast:

  • break terminates the loop (jumps to the code below it).

  • continue terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

How to check edittext's text is email address or not?

The following code should be useful to you.

String email;
check.setOnClickListener(new OnClickListener() {


                public void onClick(View arg0) {

                    checkEmail(email);
                    if (checkMail) {
                        System.out.println("Valid mail Id");
                    }
                }
            });

        }
    }

    public static boolean checkEmail(String email) {

        Pattern EMAIL_ADDRESS_PATTERN = Pattern
                .compile("[a-zA-Z0-9+._%-+]{1,256}" + "@"
                        + "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" + "(" + "."
                        + "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" + ")+");
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }

Is Python strongly typed?

TLDR;

Python typing is Dynamic so you can change a string variable to an int

x = 'somestring'
x = 50

Python typing is Strong so you can't merge types:

'foo' + 3 --> TypeError: cannot concatenate 'str' and 'int' objects

In weakly-typed Javascript this happens...

 'foo'+3 = 'foo3'

Regarding Type Inference

Java forces you to explicitly declare your object types

int x = 50;

Kotlin uses inference to realize it's an int

x = 50

But because both languages use static types, x can't be changed from an int. Neither language would allow a dynamic change like

x = 50
x = 'now a string'

How to zip a file using cmd line?

If you are using Ubuntu Linux:

  1. Install zip

    sudo apt-get install zip
    
  2. Zip your folder:

    zip -r {filename.zip} {foldername}
    

If you are using Microsoft Windows:

Windows does not come with a command-line zip program, despite Windows Explorer natively supporting Zip files since the Plus! pack for Windows 98.

I recommend the open-source 7-Zip utility which includes a command-line executable and supports many different archive file types, especially its own *.7z format which offers superior compression ratios to traditional (PKZIP) *.zip files:

  1. Download 7-Zip from the 7-Zip home page

  2. Add the path to 7z.exe to your PATH environment variable. See this QA: How to set the path and environment variables in Windows

  3. Open a new command-prompt window and use this command to create a PKZIP *.zip file:

    7z a -tzip {yourfile.zip} {yourfolder}
    

Cross-platform Java:

If you have the Java JDK installed then you can use the jar utility to create Zip files, as *.jar files are essentially just renamed *.zip (PKZIP) files:

jar -cfM {yourfile.zip} {yourfolder}

Explanation: * -c compress * -f specify filename * -M do not include a MANIFEST file

Using pg_dump to only get insert statements from one table within database

If you want to DUMP your inserts into an .sql file:

  1. cd to the location which you want to .sql file to be located
  2. pg_dump --column-inserts --data-only --table=<table> <database> > my_dump.sql

Note the > my_dump.sql command. This will put everything into a sql file named my_dump

Environment variables in Jenkins

The environment variables displayed in Jenkins (Manage Jenkins -> System information) are inherited from the system (i.e. inherited environment variables)

If you run env command in a shell you should see the same environment variables as Jenkins shows.

These variables are either set by the shell/system or by you in ~/.bashrc, ~/.bash_profile.

There are also environment variables set by Jenkins when a job executes, but these are not displayed in the System Information.

How to make a gui in python

Just look at the python GUI programming options at http://wiki.python.org/moin/GuiProgramming. But, Consider Wxpython for your GUI application as it is cross platform. And,from above link you could also get some IDE to work upon.

AWS ssh access 'Permission denied (publickey)' issue

If you're using a Bitnami image, log in as 'bitnami'.

Seems obvious, but something I overlooked.

write() versus writelines() and concatenated strings

Exercise 16 from Zed Shaw's book? You can use escape characters as follows:

paragraph1 = "%s \n %s \n %s \n" % (line1, line2, line3)
target.write(paragraph1)
target.close()

SQL Server: Get table primary key using sql query

From memory, it's either this

SELECT * FROM sys.objects
WHERE type = 'PK' 
AND  object_id = OBJECT_ID ('tableName')

or this..

SELECT * FROM sys.objects
WHERE type = 'PK' 
AND  parent_object_id = OBJECT_ID ('tableName')

I think one of them should probably work depending on how the data is stored but I am afraid I have no access to SQL to actually verify the same.

Auto Increment after delete in MySQL

here is a function that fix your problem

    public static void fixID(Connection conn, String table) {

    try {
        Statement myStmt = conn.createStatement();
        ResultSet myRs;
        int i = 1, id = 1, n = 0;
        boolean b;
        String sql;

        myRs = myStmt.executeQuery("select max(id) from " + table);
        if (myRs.next()) {
            n = myRs.getInt(1);
        }
        while (i <= n) {
            b = false;
            myRs = null;
            while (!b) {
                myRs = myStmt.executeQuery("select id from " + table + " where id=" + id);
                if (!myRs.next()) {
                    id++;
                } else {
                    b = true;
                }
            }

            sql = "UPDATE " + table + " set id =" + i + " WHERE id=" + id;
            myStmt.execute(sql);
            i++;
            id++;
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Which characters make a URL invalid?

Most of the existing answers here are impractical because they totally ignore the real-world usage of addresses like:

First, a digression into terminology. What are these addresses? Are they valid URLs?

Historically, the answer was "no". According to RFC 3986, from 2005, such addresses are not URIs (and therefore not URLs, since URLs are a type of URIs). Per the terminology of 2005 IETF standards, we should properly call them IRIs (Internationalized Resource Identifiers), as defined in RFC 3987, which are technically not URIs but can be converted to URIs simply by percent-encoding all non-ASCII characters in the IRI.

Per modern spec, the answer is "yes". The WHATWG Living Standard simply classifies everything that would previously be called "URIs" or "IRIs" as "URLs". This aligns the specced terminology with how normal people who haven't read the spec use the word "URL", which was one of the spec's goals.

What characters are allowed under the WHATWG Living Standard?

Per this newer meaning of "URL", what characters are allowed? In many parts of the URL, such as the query string and path, we're allowed to use arbitrary "URL units", which are

URL code points and percent-encoded bytes.

What are "URL code points"?

The URL code points are ASCII alphanumeric, U+0021 (!), U+0024 ($), U+0026 (&), U+0027 ('), U+0028 LEFT PARENTHESIS, U+0029 RIGHT PARENTHESIS, U+002A (*), U+002B (+), U+002C (,), U+002D (-), U+002E (.), U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+003F (?), U+0040 (@), U+005F (_), U+007E (~), and code points in the range U+00A0 to U+10FFFD, inclusive, excluding surrogates and noncharacters.

(Note that the list of "URL code points" doesn't include %, but that %s are allowed in "URL code units" if they're part of a percent-encoding sequence.)

The only place I can spot where the spec permits the use of any character that's not in this set is in the host, where IPv6 addresses are enclosed in [ and ] characters. Everywhere else in the URL, either URL units are allowed or some even more restrictive set of characters.

What characters were allowed under the old RFCs?

For the sake of history, and since it's not explored fully elsewhere in the answers here, let's examine was allowed under the older pair of specs.

First of all, we have two types of RFC 3986 reserved characters:

  • :/?#[]@, which are part of the generic syntax for a URI defined in RFC 3986
  • !$&'()*+,;=, which aren't part of the RFC's generic syntax, but are reserved for use as syntactic components of particular URI schemes. For instance, semicolons and commas are used as part of the syntax of data URIs, and & and = are used as part of the ubiquitous ?foo=bar&qux=baz format in query strings (which isn't specified by RFC 3986).

Any of the reserved characters above can be legally used in a URI without encoding, either to serve their syntactic purpose or just as literal characters in data in some places where such use could not be misinterpreted as the character serving its syntactic purpose. (For example, although / has syntactic meaning in a URL, you can use it unencoded in a query string, because it doesn't have meaning in a query string.)

RFC 3986 also specifies some unreserved characters, which can always be used simply to represent data without any encoding:

  • abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~

Finally, the % character itself is allowed for percent-encodings.

That leaves only the following ASCII characters that are forbidden from appearing in a URL:

  • The control characters (chars 0-1F and 7F), including new line, tab, and carriage return.
  • "<>\^`{|}

Every other character from ASCII can legally feature in a URL.

Then RFC 3987 extends that set of unreserved characters with the following unicode character ranges:

  %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
/ %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
/ %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
/ %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
/ %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
/ %xD0000-DFFFD / %xE1000-EFFFD

These block choices from the old spec seem bizarre and arbitrary given the latest Unicode block definitions; this is probably because the blocks have been added to in the decade since RFC 3987 was written.


Finally, it's perhaps worth noting that simply knowing which characters can legally appear in a URL isn't sufficient to recognise whether some given string is a legal URL or not, since some characters are only legal in particular parts of the URL. For example, the reserved characters [ and ] are legal as part of an IPv6 literal host in a URL like http://[1080::8:800:200C:417A]/foo but aren't legal in any other context, so the OP's example of http://example.com/file[/].html is illegal.

What is the HTML unicode character for a "tall" right chevron?

Use '›'

&rsaquo; -> single right angle quote. For single left angle quote, use &lsaquo;

ListView with OnItemClickListener

Hey check this, works for me... hope it work for u too

If list item contains ImageButton

Problem: OnItemClickListener just doesn’t repond any at all!

Reason: No idea

Solution: in code, set ImageButton's focus to “false”

1: ImageButton button = (ImageButton) convertView.findViewById(R.id.imageButton);

2: button.setFocusable(false);

How do you loop through each line in a text file using a windows batch file?

From the Windows command line reference:

To parse a file, ignoring commented lines, type:

for /F "eol=; tokens=2,3* delims=," %i in (myfile.txt) do @echo %i %j %k

This command parses each line in Myfile.txt, ignoring lines that begin with a semicolon and passing the second and third token from each line to the FOR body (tokens are delimited by commas or spaces). The body of the FOR statement references %i to get the second token, %j to get the third token, and %k to get all of the remaining tokens.

If the file names that you supply contain spaces, use quotation marks around the text (for example, "File Name"). To use quotation marks, you must use usebackq. Otherwise, the quotation marks are interpreted as defining a literal string to parse.

By the way, you can find the command-line help file on most Windows systems at:

 "C:\WINDOWS\Help\ntcmds.chm"

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

It is considered bad practice to invoke the actual generator (e.g. via make) if using CMake. It is highly recommended to do it like this:

  1. Configure phase:

    cmake -Hfoo -B_builds/foo/debug -G"Unix Makefiles" -DCMAKE_BUILD_TYPE=Debug -DCMAKE_DEBUG_POSTFIX=d -DCMAKE_INSTALL_PREFIX=/usr
    
  2. Build and Install phases

    cmake --build _builds/foo/debug --config Debug --target install
    

When following this approach, the generator can be easily switched (e.g. -GNinja for Ninja) without having to remember any generator-specific commands.

In DB2 Display a table's definition

Describe table syntax

describe table schemaName.TableName

Pandas: Looking up the list of sheets in an excel file

You should explicitly specify the second parameter (sheetname) as None. like this:

 df = pandas.read_excel("/yourPath/FileName.xlsx", None);

"df" are all sheets as a dictionary of DataFrames, you can verify it by run this:

df.keys()

result like this:

[u'201610', u'201601', u'201701', u'201702', u'201703', u'201704', u'201705', u'201706', u'201612', u'fund', u'201603', u'201602', u'201605', u'201607', u'201606', u'201608', u'201512', u'201611', u'201604']

please refer pandas doc for more details: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html

HTML+CSS: How to force div contents to stay in one line?

Everybody jumped on this one!!! I too made a fiddle:

http://jsfiddle.net/audetwebdesign/kh4aR/

RobAgar gets a point for pointing out white-space:nowrap first.

Couple of things here, you need overflow: hidden if you don't want to see the extra characters poking out into your layout.

Also, as mentioned, you could use white-space: pre (see EnderMB) keeping in mind that pre will not collapse white space whereas white-space: nowrap will.

Get width height of remote image from url

ES6: Using async/await you can do below getMeta function in sequence-like way and you can use it as follows (which is almost identical to code in your question (I add await keyword and change variable end to img, and change var to let keyword). You need to run getMeta by await only from async function (run).

_x000D_
_x000D_
function getMeta(url) {
    return new Promise((resolve, reject) => {
        let img = new Image();
        img.onload = () => resolve(img);
        img.onerror = () => reject();
        img.src = url;
    });
}

async function run() {

  let img = await getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");

  let w = img.width;
  let h = img.height; 

  size.innerText = `width=${w}px, height=${h}px`;
  size.appendChild(img);
}

run();
_x000D_
<div id="size" />
_x000D_
_x000D_
_x000D_

UITableview: How to Disable Selection for Some Rows but Not Others

For swift 4.0 This will do the trick. It will disable the Cell in didSelectRowAtIndexPath method but keep the subviews clickable.

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
         if (indexPath.row == clickableIndex ) { 
            return indexPath
         }else{
            return nil
        }
    }

How to use sed to extract substring

Explaining how you can use cut:

cat yourxmlfile | cut -d'"' -f2

It will 'cut' all the lines in the file based on " delimiter, and will take the 2nd field , which is what you wanted.

Nth max salary in Oracle

select min(sal) from (select distinct sal from employee order by sal DESC) where rownum<=N;

place the number whatever the highest sal you want to retrieve.

how to implement Pagination in reactJs

Give you a pagination component, which is maybe a little difficult to understand for newbie to react:

https://www.npmjs.com/package/pagination

Intersection and union of ArrayLists in Java

I was also working on the similar situation and reached here searching for help. Ended up finding my own solution for Arrays. ArrayList AbsentDates = new ArrayList(); // Will Store Array1-Array2

Note : Posting this if it can help someone reaching this page for help.

ArrayList<String> AbsentDates = new ArrayList<String>();//This Array will store difference
      public void AbsentDays() {
            findDates("April", "2017");//Array one with dates in Month April 2017
            findPresentDays();//Array two carrying some dates which are subset of Dates in Month April 2017

            for (int i = 0; i < Dates.size(); i++) {

                for (int j = 0; j < PresentDates.size(); j++) {

                    if (Dates.get(i).equals(PresentDates.get(j))) {

                        Dates.remove(i);
                    }               

                }              
                AbsentDates = Dates;   
            }
            System.out.println(AbsentDates );
        }

Javascript: The prettiest way to compare one value against multiple values

Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):

(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)

if (~[foo, bar].indexOf(foobar)) {
    // pretty
}

Output (echo/print) everything from a PHP Array

I think you are looking for print_r which will print out the array as text. You can't control the formatting though, it's more for debugging. If you want cool formatting you'll need to do it manually.

Redirecting to a page after submitting form in HTML

For anyone else having the same problem, I figured it out myself.

_x000D_
_x000D_
    <html>_x000D_
      <body>_x000D_
        <form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
          <input type="hidden" name="fullname" value="Sam" />_x000D_
          <input type="hidden" name="city" value="Dubai&#32;" />_x000D_
          <input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
        </form>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.

Read connection string from web.config

First add this:

using System.Configuration;

python: iterate a specific range in a list

You want to use slicing.

for item in listOfStuff[1:3]:
    print item

IPhone/IPad: How to get screen width programmatically?

CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
//Bonus height.
CGFloat height = CGRectGetHeight(screen);

Threads vs Processes in Linux

In my recent work with LINUX is one thing to be aware of is libraries. If you are using threads make sure any libraries you may use across threads are thread-safe. This burned me a couple of times. Notably libxml2 is not thread-safe out of the box. It can be compiled with thread safe but that is not what you get with aptitude install.

C# elegant way to check if a property's property is null

Just stumbled accross this post.

Some time ago I made a suggestion on Visual Studio Connect about adding a new ??? operator.

http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/4104392-add-as-an-recursive-null-reference-check-opera

This would require some work from the framework team but don't need to alter the language but just do some compiler magic. The idea was that the compiler should change this code (syntax not allowed atm)

string product_name = Order.OrderDetails[0].Product.Name ??? "no product defined";

into this code

Func<string> _get_default = () => "no product defined"; 
string product_name = Order == null 
    ? _get_default.Invoke() 
    : Order.OrderDetails[0] == null 
        ? _get_default.Invoke() 
        : Order.OrderDetails[0].Product == null 
            ? _get_default.Invoke() 
            : Order.OrderDetails[0].Product.Name ?? _get_default.Invoke()

For null check this could look like

bool isNull = (Order.OrderDetails[0].Product ??? null) == null;

Understanding string reversal via slicing

It's called Slice Notation in Python and you can read a bit more of how it works here:

Explain Python's slice notation

Handler vs AsyncTask vs Thread

Thread:

You can use the new Thread for long-running background tasks without impacting UI Thread. From java Thread, you can't update UI Thread.

Since normal Thread is not much useful for Android architecture, helper classes for threading have been introduced.

You can find answers to your queries in Threading performance documentation page.

Handler:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.

There are two main uses for a Handler:

  1. To schedule messages and runnables to be executed as some point in the future;

  2. To enqueue an action to be performed on a different thread than your own.

AsyncTask:

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Drawbacks:

  1. By default, an app pushes all of the AsyncTask objects it creates into a single thread. Therefore, they execute in serial fashion, and—as with the main thread—an especially long work packet can block the queue. Due to this reason, use AsyncTask to handle work items shorter than 5ms in duration.

  2. AsyncTask objects are also the most common offenders for implicit-reference issues. AsyncTask objects present risks related to explicit references, as well.

HandlerThread:

You may need a more traditional approach to executing a block of work on a long-running thread (unlike AsyncTask, which should be used for 5ms workload), and some ability to manage that workflow manually. A handler thread is effectively a long-running thread that grabs work from a queue and operates on it.

ThreadPoolExecutor:

This class manages the creation of a group of threads, sets their priorities, and manages how work is distributed among those threads. As workload increases or decreases, the class spins up or destroys more threads to adjust to the workload.

If the workload is more and single HandlerThread is not suffice, you can go for ThreadPoolExecutor

However I would like to have a socket connection run in service. Should this be run in a handler or a thread, or even an AsyncTask? UI interaction is not necessary at all. Does it make a difference in terms of performance which I use?

Since UI interaction is not required, you may not go for AsyncTask. Normal threads are not much useful and hence HandlerThread is the best option. Since you have to maintain socket connection, Handler on the main thread is not useful at all. Create a HandlerThread and get a Handler from the looper of HandlerThread.

 HandlerThread handlerThread = new HandlerThread("SocketOperation");
 handlerThread.start();
 Handler requestHandler = new Handler(handlerThread.getLooper());
 requestHandler.post(myRunnable); // where myRunnable is your Runnable object. 

If you want to communicate back to UI thread, you can use one more Handler to process response.

final Handler responseHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            //txtView.setText((String) msg.obj);
            Toast.makeText(MainActivity.this,
                    "Foreground task is completed:"+(String)msg.obj,
                    Toast.LENGTH_LONG)
                    .show();
        }
    };

in your Runnable, you can add

responseHandler.sendMessage(msg);

More details about implementation can be found here:

Android: Toast in a thread

Appending an element to the end of a list in Scala

That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:

(4 :: List(1,2,3).reverse).reverse

or that:

List(1,2,3) ::: List(4)

How to start jenkins on different port rather than 8080 using command prompt in Windows?

Change the '/etc/init.d/jenkins' shell

check_tcp_port "http" "$HTTP_PORT" "8080" || return 1

Change 8080 to whichever you want

Shortcut to open file in Vim

There's also command-t which I find to be the best of the bunch (and I've tried them all). It's a minor hassle to install it but, once it's installed, it's a dream to use.

https://wincent.com/products/command-t/

DateTime.Now.ToShortDateString(); replace month and day

Use DateTime.ToString with the specified format MM.dd.yyyy:

this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");

Here, MM means the month from 01 to 12, dd means the day from 01 to 31 and yyyy means the year as a four-digit number.

How do I detect "shift+enter" and generate a new line in Textarea?

In case someone is still wondering how to do this without jQuery.

HTML

<textarea id="description"></textarea>

Javascript

const textarea = document.getElementById('description');

textarea.addEventListener('keypress', (e) => {
    e.keyCode === 13 && !e.shiftKey && e.preventDefault(); 
})

Vanilla JS

var textarea = document.getElementById('description');

textarea.addEventListener('keypress', function(e) {
    if(e.keyCode === 13 && !e.shiftKey) {
      e.preventDefault();
    }
})

Stashing only staged changes in git - is it possible?

Why don't you commit the change for a certain bug and create a patch from that commit and its predecessor?

# hackhackhack, fix two unrelated bugs
git add -p                   # add hunks of first bug
git commit -m 'fix bug #123' # create commit #1
git add -p                   # add hunks of second bug
git commit -m 'fix bug #321' # create commit #2

Then, to create the appropriate patches, use git format-patch:

git format-patch HEAD^^

This will create two files: 0001-fix-bug-123.patch and 0002-fix-bug-321.patch

Or you can create separate branches for each bug, so you can merge or rebase bug fixes individually, or even delete them, if they don't work out.

How to check all checkboxes using jQuery?

function chek_al_indi(id)
{
    var k = id;
    var cnt_descriptiv_indictr = eval($('#cnt_descriptiv_indictr').val());
    var std_cnt = 10;

    if ($('#'+ k).is(":checked"))
    {
        for (var i = 1; i <= std_cnt; i++)  
        {
            $("#chk"+ k).attr('checked',true);  
            k = k + cnt_descriptiv_indictr;
        }
    }

    if ($('#'+ k).is(":not(:checked)"))
    {
        for (var i = 1; i <= std_cnt; i++)  
        {
            $("#chk"+ k).attr('checked',false);     
            k = k + cnt_descriptiv_indictr;
        }       
    }
}

java build path problems

Here's a good discussion on this:

Basically you should

  1. Download and install the 1.5 JDK. (download link)
  2. In Eclipse, Go to Window ? Preferences ? Java ? Installed JREs.
  3. Add the 1.5 JDK to the list.
  4. Select 1.5 as Compiler Compliance Level.

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

Don't forget to check

innodb_data_home_dir = <your_directory_location>
innodb_log_group_home_dir = <your_directory_location>

on my.ini files. Wrong set value for these two variable make mysql process terminated and produce error 1067. Also check eventvwr.msc and mysql_error.log for detail error.

How to format a floating number to fixed width in Python

You can also left pad with zeros. For example if you want number to have 9 characters length, left padded with zeros use:

print('{:09.3f}'.format(number))

Thus, if number = 4.656, the output is: 00004.656

For your example the output will look like this:

numbers  = [23.2300, 0.1233, 1.0000, 4.2230, 9887.2000]
for x in numbers: 
    print('{:010.4f}'.format(x))

prints:

00023.2300
00000.1233
00001.0000
00004.2230
09887.2000

One example where this may be useful is when you want to properly list filenames in alphabetical order. I noticed in some linux systems, the number is: 1,10,11,..2,20,21,...

Thus if you want to enforce the necessary numeric order in filenames, you need to left pad with the appropriate number of zeros.

CSS body background image fixed to full screen even when zooming in/out

I've used these techniques before and they both work well. If you read the pros/cons of each you can decide which is right for your site.

Alternatively you could use the full size background image jQuery plugin if you want to get away from the bugs in the above.

Use awk to find average of a column

awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }'

Add the numbers in $2 (second column) in sum (variables are auto-initialized to zero by awk) and increment the number of rows (which could also be handled via built-in variable NR). At the end, if there was at least one value read, print the average.

awk '{ sum += $2 } END { if (NR > 0) print sum / NR }'

If you want to use the shebang notation, you could write:

#!/bin/awk

{ sum += $2 }
END { if (NR > 0) print sum / NR }

You can also control the format of the average with printf() and a suitable format ("%13.6e\n", for example).

You can also generalize the code to average the Nth column (with N=2 in this sample) using:

awk -v N=2 '{ sum += $N } END { if (NR > 0) print sum / NR }'

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

How to dismiss keyboard iOS programmatically when pressing return

Simply use this in Objective-C to dismiss keyboard:

[[UIApplication sharedApplication].keyWindow endEditing:YES];

How does Java deal with multiple conditions inside a single IF statement

Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

if(s != null && s.length() > 0)

or

if(s == null || s.length() == 0)

BTW if you use & and | it will always evaluate both sides of the expression.

Making macOS Installer Packages which are Developer ID ready

There is one very interesting application by Stéphane Sudre which does all of this for you, is scriptable / supports building from the command line, has a super nice GUI and is FREE. Sad thing is: it's called "Packages" which makes it impossible to find in google.

http://s.sudre.free.fr/Software/Packages/about.html

I wished I had known about it before I started handcrafting my own scripts.

Packages application screenshot

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

If you ensure that every place holder, in each of the contexts involved, is ignoring unresolvable keys then both of these approaches work. For example:

<context:property-placeholder
location="classpath:dao.properties,
          classpath:services.properties,
          classpath:user.properties"
ignore-unresolvable="true"/>

or

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:dao.properties</value>
                <value>classpath:services.properties</value>
                <value>classpath:user.properties</value>
            </list>
        </property> 
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

Well try ini_set('memory_limit', '256M');

134217728 bytes = 128 MB

Or rewrite the code to consume less memory.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

to fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the
deserialized type so that it is a normal .NET type (e.g. not a primitive type like
integer, not a collection type like an array or List) that can be deserialized from a
JSON object.`

The whole message indicates that it is possible to serialize to a List object, but the input must be a JSON list. This means that your JSON must contain

"accounts" : [{<AccountObjectData}, {<AccountObjectData>}...],

Where AccountObject data is JSON representing your Account object or your Badge object

What it seems to be getting currently is

"accounts":{"github":"sergiotapia"}

Where accounts is a JSON object (denoted by curly braces), not an array of JSON objects (arrays are denoted by brackets), which is what you want. Try

"accounts" : [{"github":"sergiotapia"}]

Find and replace in file and overwrite file doesn't work, it empties the file

I was searching for the option where I can define the line range and found the answer. For example I want to change host1 to host2 from line 36-57.

sed '36,57 s/host1/host2/g' myfile.txt > myfile1.txt

You can use gi option as well to ignore the character case.

sed '30,40 s/version/story/gi' myfile.txt > myfile1.txt

What is your single most favorite command-line trick using Bash?

!<first few characters of the command> will execute the last command which matches.

Example:

!b will run "build whatever -O -p -t -i -on" !. will run ./a.out

It works best with long and repetitive commands, like compile, build, execute, etc. It saved me sooo much time when coding and testing.

Skipping error in for-loop

Here's a simple way

for (i in 1:10) {
  
  skip_to_next <- FALSE
  
  # Note that print(b) fails since b doesn't exist
  
  tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
  
  if(skip_to_next) { next }     
}

Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch

_x000D_
_x000D_
var data = { "results":[  _x000D_
  [  _x000D_
     {  _x000D_
        "b":"0.110547334",_x000D_
        "cost":"0.000000",_x000D_
        "w":"1.998889"_x000D_
     }_x000D_
  ],_x000D_
  [  _x000D_
     {  _x000D_
        "x":0,_x000D_
        "y":0_x000D_
     },_x000D_
     {  _x000D_
        "x":1,_x000D_
        "y":2_x000D_
     },_x000D_
     {  _x000D_
        "x":2,_x000D_
        "y":4_x000D_
     },_x000D_
     {  _x000D_
        "x":3,_x000D_
        "y":6_x000D_
     },_x000D_
     {  _x000D_
        "x":4,_x000D_
        "y":8_x000D_
     },_x000D_
     {  _x000D_
        "x":5,_x000D_
        "y":10_x000D_
     },_x000D_
     {  _x000D_
        "x":6,_x000D_
        "y":12_x000D_
     },_x000D_
     {  _x000D_
        "x":7,_x000D_
        "y":14_x000D_
     },_x000D_
     {  _x000D_
        "x":8,_x000D_
        "y":16_x000D_
     },_x000D_
     {  _x000D_
        "x":9,_x000D_
        "y":18_x000D_
     },_x000D_
     {  _x000D_
        "x":10,_x000D_
        "y":20_x000D_
     },_x000D_
     {  _x000D_
        "x":11,_x000D_
        "y":22_x000D_
     },_x000D_
     {  _x000D_
        "x":12,_x000D_
        "y":24_x000D_
     },_x000D_
     {  _x000D_
        "x":13,_x000D_
        "y":26_x000D_
     },_x000D_
     {  _x000D_
        "x":14,_x000D_
        "y":28_x000D_
     },_x000D_
     {  _x000D_
        "x":15,_x000D_
        "y":30_x000D_
     },_x000D_
     {  _x000D_
        "x":16,_x000D_
        "y":32_x000D_
     },_x000D_
     {  _x000D_
        "x":17,_x000D_
        "y":34_x000D_
     },_x000D_
     {  _x000D_
        "x":18,_x000D_
        "y":36_x000D_
     },_x000D_
     {  _x000D_
        "x":19,_x000D_
        "y":38_x000D_
     },_x000D_
     {  _x000D_
        "x":20,_x000D_
        "y":40_x000D_
     },_x000D_
     {  _x000D_
        "x":21,_x000D_
        "y":42_x000D_
     },_x000D_
     {  _x000D_
        "x":22,_x000D_
        "y":44_x000D_
     },_x000D_
     {  _x000D_
        "x":23,_x000D_
        "y":46_x000D_
     },_x000D_
     {  _x000D_
        "x":24,_x000D_
        "y":48_x000D_
     },_x000D_
     {  _x000D_
        "x":25,_x000D_
        "y":50_x000D_
     },_x000D_
     {  _x000D_
        "x":26,_x000D_
        "y":52_x000D_
     },_x000D_
     {  _x000D_
        "x":27,_x000D_
        "y":54_x000D_
     },_x000D_
     {  _x000D_
        "x":28,_x000D_
        "y":56_x000D_
     },_x000D_
     {  _x000D_
        "x":29,_x000D_
        "y":58_x000D_
     },_x000D_
     {  _x000D_
        "x":30,_x000D_
        "y":60_x000D_
     },_x000D_
     {  _x000D_
        "x":31,_x000D_
        "y":62_x000D_
     },_x000D_
     {  _x000D_
        "x":32,_x000D_
        "y":64_x000D_
     },_x000D_
     {  _x000D_
        "x":33,_x000D_
        "y":66_x000D_
     },_x000D_
     {  _x000D_
        "x":34,_x000D_
        "y":68_x000D_
     },_x000D_
     {  _x000D_
        "x":35,_x000D_
        "y":70_x000D_
     },_x000D_
     {  _x000D_
        "x":36,_x000D_
        "y":72_x000D_
     },_x000D_
     {  _x000D_
        "x":37,_x000D_
        "y":74_x000D_
     },_x000D_
     {  _x000D_
        "x":38,_x000D_
        "y":76_x000D_
     },_x000D_
     {  _x000D_
        "x":39,_x000D_
        "y":78_x000D_
     },_x000D_
     {  _x000D_
        "x":40,_x000D_
        "y":80_x000D_
     },_x000D_
     {  _x000D_
        "x":41,_x000D_
        "y":82_x000D_
     },_x000D_
     {  _x000D_
        "x":42,_x000D_
        "y":84_x000D_
     },_x000D_
     {  _x000D_
        "x":43,_x000D_
        "y":86_x000D_
     },_x000D_
     {  _x000D_
        "x":44,_x000D_
        "y":88_x000D_
     },_x000D_
     {  _x000D_
        "x":45,_x000D_
        "y":90_x000D_
     },_x000D_
     {  _x000D_
        "x":46,_x000D_
        "y":92_x000D_
     },_x000D_
     {  _x000D_
        "x":47,_x000D_
        "y":94_x000D_
     },_x000D_
     {  _x000D_
        "x":48,_x000D_
        "y":96_x000D_
     },_x000D_
     {  _x000D_
        "x":49,_x000D_
        "y":98_x000D_
     },_x000D_
     {  _x000D_
        "x":50,_x000D_
        "y":100_x000D_
     },_x000D_
     {  _x000D_
        "x":51,_x000D_
        "y":102_x000D_
     },_x000D_
     {  _x000D_
        "x":52,_x000D_
        "y":104_x000D_
     },_x000D_
     {  _x000D_
        "x":53,_x000D_
        "y":106_x000D_
     },_x000D_
     {  _x000D_
        "x":54,_x000D_
        "y":108_x000D_
     },_x000D_
     {  _x000D_
        "x":55,_x000D_
        "y":110_x000D_
     },_x000D_
     {  _x000D_
        "x":56,_x000D_
        "y":112_x000D_
     },_x000D_
     {  _x000D_
        "x":57,_x000D_
        "y":114_x000D_
     },_x000D_
     {  _x000D_
        "x":58,_x000D_
        "y":116_x000D_
     },_x000D_
     {  _x000D_
        "x":59,_x000D_
        "y":118_x000D_
     },_x000D_
     {  _x000D_
        "x":60,_x000D_
        "y":120_x000D_
     },_x000D_
     {  _x000D_
        "x":61,_x000D_
        "y":122_x000D_
     },_x000D_
     {  _x000D_
        "x":62,_x000D_
        "y":124_x000D_
     },_x000D_
     {  _x000D_
        "x":63,_x000D_
        "y":126_x000D_
     },_x000D_
     {  _x000D_
        "x":64,_x000D_
        "y":128_x000D_
     },_x000D_
     {  _x000D_
        "x":65,_x000D_
        "y":130_x000D_
     },_x000D_
     {  _x000D_
        "x":66,_x000D_
        "y":132_x000D_
     },_x000D_
     {  _x000D_
        "x":67,_x000D_
        "y":134_x000D_
     },_x000D_
     {  _x000D_
        "x":68,_x000D_
        "y":136_x000D_
     },_x000D_
     {  _x000D_
        "x":69,_x000D_
        "y":138_x000D_
     },_x000D_
     {  _x000D_
        "x":70,_x000D_
        "y":140_x000D_
     },_x000D_
     {  _x000D_
        "x":71,_x000D_
        "y":142_x000D_
     },_x000D_
     {  _x000D_
        "x":72,_x000D_
        "y":144_x000D_
     },_x000D_
     {  _x000D_
        "x":73,_x000D_
        "y":146_x000D_
     },_x000D_
     {  _x000D_
        "x":74,_x000D_
        "y":148_x000D_
     },_x000D_
     {  _x000D_
        "x":75,_x000D_
        "y":150_x000D_
     },_x000D_
     {  _x000D_
        "x":76,_x000D_
        "y":152_x000D_
     },_x000D_
     {  _x000D_
        "x":77,_x000D_
        "y":154_x000D_
     },_x000D_
     {  _x000D_
        "x":78,_x000D_
        "y":156_x000D_
     },_x000D_
     {  _x000D_
        "x":79,_x000D_
        "y":158_x000D_
     },_x000D_
     {  _x000D_
        "x":80,_x000D_
        "y":160_x000D_
     },_x000D_
     {  _x000D_
        "x":81,_x000D_
        "y":162_x000D_
     },_x000D_
     {  _x000D_
        "x":82,_x000D_
        "y":164_x000D_
     },_x000D_
     {  _x000D_
        "x":83,_x000D_
        "y":166_x000D_
     },_x000D_
     {  _x000D_
        "x":84,_x000D_
        "y":168_x000D_
     },_x000D_
     {  _x000D_
        "x":85,_x000D_
        "y":170_x000D_
     },_x000D_
     {  _x000D_
        "x":86,_x000D_
        "y":172_x000D_
     },_x000D_
     {  _x000D_
        "x":87,_x000D_
        "y":174_x000D_
     },_x000D_
     {  _x000D_
        "x":88,_x000D_
        "y":176_x000D_
     },_x000D_
     {  _x000D_
        "x":89,_x000D_
        "y":178_x000D_
     },_x000D_
     {  _x000D_
        "x":90,_x000D_
        "y":180_x000D_
     },_x000D_
     {  _x000D_
        "x":91,_x000D_
        "y":182_x000D_
     },_x000D_
     {  _x000D_
        "x":92,_x000D_
        "y":184_x000D_
     },_x000D_
     {  _x000D_
        "x":93,_x000D_
        "y":186_x000D_
     },_x000D_
     {  _x000D_
        "x":94,_x000D_
        "y":188_x000D_
     },_x000D_
     {  _x000D_
        "x":95,_x000D_
        "y":190_x000D_
     },_x000D_
     {  _x000D_
        "x":96,_x000D_
        "y":192_x000D_
     },_x000D_
     {  _x000D_
        "x":97,_x000D_
        "y":194_x000D_
     },_x000D_
     {  _x000D_
        "x":98,_x000D_
        "y":196_x000D_
     },_x000D_
     {  _x000D_
        "x":99,_x000D_
        "y":198_x000D_
     }_x000D_
  ]]};_x000D_
_x000D_
var scatterSeries = []; _x000D_
_x000D_
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';_x000D_
               console.info(ch);_x000D_
               _x000D_
               scatterSeries.push(JSON.parse(ch));_x000D_
console.info(scatterSeries);
_x000D_
_x000D_
_x000D_

code sample - https://codepen.io/nagasai/pen/GGzZVB

How can I update npm on Windows?

follow these steps for window 10 or window 8

  • press WIN + R and type cmd and enter
  • npm i -g npm@next
  • npm i -g npm@next OR npm i -g node@{version}
  • Remove environment path C:\Program Files\nodejs from envrionment variable PATH.
  • type refreshenv in cmd

Now you will have your new version which you installed.

Note: If you don't remove path. You will see the previous version of node.

How to find all the subclasses of a class given its name?

This isn't as good an answer as using the special built-in __subclasses__() class method which @unutbu mentions, so I present it merely as an exercise. The subclasses() function defined returns a dictionary which maps all the subclass names to the subclasses themselves.

def traced_subclass(baseclass):
    class _SubclassTracer(type):
        def __new__(cls, classname, bases, classdict):
            obj = type(classname, bases, classdict)
            if baseclass in bases: # sanity check
                attrname = '_%s__derived' % baseclass.__name__
                derived = getattr(baseclass, attrname, {})
                derived.update( {classname:obj} )
                setattr(baseclass, attrname, derived)
             return obj
    return _SubclassTracer

def subclasses(baseclass):
    attrname = '_%s__derived' % baseclass.__name__
    return getattr(baseclass, attrname, None)


class BaseClass(object):
    pass

class SubclassA(BaseClass):
    __metaclass__ = traced_subclass(BaseClass)

class SubclassB(BaseClass):
    __metaclass__ = traced_subclass(BaseClass)

print subclasses(BaseClass)

Output:

{'SubclassB': <class '__main__.SubclassB'>,
 'SubclassA': <class '__main__.SubclassA'>}

Hibernate, @SequenceGenerator and allocationSize

To be absolutely clear... what you describe does not conflict with the spec in any way. The spec talks about the values Hibernate assigns to your entities, not the values actually stored in the database sequence.

However, there is the option to get the behavior you are looking for. First see my reply on Is there a way to dynamically choose a @GeneratedValue strategy using JPA annotations and Hibernate? That will give you the basics. As long as you are set up to use that SequenceStyleGenerator, Hibernate will interpret allocationSize using the "pooled optimizer" in the SequenceStyleGenerator. The "pooled optimizer" is for use with databases that allow an "increment" option on the creation of sequences (not all databases that support sequences support an increment). Anyway, read up about the various optimizer strategies there.

Bootstrap Dropdown with Hover

Triggering a click event with a hover has a small error. If mouse-in and then a click creates vice-versa effect. It opens when mouse-out and close when mouse-in. A better solution:

$('.dropdown').hover(function() {
    if (!($(this).hasClass('open'))) {
        $('.dropdown-toggle', this).trigger('click');
    }
}, function() {
    if ($(this).hasClass('open')) {
        $('.dropdown-toggle', this).trigger('click');
    }
});

Browser: Identifier X has already been declared

The problem solved when I don't use any declaration like var, let or const

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

I was getting following error on a fedora 18 box:


1. /usr/include/gnu/stubs.h:7:27: fatal error: gnu/stubs-32.h: No such file or directory compilation terminated.

I Installed glibc.i686 and glibc-devel.i686, then compilation failed with following error:

2. /usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-redhat-linux/4.7.2/libgcc_s.so when searching for -lgcc_s /usr/bin/ld: cannot find -lgcc_s collect2: error: ld returned 1 exit status

Solution:

I installed (yum install) glibc.i686 glibc-devel.i386 and libgcc.i686 to get rid of the compilation issue.

Now compilation for 32 bit (-m32) works fine.

What's the best way to send a signal to all members of a process group?

Based on zhigang's answer, this avoids self-killing:

init_killtree() {
    local pid=$1 child

    for child in $(pgrep -P $pid); do
        init_killtree $child
    done
    [ $pid -ne $$ ] && kill -kill $pid
}

Eclipse "this compilation unit is not on the build path of a java project"

You may want to try running eclipse with the -clean startup option - it tries re-building eclipse's metadata of the workspace.

How to convert URL parameters to a JavaScript object?

I needed to also deal with + in the query part of the URL (decodeURIComponent doesn't), so I adapted Wolfgang's code to become:

var search = location.search.substring(1);
search = search?JSON.parse('{"' + search.replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
             function(key, value) { return key===""?value:decodeURIComponent(value)}):{};

In my case, I'm using jQuery to get URL-ready form parameters, then this trick to build an object out of it and I can then easily update parameters on the object and rebuild the query URL, e.g.:

var objForm = JSON.parse('{"' + $myForm.serialize().replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
             function(key, value) { return key===""?value:decodeURIComponent(value)});
objForm.anyParam += stringToAddToTheParam;
var serializedForm = $.param(objForm);

htaccess "order" Deny, Allow, Deny

Not answering OPs question directly, but for the people finding this question in search of clarity on what's the difference between allow,deny and deny,allow:

Read the comma as a "but".

  • allow but deny: whitelist with exceptions.
    everything is denied, except items on the allow list, except items on the deny list
  • deny but allow: blacklist with exceptions.
    everything is allowed, except items on the deny list, except items on the allow list

allow only one country access, but exclude proxies within this country

OP needed a whitelist with exceptions, therefore allow,deny instead of deny,allow

Python: tf-idf-cosine: to find document similarity

Here is a function that compares your test data against the training data, with the Tf-Idf transformer fitted with the training data. Advantage is that you can quickly pivot or group by to find the n closest elements, and that the calculations are down matrix-wise.

def create_tokenizer_score(new_series, train_series, tokenizer):
    """
    return the tf idf score of each possible pairs of documents
    Args:
        new_series (pd.Series): new data (To compare against train data)
        train_series (pd.Series): train data (To fit the tf-idf transformer)
    Returns:
        pd.DataFrame
    """

    train_tfidf = tokenizer.fit_transform(train_series)
    new_tfidf = tokenizer.transform(new_series)
    X = pd.DataFrame(cosine_similarity(new_tfidf, train_tfidf), columns=train_series.index)
    X['ix_new'] = new_series.index
    score = pd.melt(
        X,
        id_vars='ix_new',
        var_name='ix_train',
        value_name='score'
    )
    return score

train_set = pd.Series(["The sky is blue.", "The sun is bright."])
test_set = pd.Series(["The sun in the sky is bright."])
tokenizer = TfidfVectorizer() # initiate here your own tokenizer (TfidfVectorizer, CountVectorizer, with stopwords...)
score = create_tokenizer_score(train_series=train_set, new_series=test_set, tokenizer=tokenizer)
score

   ix_new   ix_train    score
0   0       0       0.617034
1   0       1       0.862012

getting the difference between date in days in java

Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:

private static void dateDiff() {

    System.out.println("Calculate difference between two dates");
    System.out.println("=================================================================");

    DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    System.out.println("  Difference between " + endDate);
    System.out.println("  and " + startDate + " is " + days + " days.");

  }

Find the files that have been changed in last 24 hours

For others who land here in the future (including myself), add a -name option to find specific file types, for instance: find /var -name "*.php" -mtime -1 -ls

How to pretty print nested dictionaries?

As of what have been done, I don't see any pretty printer that at least mimics the output of the python interpreter with very simple formatting so here's mine :

class Formatter(object):
    def __init__(self):
        self.types = {}
        self.htchar = '\t'
        self.lfchar = '\n'
        self.indent = 0
        self.set_formater(object, self.__class__.format_object)
        self.set_formater(dict, self.__class__.format_dict)
        self.set_formater(list, self.__class__.format_list)
        self.set_formater(tuple, self.__class__.format_tuple)

    def set_formater(self, obj, callback):
        self.types[obj] = callback

    def __call__(self, value, **args):
        for key in args:
            setattr(self, key, args[key])
        formater = self.types[type(value) if type(value) in self.types else object]
        return formater(self, value, self.indent)

    def format_object(self, value, indent):
        return repr(value)

    def format_dict(self, value, indent):
        items = [
            self.lfchar + self.htchar * (indent + 1) + repr(key) + ': ' +
            (self.types[type(value[key]) if type(value[key]) in self.types else object])(self, value[key], indent + 1)
            for key in value
        ]
        return '{%s}' % (','.join(items) + self.lfchar + self.htchar * indent)

    def format_list(self, value, indent):
        items = [
            self.lfchar + self.htchar * (indent + 1) + (self.types[type(item) if type(item) in self.types else object])(self, item, indent + 1)
            for item in value
        ]
        return '[%s]' % (','.join(items) + self.lfchar + self.htchar * indent)

    def format_tuple(self, value, indent):
        items = [
            self.lfchar + self.htchar * (indent + 1) + (self.types[type(item) if type(item) in self.types else object])(self, item, indent + 1)
            for item in value
        ]
        return '(%s)' % (','.join(items) + self.lfchar + self.htchar * indent)

To initialize it :

pretty = Formatter()

It can support the addition of formatters for defined types, you simply need to make a function for that like this one and bind it to the type you want with set_formater :

from collections import OrderedDict

def format_ordereddict(self, value, indent):
    items = [
        self.lfchar + self.htchar * (indent + 1) +
        "(" + repr(key) + ', ' + (self.types[
            type(value[key]) if type(value[key]) in self.types else object
        ])(self, value[key], indent + 1) + ")"
        for key in value
    ]
    return 'OrderedDict([%s])' % (','.join(items) +
           self.lfchar + self.htchar * indent)
pretty.set_formater(OrderedDict, format_ordereddict)

For historical reasons, I keep the previous pretty printer which was a function instead of a class, but they both can be used the same way, the class version simply permit much more :

def pretty(value, htchar='\t', lfchar='\n', indent=0):
    nlch = lfchar + htchar * (indent + 1)
    if type(value) is dict:
        items = [
            nlch + repr(key) + ': ' + pretty(value[key], htchar, lfchar, indent + 1)
            for key in value
        ]
        return '{%s}' % (','.join(items) + lfchar + htchar * indent)
    elif type(value) is list:
        items = [
            nlch + pretty(item, htchar, lfchar, indent + 1)
            for item in value
        ]
        return '[%s]' % (','.join(items) + lfchar + htchar * indent)
    elif type(value) is tuple:
        items = [
            nlch + pretty(item, htchar, lfchar, indent + 1)
            for item in value
        ]
        return '(%s)' % (','.join(items) + lfchar + htchar * indent)
    else:
        return repr(value)

To use it :

>>> a = {'list':['a','b',1,2],'dict':{'a':1,2:'b'},'tuple':('a','b',1,2),'function':pretty,'unicode':u'\xa7',("tuple","key"):"valid"}
>>> a
{'function': <function pretty at 0x7fdf555809b0>, 'tuple': ('a', 'b', 1, 2), 'list': ['a', 'b', 1, 2], 'dict': {'a': 1, 2: 'b'}, 'unicode': u'\xa7', ('tuple', 'key'): 'valid'}
>>> print(pretty(a))
{
    'function': <function pretty at 0x7fdf555809b0>,
    'tuple': (
        'a',
        'b',
        1,
        2
    ),
    'list': [
        'a',
        'b',
        1,
        2
    ],
    'dict': {
        'a': 1,
        2: 'b'
    },
    'unicode': u'\xa7',
    ('tuple', 'key'): 'valid'
}

Compared to other versions :

  • This solution looks directly for object type, so you can pretty print almost everything, not only list or dict.
  • Doesn't have any dependancy.
  • Everything is put inside a string, so you can do whatever you want with it.
  • The class and the function has been tested and works with Python 2.7 and 3.4.
  • You can have all type of objects inside, this is their representations and not theirs contents that being put in the result (so string have quotes, Unicode string are fully represented ...).
  • With the class version, you can add formatting for every object type you want or change them for already defined ones.
  • key can be of any valid type.
  • Indent and Newline character can be changed for everything we'd like.
  • Dict, List and Tuples are pretty printed.

Python threading. How do I lock a thread?

import threading 

# global variable x 
x = 0

def increment(): 
    """ 
    function to increment global variable x 
    """
    global x 
    x += 1

def thread_task(): 
    """ 
    task for thread 
    calls increment function 100000 times. 
    """
    for _ in range(100000): 
        increment() 

def main_task(): 
    global x 
    # setting global variable x as 0 
    x = 0

    # creating threads 
    t1 = threading.Thread(target=thread_task) 
    t2 = threading.Thread(target=thread_task) 

    # start threads 
    t1.start() 
    t2.start() 

    # wait until threads finish their job 
    t1.join() 
    t2.join() 

if __name__ == "__main__": 
    for i in range(10): 
        main_task() 
        print("Iteration {0}: x = {1}".format(i,x))

How do I concatenate two lists in Python?

It's also possible to create a generator that simply iterates over the items in both lists using itertools.chain(). This allows you to chain lists (or any iterable) together for processing without copying the items to a new list:

import itertools
for item in itertools.chain(listone, listtwo):
    # Do something with each list item

How to use Elasticsearch with MongoDB?

This answer should be enough to get you set up to follow this tutorial on Building a functional search component with MongoDB, Elasticsearch, and AngularJS.

If you're looking to use faceted search with data from an API then Matthiasn's BirdWatch Repo is something you might want to look at.

So here's how you can setup a single node Elasticsearch "cluster" to index MongoDB for use in a NodeJS, Express app on a fresh EC2 Ubuntu 14.04 instance.

Make sure everything is up to date.

sudo apt-get update

Install NodeJS.

sudo apt-get install nodejs
sudo apt-get install npm

Install MongoDB - These steps are straight from MongoDB docs. Choose whatever version you're comfortable with. I'm sticking with v2.4.9 because it seems to be the most recent version MongoDB-River supports without issues.

Import the MongoDB public GPG Key.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

Update your sources list.

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

Get the 10gen package.

sudo apt-get install mongodb-10gen

Then pick your version if you don't want the most recent. If you are setting your environment up on a windows 7 or 8 machine stay away from v2.6 until they work some bugs out with running it as a service.

apt-get install mongodb-10gen=2.4.9

Prevent the version of your MongoDB installation being bumped up when you update.

echo "mongodb-10gen hold" | sudo dpkg --set-selections

Start the MongoDB service.

sudo service mongodb start

Your database files default to /var/lib/mongo and your log files to /var/log/mongo.

Create a database through the mongo shell and push some dummy data into it.

mongo YOUR_DATABASE_NAME
db.createCollection(YOUR_COLLECTION_NAME)
for (var i = 1; i <= 25; i++) db.YOUR_COLLECTION_NAME.insert( { x : i } )

Now to Convert the standalone MongoDB into a Replica Set.

First Shutdown the process.

mongo YOUR_DATABASE_NAME
use admin
db.shutdownServer()

Now we're running MongoDB as a service, so we don't pass in the "--replSet rs0" option in the command line argument when we restart the mongod process. Instead, we put it in the mongod.conf file.

vi /etc/mongod.conf

Add these lines, subbing for your db and log paths.

replSet=rs0
dbpath=YOUR_PATH_TO_DATA/DB
logpath=YOUR_PATH_TO_LOG/MONGO.LOG

Now open up the mongo shell again to initialize the replica set.

mongo DATABASE_NAME
config = { "_id" : "rs0", "members" : [ { "_id" : 0, "host" : "127.0.0.1:27017" } ] }
rs.initiate(config)
rs.slaveOk() // allows read operations to run on secondary members.

Now install Elasticsearch. I'm just following this helpful Gist.

Make sure Java is installed.

sudo apt-get install openjdk-7-jre-headless -y

Stick with v1.1.x for now until the Mongo-River plugin bug gets fixed in v1.2.1.

wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.1.1.deb
sudo dpkg -i elasticsearch-1.1.1.deb

curl -L http://github.com/elasticsearch/elasticsearch-servicewrapper/tarball/master | tar -xz
sudo mv *servicewrapper*/service /usr/local/share/elasticsearch/bin/
sudo rm -Rf *servicewrapper*
sudo /usr/local/share/elasticsearch/bin/service/elasticsearch install
sudo ln -s `readlink -f /usr/local/share/elasticsearch/bin/service/elasticsearch` /usr/local/bin/rcelasticsearch

Make sure /etc/elasticsearch/elasticsearch.yml has the following config options enabled if you're only developing on a single node for now:

cluster.name: "MY_CLUSTER_NAME"
node.local: true

Start the Elasticsearch service.

sudo service elasticsearch start

Verify it's working.

curl http://localhost:9200

If you see something like this then you're good.

{
  "status" : 200,
  "name" : "Chi Demon",
  "version" : {
    "number" : "1.1.2",
    "build_hash" : "e511f7b28b77c4d99175905fac65bffbf4c80cf7",
    "build_timestamp" : "2014-05-22T12:27:39Z",
    "build_snapshot" : false,
    "lucene_version" : "4.7"
  },
  "tagline" : "You Know, for Search"
}

Now install the Elasticsearch plugins so it can play with MongoDB.

bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb/1.6.0
bin/plugin --install elasticsearch/elasticsearch-mapper-attachments/1.6.0

These two plugins aren't necessary but they're good for testing queries and visualizing changes to your indexes.

bin/plugin --install mobz/elasticsearch-head
bin/plugin --install lukas-vlcek/bigdesk

Restart Elasticsearch.

sudo service elasticsearch restart

Finally index a collection from MongoDB.

curl -XPUT localhost:9200/_river/DATABASE_NAME/_meta -d '{
  "type": "mongodb",
  "mongodb": {
    "servers": [
      { "host": "127.0.0.1", "port": 27017 }
    ],
    "db": "DATABASE_NAME",
    "collection": "ACTUAL_COLLECTION_NAME",
    "options": { "secondary_read_preference": true },
    "gridfs": false
  },
  "index": {
    "name": "ARBITRARY INDEX NAME",
    "type": "ARBITRARY TYPE NAME"
  }
}'

Check that your index is in Elasticsearch

curl -XGET http://localhost:9200/_aliases

Check your cluster health.

curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

It's probably yellow with some unassigned shards. We have to tell Elasticsearch what we want to work with.

curl -XPUT 'localhost:9200/_settings' -d '{ "index" : { "number_of_replicas" : 0 } }'

Check cluster health again. It should be green now.

curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

Go play.

How to remove empty cells in UITableView?

Set a zero height table footer view (perhaps in your viewDidLoad method), like so:

Swift:

tableView.tableFooterView = UIView()

Objective-C:

tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

Because the table thinks there is a footer to show, it doesn't display any cells beyond those you explicitly asked for.

Interface builder pro-tip:

If you are using a xib/Storyboard, you can just drag a UIView (with height 0pt) onto the bottom of the UITableView.

How To Upload Files on GitHub

Here are the steps (in-short), since I don't know what exactly you have done:
1. Download and install Git on your system: http://git-scm.com/downloads
2. Using the Git Bash (a command prompt for Git) or your system's native command prompt, set up a local git repository.
3. Use the same console to checkout, commit, push, etc. the files on the Git.

Hope this helps to those who come searching here.

How do I check whether a checkbox is checked in jQuery?

Though you have proposed a JavaScript solution for your problem (displaying a textbox when a checkbox is checked), this problem could be solved just by css. With this approach, your form works for users who have disabled JavaScript.

Assuming that you have the following HTML:

<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />

You can use the following CSS to achieve the desired functionality:

 #show_textbox:not(:checked) + input[type=text] {display:none;}

For other scenarios, you may think of appropriate CSS selectors.

Here is a Fiddle to demonstrate this approach.

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

Amazon S3 boto - how to create a folder?

Although you can create a folder by appending "/" to your folder_name. Under the hood, S3 maintains flat structure unlike your regular NFS.

var params = {
            Bucket : bucketName,
            Key : folderName + "/"
        };
s3.putObject(params, function (err, data) {});

No assembly found containing an OwinStartupAttribute Error

I wanted to get rid of OWIN in the project:

  1. Delete OWIN references and Nuget packages from project
  2. Clean & Rebuild project
  3. Run app

Then I got OWIN error. These steps didn't work, because OWIN.dll was still in bin/ directory.

FIX:

  1. Delete bin/ directory manually
  2. Rebuild project

How to get a value from a cell of a dataframe?

Converting it to integer worked for me:

int(sub_df.iloc[0])

MongoDB/Mongoose querying at a specific date?

Yeah, Date object complects date and time, so comparing it with just date value does not work.

You can simply use the $where operator to express more complex condition with Javascript boolean expression :)

db.posts.find({ '$where': 'this.created_on.toJSON().slice(0, 10) == "2012-07-14"' })

created_on is the datetime field and 2012-07-14 is the specified date.

Date should be exactly in YYYY-MM-DD format.

Note: Use $where sparingly, it has performance implications.

How do I call one constructor from another in Java?

Using this keyword we can call one constructor in another constructor within same class.

Example :-

 public class Example {
   
      private String name;
   
      public Example() {
          this("Mahesh");
      }

      public Example(String name) {
          this.name = name;
      }

 }

MongoDB or CouchDB - fit for production?

We are currently using mongodb as an file storage service for our collaboration over LAN. Also, projects like trello are using mongodb as their backend datastore. I have used couchdb earlier, but not in production capacity.

How to convert nanoseconds to seconds using the TimeUnit enum?

You should write :

    long startTime = System.nanoTime();        
    long estimatedTime = System.nanoTime() - startTime;

Assigning the endTime in a variable might cause a few nanoseconds. In this approach you will get the exact elapsed time.

And then:

TimeUnit.SECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS)

Difference between Inheritance and Composition

No , Both are different . Composition follow "HAS-A" relationship and inheritance follow "IS-A" relationship . Best Example for composition was Strategic pattern .

How to install MySQLi on MacOS

MySQLi is part of PHP. There should be a php-mysqli type package available, or you can take the PHP source and recompile that mysqli enabled. You may already have it installed, but it's done as a module and is disabled. Check your php.ini for extension=mysqli.so or similar. it may be commented out, or the .so file is present in your extensions directory but not linked to PHP via that extension= directive.

Java FileOutputStream Create File if not exists

Just Giving an alternative way to create the file only if doesn't exists using Path and Files.

Path path = Paths.get("Some/path/filename.txt");
Files.createDirectories(path.getParent());
if( !Files.exists(path))
    Files.createFile(path);
Files.write(path, ("").getBytes());

Dynamic type languages versus static type languages

It depends on context. There a lot benefits that are appropriate to dynamic typed system as well as for strong typed. I'm of opinion that the flow of dynamic types language is faster. The dynamic languages are not constrained with class attributes and compiler thinking of what is going on in code. You have some kinda freedom. Furthermore, the dynamic language usually is more expressive and result in less code which is good. Despite of this, it's more error prone which is also questionable and depends more on unit test covering. It's easy prototype with dynamic lang but maintenance may become nightmare.

The main gain over static typed system is IDE support and surely static analyzer of code. You become more confident of code after every code change. The maintenance is peace of cake with such tools.

The CSRF token is invalid. Please try to resubmit the form

I had the same error, but in my case the problem was that my application was using multiple first-level domains, while the cookie was using one. Removing cookie_domain: ".%domain%" from framework.session in the config.yml caused cookies to default to whatever domain the form was on, and that fixed the problem.

Length of a JavaScript object

Here's the most cross-browser solution.

This is better than the accepted answer because it uses native Object.keys if exists. Thus, it is the fastest for all modern browsers.

if (!Object.keys) {
    Object.keys = function (obj) {
        var arr = [],
            key;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                arr.push(key);
            }
        }
        return arr;
    };
}

Object.keys(obj).length;

text-align: right; not working for <label>

Label is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div element is a block element so its width is by default 100%.

You will have to place the text-align: right; on the div element in your case, or applying display: block; to your label

Another option is to set a width for each label and then use text-align. The display: block method will not be necessary using this.

How to add a linked source folder in Android Studio?

While sourceSets allows you to include entire directory structures, there's no way to exclude parts of it in Android Studio (as of version 1.2), as described here: Android Studio Exclude Class from build?

Until Android Studio gets updated to support include/exclude directives for Android sources, Symlinks work quite well. If you're using Windows, native tools such as junction or mklink can accomplish the equivalent of Un*x symlinks. CygWin can also create these with a little coersion. See: Git Symlinks in Windows and How to make symbolic link with cygwin in Windows 7

MySQL/SQL: Group by date only on a Datetime column

Cast the datetime to a date, then GROUP BY using this syntax:

SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);

Or you can GROUP BY the alias as @orlandu63 suggested:

SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;

Though I don't think it'll make any difference to performance, it is a little clearer.

How to search JSON data in MySQL?

for MySQL all (and 5.7)

SELECT LOWER(TRIM(BOTH 0x22 FROM TRIM(BOTH 0x20 FROM SUBSTRING(SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed)))),LOCATE(0x22,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed))))),LENGTH(json_filed))))) AS result FROM `table`;

Loop through files in a folder in matlab

Looping through all the files in the folder is relatively easy:

files = dir('*.csv');
for file = files'
    csv = load(file.name);
    % Do some stuff
end

Create directory if it does not exist

I wanted to be able to easily let users create a default profile for PowerShell to override some settings, and ended up with the following one-liner (multiple statements yes, but can be pasted into PowerShell and executed at once, which was the main goal):

cls; [string]$filePath = $profile; [string]$fileContents = '<our standard settings>'; if(!(Test-Path $filePath)){md -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; $fileContents | sc $filePath; Write-Host 'File created!'; } else { Write-Warning 'File already exists!' };

For readability, here's how I would do it in a .ps1 file instead:

cls; # Clear console to better notice the results
[string]$filePath = $profile; # Declared as string, to allow the use of texts without plings and still not fail.
[string]$fileContents = '<our standard settings>'; # Statements can now be written on individual lines, instead of semicolon separated.
if(!(Test-Path $filePath)) {
  New-Item -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; # Ignore output of creating directory
  $fileContents | Set-Content $filePath; # Creates a new file with the input
  Write-Host 'File created!';
}
else {
  Write-Warning "File already exists! To remove the file, run the command: Remove-Item $filePath";
};

Execute stored procedure with an Output parameter?

Return val from procedure

ALTER PROCEDURE testme @input  VARCHAR(10),
                       @output VARCHAR(20) output
AS
  BEGIN
      IF @input >= '1'
        BEGIN
            SET @output = 'i am back';

            RETURN;
        END
  END

DECLARE @get VARCHAR(20);

EXEC testme
  '1',
  @get output

SELECT @get 

Detect browser or tab closing

It is possible to check it with the help of window.closed in an event handler on 'unload' event like this, but timeout usage is required (so result cannot be guaranteed if smth delay or prevent window from closure):

Example of JSFiddle (Tested on lates Safari, FF, Chrome, Edge and IE11 )

var win = window.open('', '', 'width=200,height=50,left=200,top=50');
win.document.write(`<html>
   <head><title>CHILD WINDOW/TAB</title></head>
   <body><h2>CHILD WINDOW/TAB</h2></body>
</html>`);
win.addEventListener('load',() => {
    document.querySelector('.status').innerHTML += '<p>Child was loaded!</p>';
});
win.addEventListener('unload',() => {
    document.querySelector('.status').innerHTML += '<p>Child was unloaded!</p>';
    setTimeout(()=>{
        document.querySelector('.status').innerHTML +=  getChildWindowStatus();
    },1000);
});
win.document.close()
document.querySelector('.check-child-window').onclick = ()=> {
    alert(getChildWindowStatus());
}
function getChildWindowStatus() {
  if (win.closed) { 
      return 'Child window has been closed!';
  } else {
      return 'Child window has not been closed!';
  }
}

bodyParser is deprecated express 4

What is your opinion to use express-generator it will generate skeleton project to start with, without deprecated messages appeared in your log

run this command

npm install express-generator -g

Now, create new Express.js starter application by type this command in your Node projects folder.

express node-express-app

That command tell express to generate new Node.js application with the name node-express-app.

then Go to the newly created project directory, install npm packages and start the app using the command

cd node-express-app && npm install && npm start

What does 'URI has an authority component' mean?

I also faced similar problem while working on Affable Bean e-commerce site development. I received an error:

Module has not been deployed.

I checked the sun-resources.xml file and found the following statements which resulted in the error.

<resources>
    <jdbc-resource enabled="true"
                   jndi-name="jdbc/affablebean"
                   object-type="user"
                   pool-name="AffableBeanPool">
    </jdbc-resource>

    <jdbc-connection-pool allow-non-component-callers="false"
                          associate-with-thread="false"
                          connection-creation-retry-attempts="0"
                          connection-creation-retry-interval-in-seconds="10"
                          connection-leak-reclaim="false"
                          connection-leak-timeout-in-seconds="0"
                          connection-validation-method="auto-commit"
                          datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
                          fail-all-connections="false"
                          idle-timeout-in-seconds="300"
                          is-connection-validation-required="false"
                          is-isolation-level-guaranteed="true"
                          lazy-connection-association="false"
                          lazy-connection-enlistment="false"
                          match-connections="false"
                          max-connection-usage-count="0"
                          max-pool-size="32"
                          max-wait-time-in-millis="60000"
                          name="AffableBeanPool"
                          non-transactional-connections="false"
                          pool-resize-quantity="2"
                          res-type="javax.sql.ConnectionPoolDataSource"
                          statement-timeout-in-seconds="-1"
                          steady-pool-size="8"
                          validate-atmost-once-period-in-seconds="0"
                          wrap-jdbc-objects="false">

        <description>Connects to the affablebean database</description>
        <property name="URL" value="jdbc:mysql://localhost:3306/affablebean"/>
        <property name="User" value="root"/>
        <property name="Password" value="nbuser"/>
    </jdbc-connection-pool>
</resources>

Then I changed the statements to the following which is simple and works. I was able to run the file successfully.

<resources>
    <jdbc-resource enabled="true" jndi-name="jdbc/affablebean" object-type="user" pool-name="AffablebeanPool">
        <description/>
    </jdbc-resource>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="AffablebeanPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="URL" value="jdbc:mysql://localhost:3306/AffableBean"/>
        <property name="User" value="root"/>
        <property name="Password" value="nbuser"/>
    </jdbc-connection-pool>
</resources>

Is it possible to see more than 65536 rows in Excel 2007?

I have found that the 65536 limit still applies to pivot tables, even in Excel 2007.

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Python naming conventions for modules

Just nib. Name the class Nib, with a capital N. For more on naming conventions and other style advice, see PEP 8, the Python style guide.

Converting unix time into date-time via excel

in case the above does not work for you. for me this did not for some reasons;

the UNIX numbers i am working on are from the Mozilla place.sqlite dates.

to make it work : i splitted the UNIX cells into two cells : one of the first 10 numbers (the date) and the other 4 numbers left (the seconds i believe)

Then i used this formula, =(A1/86400)+25569 where A1 contains the cell with the first 10 number; and it worked

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Read .doc file with python

You can use python-docx2txt library to read text from Microsoft Word documents. It is an improvement over python-docx library as it can, in addition, extract text from links, headers and footers. It can even extract images.

You can install it by running: pip install docx2txt.

Let's download and read the first Microsoft document on here:

import docx2txt
my_text = docx2txt.process("test.docx")
print(my_text)

Here is a screenshot of the Terminal output the above code:

enter image description here

EDIT:

This does NOT work for .doc files. The only reason I am keep this answer is that it seems there are people who find it useful for .docx files.

How to install Flask on Windows?

Install pip as described here: How do I install pip on Windows?

Then do

pip install flask

That installation tutorial is a bit misleading, it refers to actually running it in a production environment.

Qt: How do I handle the event of the user pressing the 'X' (close) button?

also you can reimplement protected member QWidget::closeEvent()

void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
    // do what you need here
    // then call parent's procedure
    QWidget::closeEvent(event);
}

Merging two images in C#/.NET

This will add an image to another.

using (Graphics grfx = Graphics.FromImage(image))
{
    grfx.DrawImage(newImage, x, y)
}

Graphics is in the namespace System.Drawing

Where to find Application Loader app in Mac?

You can also upload an app using the Application Loader tool by using it from the terminal:

MacBook-Pro:~ denis$ altool --upload-app -f "ios-app.ipa" -u "[email protected]" -p "yourpassword"

To use altool from anywhere in the terminal you could add it to your PATH env variable by typing in terminal:

MacBook-Pro:~ denis$ export PATH=$PATH:/Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Support/
MacBook-Pro:~ denis$ source ~/.bash_profile

How to make a variadic macro (variable number of arguments)

explained for g++ here, though it is part of C99 so should work for everyone

http://www.delorie.com/gnu/docs/gcc/gcc_44.html

quick example:

#define debug(format, args...) fprintf (stderr, format, args)

Installing MySQL-python

Reread the error message. It says:

sh: mysql_config: not found

If you are on Ubuntu Natty, mysql_config belongs to package libmysqlclient-dev

How to convert string to char array in C++?

Simplest way I can think of doing it is:

string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());

For safety, you might prefer:

string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

or could be in this fashion:

string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

SQL Last 6 Months

Try this one

where datediff(month, datetime_column, getdate()) <= 6

To exclude or filter out future dates

where datediff(month, datetime_column, getdate()) between 0 and 6


This part datediff(month, datetime_column, getdate()) will get the month difference in number of current date and Datetime_Column and will return Rows like:

Result
1
2
3
4
5
6
7
8
9
10

This is Our final condition to get last 6 months data

where result <= 6

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

It seems there is no way to do this without custom view. You can get the title view:

View decor = getWindow().getDecorView();
TextView title = (TextView) decor.findViewById(getResources().getIdentifier("action_bar_title", "id", "android"));

But changing of gravity or layout_gravity doesn't have an effect. The problem in the ActionBarView, which layout its children by itself so changing of layout params of its children also doesn't have an effect. To see this excecute following code:

ViewGroup actionBar = (ViewGroup) decor.findViewById(getResources().getIdentifier("action_bar", "id", "android"));
View v = actionBar.getChildAt(0);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity= Gravity.CENTER;
v.setLayoutParams(p);
v.setBackgroundColor(Color.BLACK);

Install a .NET windows service without InstallUtil.exe

Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...

Here's an example:

[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
    public MyServiceInstallerProcess()
    {
        this.Account = ServiceAccount.NetworkService;
    }
}

[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
    public MyServiceInstaller()
    {
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    }
}

static void Install(bool undo, string[] args)
{
    try
    {
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
        {
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
            try
            {
                if (undo)
                {
                    inst.Uninstall(state);
                }
                else
                {
                    inst.Install(state);
                    inst.Commit(state);
                }
            }
            catch
            {
                try
                {
                    inst.Rollback(state);
                }
                catch { }
                throw;
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

A child container failed during start java.util.concurrent.ExecutionException

I have observed a similar issue in my project. The issue was solved when the jar with the missing class definition was pasted into the lib directory of tomcat.

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

Don't quote the column filename

mysql> INSERT INTO risks (status, subject, reference_id, location, category, team,    technology, owner, manager, assessment, notes,filename) 
VALUES ('san', 'ss', 1, 1, 1, 1, 2, 1, 1, 'sment', 'notes','santu');

How to get line count of a large file cheaply in Python?

How about this one-liner:

file_length = len(open('myfile.txt','r').read().split('\n'))

Takes 0.003 sec using this method to time it on a 3900 line file

def c():
  import time
  s = time.time()
  file_length = len(open('myfile.txt','r').read().split('\n'))
  print time.time() - s

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

How do shift operators work in Java?

The typical usage of shifting a variable and assigning back to the variable can be rewritten with shorthand operators <<=, >>=, or >>>=, also known in the spec as Compound Assignment Operators.

For example,

i >>= 2

produces the same result as

i = i >> 2

How do I include a JavaScript script file in Angular and call a function from that script?

In order to include a global library, eg jquery.js file in the scripts array from angular-cli.json (angular.json when using angular 6+):

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

After this, restart ng serve if it is already started.

Simple Pivot Table to Count Unique Values

I found an easier way of doing this. Referring to Siddarth Rout's example, if I want to count unique values in column A:

  • add a new column C and fill C2 with formula "=1/COUNTIF($A:$A,A2)"
  • drag formula down to the rest of the column
  • pivot with column A as row label, and Sum{column C) in values to get the number of unique values in column A

Getting a list of all subdirectories in the current directory

This answer didn't seem to exist already.

directories = [ x for x in os.listdir('.') if os.path.isdir(x) ]

Convert seconds value to hours minutes seconds?

DateUtils.formatElapsedTime(long), formats an elapsed time in the form "MM:SS" or "H:MM:SS" . It returns the String you are looking for. You can find the documentation here

Telegram Bot - how to get a group chat id?

I tested now 4h but it dont work 2021 with the group-chat-id. All the time the error {"ok":true,"result":[]}

But now i found a Solution:

1:) install the "Plus Messenger" (https://play.google.com/store/apps/details?id=org.telegram.plus)

2:) go in the Group => Tap now on the "Group-Name" in the Head => Double Tap now on the Headline from the Group. A Info is comming: ID123456789 is copy in the clipboard

3:) go in the Group an paste the clipboard text. It´s you Groud-ID

4:) looks like 1068773197, which is -1001068773197 for bots (with -100 prefix)!!!

btw, you see the user-id too, on your profil.

5:) Now go to the Webbrowser an send this line (Test Message):

https://api.telegram.org/botAPITOKENNUMBER:APITOKENKEYHERE/sendmessage?chat_id=-100GROUPNUMBER&text=test

Edit the API Token and the Group-ID!

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

var x = function() vs. function x() — Function declaration syntax

(function(){})() — IIFE (Immediately Invoked Function Expression)

someFunction()() — Functions which return other functions

=> — Equal sign, greater than: arrow function expression syntax

|> — Pipe, greater than: Pipeline operator

function*, yield, yield* — Star after function or yield: generator functions

[], Array() — Square brackets: array notation

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value} — Curly brackets: object literal syntax (not to be confused with blocks)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}` — Backticks, dollar sign with curly brackets: template literals

// — Slashes: regular expression literals

$ — Dollar sign in regex replace patterns: $$, $&, $`, $', $n

() — Parentheses: grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"] — Square brackets or dot: property accessors

?., ?.[], ?.() — Question mark, dot: optional chaining operator

:: — Double colon: bind operator

new operator

...iter — Three dots: spread syntax; rest parameters


Increment and decrement

++, -- — Double plus or minus: pre- / post-increment / -decrement operators


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

void operator

+, - — Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

|, &, ^, ~ — Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

% — Percent sign: remainder operator

&&, ||, ! — Double ampersand, double pipe, exclamation point: logical operators

?? — Double question mark: nullish-coalescing operator

** — Double star: power operator (exponentiation)


Equality operators

==, === — Equal signs: equality operators

!=, !== — Exclamation point and equal signs: inequality operators


Bit shift operators

<<, >>, >>> — Two or three angle brackets: bit shift operators


Conditional operator

?:… — Question mark and colon: conditional (ternary) operator


Assignment operators

= — Equal sign: assignment operator

%= — Percent equals: remainder assignment

+= — Plus equals: addition assignment operator

&&=, ||=, ??= — Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

Destructuring


Comma operator

, — Comma operator


Control flow

{} — Curly brackets: blocks (not to be confused with object literal syntax)

Declarations

var, let, const — Declaring variables


Label

label: — Colon: labels


# — Hash (number sign): Private methods or private fields

How to obtain Telegram chat_id for a specific user?

I created a bot to get User or GroupChat id, just send the /my_id to telegram bot @get_id_bot.

It does not only work for user chat ID, but also for group chat ID.

To get group chat ID, first you have to add the bot to the group, then send /my_id in the group.

Here's the link to the bot.

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

In Kotlin, you can do:

ContextCompat.getColor(requireContext(), R.color.stage_hls_fallback_snackbar)

if requireContext() is accessible from where you are calling the function. I was getting an error when trying

ContextCompat.getColor(context, R.color.stage_hls_fallback_snackbar)

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

The errors actually vary. It's helpful to run ./emulator with -verbose option, as it will show the actual errors.

typescript - cloning object

It's easy to get a shallow copy with "Object Spread" introduced in TypeScript 2.1

this TypeScript: let copy = { ...original };

produces this JavaScript:

var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
var copy = __assign({}, original);

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html

How to convert JSON to a Ruby hash

You could also use Rails' with_indifferent_access method so you could access the body with either symbols or strings.

value = '{"val":"test","val1":"test1","val2":"test2"}'
json = JSON.parse(value).with_indifferent_access

then

json[:val] #=> "test"

json["val"] #=> "test"

PivotTable to show values, not sum of values

I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.

Assuming your data is in ColumnA:C and has column labels in Row 1, also that Month is formatted mmm(this last for ease of sorting):

  1. Sort the data by Name then Month
  2. Enter in D2 =IF(AND(A2=A1,C2=C1),D1+1,1) (One way to deal with what is the tricky issue of multiple entries for the same person for the same month).
  3. Create a pivot table from A1:D(last occupied row no.)
  4. Say insert in F1.
  5. Layout as in screenshot.

SO12803305 example

I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.

  1. Copy pivot table and Paste Special/Values to, say, L1.
  2. Delete top row of copied range with shift cells up.
  3. Insert new cell at L1 and shift down.
  4. Key 'Name' into L1.
  5. Filter copied range and for ColumnL, select Row Labels and numeric values.
  6. Delete contents of L2:L(last selected cell)
  7. Delete blank rows in copied range with shift cells up (may best via adding a column that counts all 12 months). Hopefully result should be as highlighted in yellow.

Happy to explain further/try again (I've not really tested this) if does not suit.

EDIT (To avoid second block of steps above and facilitate updating for source data changes)

.0. Before first step 2. add a blank row at the very top and move A2:D2 up.
.2. Adjust cell references accordingly (in D3 =IF(AND(A3=A2,C3=C2),D2+1,1).
.3. Create pivot table from A:D

.6. Overwrite Row Labels with Name.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1, ColumnG and rows and columns that show (blank).

additional example

Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).

Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank) into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.

Change the current directory from a Bash script

If you run a bash script then it will operates on its current environment or on those of its children, never on the parent.

If goal is to run your command : goto.sh /home/test Then work interactively in /home/test one way is to run a bash interactive subshell within your script :

#!/bin/bash
cd $1
exec bash

This way you will be in /home/test until you exit ( exit or Ctrl+C ) of this shell.

Best way to add Activity to an Android project in Eclipse?

I just use the "New Class" dialog in Eclipse and set the base class as Activity. I'm not aware of any other way to do this. What other method would you expect to be available?

in angularjs how to access the element that triggered the event?

The general Angular way to get access to an element that triggered an event is to write a directive and bind() to the desired event:

app.directive('myChange', function() {
  return function(scope, element) {
    element.bind('change', function() {
      alert('change on ' + element);
    });
  };
});

or with DDO (as per @tpartee's comment below):

app.directive('myChange', function() {
  return { 
    link:  function link(scope, element) {
      element.bind('change', function() {
        alert('change on ' + element);
      });
    }
  }
});

The above directive can be used as follows:

<input id="searchText" ng-model="searchText" type="text" my-change>

Plunker.

Type into the text field, then leave/blur. The change callback function will fire. Inside that callback function, you have access to element.

Some built-in directives support passing an $event object. E.g., ng-*click, ng-Mouse*. Note that ng-change does not support this event.

Although you can get the element via the $event object:

<button ng-click="clickit($event)">Hello</button>

$scope.clickit = function(e) {
    var elem = angular.element(e.srcElement);
    ...

this goes "deep against the Angular way" -- Misko.

Dynamically add data to a javascript map

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

Facebook page automatic "like" URL (for QR Code)

In my opinion, it is not possible for the like button (and I hope it is not possible).

But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.

Getting DOM element value using pure JavaScript

The second function should have:

var value = document.getElementById(id).value;

Then they are basically the same function.

How to create a HTML Cancel button that redirects to a URL

it defaults to submitting a form, easiest way is to add "return false"

<button type="cancel" onclick="window.location='http://stackoverflow.com';return false;">Cancel</button>

Best Regular Expression for Email Validation in C#

First option (bad because of throw-catch, but MS will do work for you):

bool IsValidEmail(string email)
{
    try {
        var mail = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch {
        return false;
    }
}

Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification

Block direct access to a file over http but allow php script access

Are the files on the same server as the PHP script? If so, just keep the files out of the web root and make sure your PHP script has read permissions for wherever they're stored.

gitx How do I get my 'Detached HEAD' commits back into master

If your detached HEAD is a fast forward of master and you just want the commits upstream, you can

git push origin HEAD:master

to push directly, or

git checkout master && git merge [ref of HEAD]

will merge it back into your local master.

Selenium WebDriver and DropDown Boxes

Try the Select helper class and see if that makes any difference?

String valueToSelect= "Germany";
WebElement select = driver.findElement(By.id("selection"));
Select dropDown = new Select(select);           
String selected = dropDown.getFirstSelectedOption().getText();
if(selected.equals(valueToSelect)) {//do stuff already selected}
List<WebElement> Options = dropDown.getOptions();
for(WebElement option:Options){
  if(option.getText().equals(valueToSelect)){
       option.click();  
  }
}

How to change current working directory using a batch file

Just use cd /d %root% to switch driver letters and change directories.

Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.

Note that pushd will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd for that directory.

How to get numbers after decimal point?

If you are using pandas:

df['decimals'] = df['original_number'].mod(1)

How could I convert data from string to long in c#

This answer no longer works, and I cannot come up with anything better then the other answers (see below) listed here. Please review and up-vote them.

Convert.ToInt64("1100.25")

Method signature from MSDN:

public static long ToInt64(
    string value
)

Input and Output binary streams using JERSEY?

This worked fine with me url:http://example.com/rest/muqsith/get-file?filePath=C:\Users\I066807\Desktop\test.xml

@GET
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
@Path("/get-file")
public Response getFile(@Context HttpServletRequest request){
   String filePath = request.getParameter("filePath");
   if(filePath != null && !"".equals(filePath)){
        File file = new File(filePath);
        StreamingOutput stream = null;
        try {
        final InputStream in = new FileInputStream(file);
        stream = new StreamingOutput() {
            public void write(OutputStream out) throws IOException, WebApplicationException {
                try {
                    int read = 0;
                        byte[] bytes = new byte[1024];

                        while ((read = in.read(bytes)) != -1) {
                            out.write(bytes, 0, read);
                        }
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
        return Response.ok(stream).header("content-disposition","attachment; filename = "+file.getName()).build();
        }
    return Response.ok("file path null").build();
}

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

I run it like this -

created > startOfDay(-0d)

It gives me all issues created today. When you change -0d to -1d, it will give you all issues created yesterday and today.

Is it possible to decrypt MD5 hashes?

No, it is not possible to reverse a hash function such as MD5: given the output hash value it is impossible to find the input message unless enough information about the input message is known.

Decryption is not a function that is defined for a hash function; encryption and decryption are functions of a cipher such as AES in CBC mode; hash functions do not encrypt nor decrypt. Hash functions are used to digest an input message. As the name implies there is no reverse algorithm possible by design.


MD5 has been designed as a cryptographically secure, one-way hash function. It is now easy to generate collisions for MD5 - even if a large part of the input message is pre-determined. So MD5 is officially broken and MD5 should not be considered a cryptographically secure hash anymore. It is however still impossible to find an input message that leads to a hash value: find X when only H(X) is known (and X doesn't have a pre-computed structure with at least one 128 byte block of precomputed data). There are no known pre-image attacks against MD5.

It is generally also possible to guess passwords using brute force or (augmented) dictionary attacks, to compare databases or to try and find password hashes in so called rainbow tables. If a match is found then it is computationally certain that the input has been found. Hash functions are also secure against collision attacks: finding X' so that H(X') = H(X) given H(X). So if an X is found it is computationally certain that it was indeed the input message. Otherwise you would have performed a collision attack after all. Rainbow tables can be used to speed up the attacks and there are specialized internet resources out there that will help you find a password given a specific hash.

It is of course possible to re-use the hash value H(X) to verify passwords that were generated on other systems. The only thing that the receiving system has to do is to store the result of a deterministic function F that takes H(X) as input. When X is given to the system then H(X) and therefore F can be recalculated and the results can be compared. In other words, it is not required to decrypt the hash value to just verify that a password is correct, and you can still store the hash as a different value.


Instead of MD5 it is important to use a password hash or PBKDF (password based key derivation function) instead. Such a function specifies how to use a salt together with a hash. That way identical hashes won't be generated for identical passwords (from other users or within other databases). Password hashes for that reason also do not allow rainbow tables to be used as long as the salt is large enough and properly randomized.

Password hashes also contain a work factor (sometimes configured using an iteration count) that can significantly slow down attacks that try to find the password given the salt and hash value. This is important as the database with salts and hash values could be stolen. Finally, the password hash may also be memory-hard so that a significant amount of memory is required to calculate the hash. This makes it impossible to use special hardware (GPU's, ASIC's, FPGA's etc.) to allow an attacker to speed up the search. Other inputs or configuration options such as a pepper or the amount of parallelization may also be available to a password hash.

It will however still allow anybody to verify a password given H(X) even if H(X) is a password hash. Password hashes are still deterministic, so if anybody has knows all the input and the hash algorithm itself then X can be used to calculate H(X) and - again - the results can be compared.

Commonly used password hashes are bcrypt, scrypt and PBKDF2. There is also Argon2 in various forms which is the winner of the reasonably recent password hashing competition. Here on CrackStation is a good blog post on doing password security right.


It is possible to make it impossible for adversaries to perform the hash calculation verify that a password is correct. For this a pepper can be used as input to the password hash. Alternatively, the hash value can of course be encrypted using a cipher such as AES and a mode of operation such as CBC or GCM. This however requires the storage of a secret / key independently and with higher access requirements than the password hash.

Change header background color of modal of twitter bootstrap

The corners are actually in .modal-content

So you may try this:

.modal-content {
  background-color: #0480be;
}
.modal-body {
  background-color: #fff;
}

If you change the color of the header or footer, the rounded corners will be drawn over.

How to tag an older commit in Git?

This is an old question, and the answers already given all work, but there's also a new option which can be considered.

If you're using SourceTree to manage your git repositories, you can right-click on any commit and add a tag to it. With another mouseclick you can also send the tag straight to the branch on origin.

How to deselect a selected UITableView cell?

Try this:

for (NSIndexPath *indexPath in tableView.indexPathsForSelectedRows) {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

The I/O operation has been aborted because of either a thread exit or an application request

I had this problem. I think that it was caused by the socket getting opened and no data arriving within a short time after the open. I was reading from a serial to ethernet box called a Devicemaster. I changed the Devicemaster port setting from "connect always" to "connect on data" and the problem disappeared. I have great respect for Hans Passant but I do not agree that this is an error code that you can easily solve by scrutinizing code.

Renew Provisioning Profile

I went to the Program Portal on Apple's dev site, clicked on Provisioning, clicked on the "Renew" button next to my Profile, the status changed from 'expired' to 'pending', waited a few moments, clicked refresh, the new status was active until 3 months from now, I clicked on "Download", found the downloaded file in my downloads folder, and dragged it onto my XCode Icon. (I had Xcode running already, and had the iphone plugged in). The new profile showed up, and I deleted the old one (being careful because they had the same name, but when you mouse over them the expiration date appears).

I think because I had the phone plugged in already it automagically updated to the phone, because I didn't have to re-sync or anything.

Now my App works again!

rails 3 validation on uniqueness on multiple attributes

Multiple Scope Parameters:

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

This should answer Greg's question.

Writing BMP image in pure c/c++ without other libraries

C++ answer, flexible API, assumes little-endian system to code-golf it a bit. Note this uses the bmp native y-axis (0 at the bottom).

#include <vector>
#include <fstream>

struct image
{   
    image(int width, int height)
    :   w(width), h(height), rgb(w * h * 3)
    {}
    uint8_t & r(int x, int y) { return rgb[(x + y*w)*3 + 2]; }
    uint8_t & g(int x, int y) { return rgb[(x + y*w)*3 + 1]; }
    uint8_t & b(int x, int y) { return rgb[(x + y*w)*3 + 0]; }

    int w, h;
    std::vector<uint8_t> rgb;
};

template<class Stream>
Stream & operator<<(Stream & out, image const& img)
{   
    uint32_t w = img.w, h = img.h;
    uint32_t pad = w * -3 & 3;
    uint32_t total = 54 + 3*w*h + pad*h;
    uint32_t head[13] = {total, 0, 54, 40, w, h, (24<<16)|1};
    char const* rgb = (char const*)img.rgb.data();

    out.write("BM", 2);
    out.write((char*)head, 52);
    for(uint32_t i=0 ; i<h ; i++)
    {   out.write(rgb + (3 * w * i), 3 * w);
        out.write((char*)&pad, pad);
    }
    return out;
}

int main()
{
    image img(100, 100);
    for(int x=0 ; x<100 ; x++)
    {   for(int y=0 ; y<100 ; y++)
        {   img.r(x,y) = x;
            img.g(x,y) = y;
            img.b(x,y) = 100-x;
        }
    }
    std::ofstream("/tmp/out.bmp") << img;
}

Google Chrome "window.open" workaround?

I believe currently there is no javascript way to force chrome to open as a new window in tab mode. A ticket has been submitted as in here Pop-ups to show as tab by default. But the user can click the chrome icon on the top left corner and select "Show as tab", the address bar then becomes editable.

A similar question asked in javascript open in a new window not tab.

Attach to a processes output for viewing

I think I have a simpler solution here. Just look for a directory whose name corresponds to the PID you are looking for, under the pseudo-filesystem accessible under the /proc path. So if you have a program running, whose ID is 1199, cd into it:

$ cd /proc/1199

Then look for the fd directory underneath

$ cd fd

This fd directory hold the file-descriptors objects that your program is using (0: stdin, 1: stdout, 2: stderr) and just tail -f the one you need - in this case, stdout):

$ tail -f 1

Angularjs autocomplete from $http

I found this link helpful

$scope.loadSkillTags = function (query) {
var data = {qData: query};
   return SkillService.querySkills(data).then(function(response) {
   return response.data;
  });
 };

How to set null to a GUID property

Since "Guid" is not nullable, use "Guid.Empty" as default value.

Does SVG support embedding of bitmap images?

You could use a Data URI to supply the image data, for example:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

<image width="20" height="20" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>

</svg>

The image will go through all normal svg transformations.

But this technique has disadvantages, for example the image will not be cached by the browser