Programs & Examples On #Key storage

Delete commit on gitlab

Supose you have the following scenario:

* 1bd2200 (HEAD, master) another commit
* d258546 bad commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit

Where you want to remove d258546 i.e. "bad commit".

You shall try an interactive rebase to remove it: git rebase -i 34c4f95

then your default editor will pop with something like this:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick d258546 bad commit
 pick 1bd2200 another commit

 # Rebase 34c4f95..1bd2200 onto 34c4f95
 #
 # Commands:
 #  p, pick = use commit
 #  r, reword = use commit, but edit the commit message
 #  e, edit = use commit, but stop for amending
 #  s, squash = use commit, but meld into previous commit
 #  f, fixup = like "squash", but discard this commit's log message
 #  x, exec = run command (the rest of the line) using shell
 #
 # These lines can be re-ordered; they are executed from top to bottom.
 #
 # If you remove a line here THAT COMMIT WILL BE LOST.
 #
 # However, if you remove everything, the rebase will be aborted.
 #
 # Note that empty commits are commented out

just remove the line with the commit you want to strip and save+exit the editor:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick 1bd2200 another commit
 ...

git will proceed to remove this commit from your history leaving something like this (mind the hash change in the commits descendant from the removed commit):

 * 34fa994 (HEAD, master) another commit
 * 0f1efa9 3rd commit
 * bd8aa13 2nd commit
 * 34c4f95 1st commit

Now, since I suppose that you already pushed the bad commit to gitlab, you'll need to repush your graph to the repository (but with the -f option to prevent it from being rejected due to a non fastforwardeable history i.e. git push -f <your remote> <your branch>)

Please be extra careful and make sure that none coworker is already using the history containing the "bad commit" in their branches.

Alternative option:

Instead of rewrite the history, you may simply create a new commit which negates the changes introduced by your bad commit, to do this just type git revert <your bad commit hash>. This option is maybe not as clean, but is far more safe (in case you are not fully aware of what are you doing with an interactive rebase).

PHP GuzzleHttp. How to make a post request with params?

Since Marco's answer is deprecated, you must use the following syntax (according jasonlfunk's comment) :

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ]
]);

Request with POST files

$response = $client->request('POST', 'http://www.example.com/files/post', [
    'multipart' => [
        [
            'name'     => 'file_name',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'csv_header',
            'contents' => 'First Name, Last Name, Username',
            'filename' => 'csv_header.csv'
        ]
    ]
]);

REST verbs usage with params

// PUT
$client->put('http://www.example.com/user/4', [
    'body' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ],
    'timeout' => 5
]);

// DELETE
$client->delete('http://www.example.com/user');

Async POST data

Usefull for long server operations.

$client = new \GuzzleHttp\Client();
$promise = $client->requestAsync('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ]
]);
$promise->then(
    function (ResponseInterface $res) {
        echo $res->getStatusCode() . "\n";
    },
    function (RequestException $e) {
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);

Set headers

According to documentation, you can set headers :

// Set various headers on a request
$client->request('GET', '/get', [
    'headers' => [
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz']
    ]
]);

More information for debugging

If you want more details information, you can use debug option like this :

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ],
    // If you want more informations during request
    'debug' => true
]);

Documentation is more explicits about new possibilities.

How to find the length of an array in shell?

In the Fish Shell the length of an array can be found with:

$ set a 1 2 3 4
$ count $a
4

How to add/subtract dates with JavaScript?

startdate.setDate(startdate.getDate() - daysToSubtract);


startdate.setDate(startdate.getDate() + daysToAdd);

convert month from name to number

$string = "July";
echo $month_number = date("n",strtotime($string));

returns '7' [month number]

Use date("m",strtotime($string)); for the output "08"

For more formats reffer this..
http://php.net/manual/en/function.date.php

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How do you extract a column from a multi-dimensional array?

Well a 'bit' late ...

In case performance matters and your data is shaped rectangular, you might also store it in one dimension and access the columns by regular slicing e.g. ...

A = [[1,2,3,4],[5,6,7,8]]     #< assume this 4x2-matrix
B = reduce( operator.add, A ) #< get it one-dimensional

def column1d( matrix, dimX, colIdx ):
  return matrix[colIdx::dimX]

def row1d( matrix, dimX, rowIdx ):
  return matrix[rowIdx:rowIdx+dimX] 

>>> column1d( B, 4, 1 )
[2, 6]
>>> row1d( B, 4, 1 )
[2, 3, 4, 5]

The neat thing is this is really fast. However, negative indexes don't work here! So you can't access the last column or row by index -1.

If you need negative indexing you can tune the accessor-functions a bit, e.g.

def column1d( matrix, dimX, colIdx ):
  return matrix[colIdx % dimX::dimX]

def row1d( matrix, dimX, dimY, rowIdx ):
  rowIdx = (rowIdx % dimY) * dimX
  return matrix[rowIdx:rowIdx+dimX]

A project with an Output Type of Class Library cannot be started directly

To fix this issue, do these steps:

  1. Right click the Project name in Solution Explorer of Visual Studio
  2. Select Set as StartUp Project from the menu
  3. Re-run your project It should work!

If it did not work, be sure that you have set your start page. If your project is C# Windows Application or C# Console Application, try this:

  1. Right click the Project name in Solution Explorer of Visual Studio
  2. Select Properties
  3. Select the Application tab
  4. In the Output Type drop box
  5. Select the correct application type of your project
  6. Re-run your project and let me know if it won’t work.

True and False for && logic and || Logic table

Truth values can be described using a Boolean algebra. The article also contains tables for and and or. This should help you to get started or to get even more confused.

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Something like this should work, I'm not sure whether or not there is a simpler way:

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId, @RequestBody String body,
            HttpServletRequest request, HttpServletResponse response) {
    String json = matchService.getMatchJson(matchId);
    if (json == null) {
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
    }
    return json;
}

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

Vagrant ssh authentication failure

For general information: by default to ssh-connect you may simply use

user: vagrant password: vagrant

https://www.vagrantup.com/docs/boxes/base.html#quot-vagrant-quot-user

First, try: to see what vagrant insecure_private_key is in your machine config

$ vagrant ssh-config

Example:

$ vagrant ssh-config
Host default
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile C:/Users/konst/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
  LogLevel FATAL

http://docs.vagrantup.com/v2/cli/ssh_config.html

Second, do: Change the contents of file insecure_private_key with the contents of your personal system private key

Or use: Add it to the Vagrantfile:

Vagrant.configure("2") do |config|
  config.ssh.private_key_path = "~/.ssh/id_rsa"
  config.ssh.forward_agent = true
end
  1. config.ssh.private_key_path is your local private key
  2. Your private key must be available to the local ssh-agent. You can check with ssh-add -L. If it's not listed, add it with ssh-add ~/.ssh/id_rsa
  3. Don't forget to add your public key to ~/.ssh/authorized_keys on the Vagrant VM. You can do it by copy-and-pasting or using a tool like ssh-copy-id (user: root password: vagrant port: 2222) ssh-copy-id '-p 2222 [email protected]'

If still does not work try this:

  1. Remove insecure_private_key file from c:\Users\USERNAME\.vagrant.d\insecure_private_key

  2. Run vagrant up (vagrant will be generate a new insecure_private_key file)

In other cases, it is helpful to just set forward_agent in Vagrantfile:

Vagrant::Config.run do |config|
   config.ssh.forward_agent = true
end

Useful:

Configurating git may be with git-scm.com

After setup this program and creating personal system private key will be in yours profile path: c:\users\USERNAME\.ssh\id_rsa.pub

PS: Finally - suggest you look at Ubuntu on Windows 10

How do I create a new column from the output of pandas groupby().sum()?

You want to use transform this will return a Series with the index aligned to the df so you can then add it as a new column:

In [74]:

df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
   Data2  Data3        Date   Sym  Data4
0     11      5  2015-05-08  aapl     55
1      8      8  2015-05-07  aapl    108
2     10      6  2015-05-06  aapl     66
3     15      1  2015-05-05  aapl    121
4    110     50  2015-05-08  aaww     55
5     60    100  2015-05-07  aaww    108
6    100     60  2015-05-06  aaww     66
7     40    120  2015-05-05  aaww    121

Copying a local file from Windows to a remote server using scp

Drive letter can be used in the source like

scp /c/path/to/file.txt user@server:/dir1/file.txt

How to close jQuery Dialog within the dialog?

After checking all of these answers above without luck, the folling code worked for me to solve the problem:

$(".ui-dialog").dialog("close");

Maybe this will be also a good try if you seek for alternatives.

Limit Decimal Places in Android EditText

I really liked Pinhassi's answer, but noticed that after the user had entered the specified number digits after the decimal point you could no longer enter text to the left side of the decimal point. The problem was that the solution only tested the previous text that had been entered, not the current text being entered. So here is my solution that inserts the new character into the original text for validation.

package com.test.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;

public class InputFilterCurrency implements InputFilter {
    Pattern moPattern;

    public InputFilterCurrency(int aiMinorUnits) {
        // http://www.regexplanet.com/advanced/java/index.html
        moPattern=Pattern.compile("[0-9]*+((\\.[0-9]{0,"+ aiMinorUnits + "})?)||(\\.)?");

    } // InputFilterCurrency

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String lsStart  = "";
        String lsInsert = "";
        String lsEnd    = "";
        String lsText   = "";

        Log.d("debug", moPattern.toString());
        Log.d("debug", "source: " + source + ", start: " + start + ", end:" + end + ", dest: " + dest + ", dstart: " + dstart + ", dend: " + dend );

        lsText = dest.toString();

        // If the length is greater then 0, then insert the new character
        // into the original text for validation
        if (lsText.length() > 0) {

            lsStart = lsText.substring(0, dstart);
            Log.d("debug", "lsStart : " + lsStart);
            // Check to see if they have deleted a character
            if (source != "") {
                lsInsert = source.toString();
                Log.d("debug", "lsInsert: " + lsInsert);
            } // if
            lsEnd = lsText.substring(dend);
            Log.d("debug", "lsEnd   : " + lsEnd);
            lsText = lsStart + lsInsert + lsEnd;
            Log.d("debug", "lsText  : " + lsText);

        } // if

        Matcher loMatcher = moPattern.matcher(lsText);
        Log.d("debug", "loMatcher.matches(): " + loMatcher.matches() + ", lsText: " + lsText);
        if(!loMatcher.matches()) {
            return "";
        }
        return null;

    } // CharSequence

} // InputFilterCurrency

And the call to set the editText filter

editText.setFilters(new InputFilter[] {new InputFilterCurrency(2)});

Ouput with two decimal places
05-22 15:25:33.434: D/debug(30524): [0-9]*+((\.[0-9]{0,2})?)||(\.)?
05-22 15:25:33.434: D/debug(30524): source: 5, start: 0, end:1, dest: 123.4, dstart: 5, dend: 5
05-22 15:25:33.434: D/debug(30524): lsStart : 123.4
05-22 15:25:33.434: D/debug(30524): lsInsert: 5
05-22 15:25:33.434: D/debug(30524): lsEnd   : 
05-22 15:25:33.434: D/debug(30524): lsText  : 123.45
05-22 15:25:33.434: D/debug(30524): loMatcher.matches(): true, lsText: 123.45

Ouput inserting a 5 in the middle
05-22 15:26:17.624: D/debug(30524): [0-9]*+((\.[0-9]{0,2})?)||(\.)?
05-22 15:26:17.624: D/debug(30524): source: 5, start: 0, end:1, dest: 123.45, dstart: 2, dend: 2
05-22 15:26:17.624: D/debug(30524): lsStart : 12
05-22 15:26:17.624: D/debug(30524): lsInsert: 5
05-22 15:26:17.624: D/debug(30524): lsEnd   : 3.45
05-22 15:26:17.624: D/debug(30524): lsText  : 1253.45
05-22 15:26:17.624: D/debug(30524): loMatcher.matches(): true, lsText: 1253.45

format a number with commas and decimals in C# (asp.net MVC3)

string Mynewcurrency = DisplayIndianCurrency("7743450.00");
        private string DisplayIndianCurrency(string EXruppesformate) 
        { 
        string fare = EXruppesformate;
        decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
        CultureInfo hindi = new CultureInfo("en-IN");
     // string text = string.Format(hindi, "{0:c}", parsed);if you want <b>Rs 77,43,450.00</b>
    string text = string.Format(hindi, "{0:N}", parsed); //if you want <b>77,43,450.00</b>
      return ruppesformate = text;
    }

How to convert CharSequence to String?

By invoking its toString() method.

Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.

Android Horizontal RecyclerView scroll Direction

Assuming you use LinearLayoutManager in your RecyclerView, then you can pass true as third argument in the LinearLayoutManager constructor.

For example:

mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));

If you are using the StaggeredGridLayoutManager, then you can use the setReverseLayout method it provides.

draw diagonal lines in div background with CSS

All other answers to this 3-year old question require CSS3 (or SVG). However, it can also be done with nothing but lame old CSS2:

_x000D_
_x000D_
.crossed {_x000D_
    position: relative;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
.crossed:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 1px;_x000D_
    bottom: 1px;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: black white;_x000D_
}_x000D_
_x000D_
.crossed:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 1px;_x000D_
    right: 1px;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: white transparent;_x000D_
}
_x000D_
<div class='crossed'></div>
_x000D_
_x000D_
_x000D_

Explanation, as requested:

Rather than actually drawing diagonal lines, it occurred to me we can instead color the so-called negative space triangles adjacent to where we want to see these lines. The trick I came up with to accomplish this exploits the fact that multi-colored CSS borders are bevelled diagonally:

_x000D_
_x000D_
.borders {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    background-color: black;_x000D_
    border-width: 40px;_x000D_
    border-style: solid;_x000D_
    border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
_x000D_
_x000D_

To make things fit the way we want, we choose an inner rectangle with dimensions 0 and LINE_THICKNESS pixels, and another one with those dimensions reversed:

_x000D_
_x000D_
.r1 { width: 10px;_x000D_
      height: 0;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: red blue;_x000D_
      margin-bottom: 10px; }_x000D_
.r2 { width: 0;_x000D_
      height: 10px;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: blue transparent; }
_x000D_
<div class='r1'></div><div class='r2'></div>
_x000D_
_x000D_
_x000D_

Finally, use the :before and :after pseudo-selectors and position relative/absolute as a neat way to insert the borders of both of the above rectangles on top of each other into your HTML element of choice, to produce a diagonal cross. Note that results probably look best with a thin LINE_THICKNESS value, such as 1px.

How to display Toast in Android?

 Toast toast=Toast.makeText(getApplicationContext(),"Hello", Toast.LENGTH_SHORT);
 toast.setGravity(Gravity.CENTER, 0, 0); // last two args are X and Y are used for setting position
 toast.setDuration(10000);//you can even use milliseconds to display toast
 toast.show();**//showing the toast is important**

form action with javascript

A form action set to a JavaScript function is not widely supported, I'm surprised it works in FireFox.

The best is to just set form action to your PHP script; if you need to do anything before submission you can just add to onsubmit

Edit turned out you didn't need any extra function, just a small change here:

function validateFormOnSubmit(theForm) {
    var reason = "";
    reason += validateName(theForm.name);
    reason += validatePhone(theForm.phone);
    reason += validateEmail(theForm.emaile);

    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
    } else {
        simpleCart.checkout();
    }
    return false;
}

Then in your form:

<form action="#" onsubmit="return validateFormOnSubmit(this);">

How to test if a list contains another list?

I tried to make this as efficient as possible.

It uses a generator; those unfamiliar with these beasts are advised to check out their documentation and that of yield expressions.

Basically it creates a generator of values from the subsequence that can be reset by sending it a true value. If the generator is reset, it starts yielding again from the beginning of sub.

Then it just compares successive values of sequence with the generator yields, resetting the generator if they don't match.

When the generator runs out of values, i.e. reaches the end of sub without being reset, that means that we've found our match.

Since it works for any sequence, you can even use it on strings, in which case it behaves similarly to str.find, except that it returns False instead of -1.

As a further note: I think that the second value of the returned tuple should, in keeping with Python standards, normally be one higher. i.e. "string"[0:2] == "st". But the spec says otherwise, so that's how this works.

It depends on if this is meant to be a general-purpose routine or if it's implementing some specific goal; in the latter case it might be better to implement a general-purpose routine and then wrap it in a function which twiddles the return value to suit the spec.

def reiterator(sub):
    """Yield elements of a sequence, resetting if sent ``True``."""
    it = iter(sub)
    while True:
        if (yield it.next()):
            it = iter(sub)

def find_in_sequence(sub, sequence):
    """Find a subsequence in a sequence.

    >>> find_in_sequence([2, 1], [-1, 0, 1, 2])
    False
    >>> find_in_sequence([-1, 1, 2], [-1, 0, 1, 2])
    False
    >>> find_in_sequence([0, 1, 2], [-1, 0, 1, 2])
    (1, 3)
    >>> find_in_sequence("subsequence",
    ...                  "This sequence contains a subsequence.")
    (25, 35)
    >>> find_in_sequence("subsequence", "This one doesn't.")
    False

    """
    start = None
    sub_items = reiterator(sub)
    sub_item = sub_items.next()
    for index, item in enumerate(sequence):
        if item == sub_item:
            if start is None: start = index
        else:
            start = None
        try:
            sub_item = sub_items.send(start is None)
        except StopIteration:
            # If the subsequence is depleted, we win!
            return (start, index)
    return False

How to subtract a day from a date?

You can use a timedelta object:

from datetime import datetime, timedelta
    
d = datetime.today() - timedelta(days=days_to_subtract)

R adding days to a date

Use +

> as.Date("2001-01-01") + 45
[1] "2001-02-15"

How to use Git for Unity3D source control?

Just adding in on the subjet of Gitignore. The recommended way only ignores Library and Temp, if its wihtin root of your git project. if you are like me and sometimes need unity project to be a part of the repo, not the whole of the repo, the correct strings in gitignore would be:

**/[Tt]emp
**/[Ll]ibrary
**/[Bb]uild

Convert a bitmap into a byte array

More simple:

return (byte[])System.ComponentModel.TypeDescriptor.GetConverter(pImagen).ConvertTo(pImagen, typeof(byte[]))

How to pass extra variables in URL with WordPress

There are quite few solutions to tackle this issue. First you can go for a plugin if you want:

Or code manually, check out this post:

Also check out:

regex.test V.S. string.match to know if a string matches a regular expression

Don't forget to take into consideration the global flag in your regexp :

var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi');    // => true
reg.test('abcdefghi');    // => false <=

This is because Regexp keeps track of the lastIndex when a new match is found.

What does it mean to bind a multicast (UDP) socket?

It is also very important to distinguish a SENDING multicast socket from a RECEIVING multicast socket.

I agree with all the answers above regarding RECEIVING multicast sockets. The OP noted that binding a RECEIVING socket to an interface did not help. However, it is necessary to bind a multicast SENDING socket to an interface.

For a SENDING multicast socket on a multi-homed server, it is very important to create a separate socket for each interface you want to send to. A bound SENDING socket should be created for each interface.

  // This is a fix for that bug that causes Servers to pop offline/online.
  // Servers will intermittently pop offline/online for 10 seconds or so.
  // The bug only happens if the machine had a DHCP gateway, and the gateway is no longer accessible.
  // After several minutes, the route to the DHCP gateway may timeout, at which
  // point the pingponging stops.
  // You need 3 machines, Client machine, server A, and server B
  // Client has both ethernets connected, and both ethernets receiving CITP pings (machine A pinging to en0, machine B pinging to en1)
  // Now turn off the ping from machine B (en1), but leave the network connected.
  // You will notice that the machine transmitting on the interface with
  // the DHCP gateway will fail sendto() with errno 'No route to host'
  if ( theErr == 0 )
  {
     // inspired by 'ping -b' option in man page:      
     //      -b boundif
     //             Bind the socket to interface boundif for sending.
     struct sockaddr_in bindInterfaceAddr;
     bzero(&bindInterfaceAddr, sizeof(bindInterfaceAddr));
     bindInterfaceAddr.sin_len = sizeof(bindInterfaceAddr);
     bindInterfaceAddr.sin_family = AF_INET;
     bindInterfaceAddr.sin_addr.s_addr = htonl(interfaceipaddr);
     bindInterfaceAddr.sin_port = 0; // Allow the kernel to choose a random port number by passing in 0 for the port.
     theErr = bind(mSendSocketID, (struct sockaddr *)&bindInterfaceAddr, sizeof(bindInterfaceAddr));
     struct sockaddr_in serverAddress;
     int namelen = sizeof(serverAddress);  
     if (getsockname(mSendSocketID, (struct sockaddr *)&serverAddress, (socklen_t *)&namelen) < 0) {
        DLogErr(@"ERROR Publishing service... getsockname err");
     }
     else
     {
        DLog( @"socket %d bind, %@ port %d", mSendSocketID, [NSString stringFromIPAddress:htonl(serverAddress.sin_addr.s_addr)], htons(serverAddress.sin_port) );
     }

Without this fix, multicast sending will intermittently get sendto() errno 'No route to host'. If anyone can shed light on why unplugging a DHCP gateway causes Mac OS X multicast SENDING sockets to get confused, I would love to hear it.

Spark dataframe: collect () vs select ()

Select is a transformation, not an action, so it is lazily evaluated (won't actually do the calculations just map the operations). Collect is an action.

Try:

df.limit(20).collect()

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

Global events are also deprecated.

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

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

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

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

        /*
         * Private methods 
@@ -322,7 +324,7 @@
            loading.hide();

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

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

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

                    content
                        .empty()
@@ -612,7 +614,7 @@
            }

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

            wrap.show();
@@ -912,7 +914,7 @@

        busy = true;

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

        _abort();

@@ -957,7 +959,7 @@
            title.empty().hide();
            wrap.hide();

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

            content.empty();

How to get the last day of the month?

calendar.monthrange provides this information:

calendar.monthrange(year, month)
    Returns weekday of first day of the month and number of days in month, for the specified year and month.

>>> import calendar
>>> calendar.monthrange(2002, 1)
(1, 31)
>>> calendar.monthrange(2008, 2)  # leap years are handled correctly
(4, 29)
>>> calendar.monthrange(2100, 2)  # years divisible by 100 but not 400 aren't leap years
(0, 28)

so:

calendar.monthrange(year, month)[1]

seems like the simplest way to go.

Getting the button into the top right corner inside the div box

#button {
    line-height: 12px;
    width: 18px;
    font-size: 8pt;
    font-family: tahoma;
    margin-top: 1px;
    margin-right: 2px;
    position: absolute;
    top: 0;
    right: 0;
}

join list of lists in python

If you're only going one level deep, a nested comprehension will also work:

>>> x = [["a","b"], ["c"]]
>>> [inner
...     for outer in x
...         for inner in outer]
['a', 'b', 'c']

On one line, that becomes:

>>> [j for i in x for j in i]
['a', 'b', 'c']

python: urllib2 how to send cookie with urlopen request

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

Android Location Providers - GPS or Network Provider?

There are 3 location providers in Android.

They are:

gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.

network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.

passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).

The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).

enter image description here

Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris

Code Reference : https://stackoverflow.com/a/3145655/28557

-----------------------Update-----------------------

Now Android have Fused location provider

The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage

Fused location provider provide three ways to fetch location

  1. Last Location: Use when you want to know current location once.
  2. Request Location using Listener: Use when application is on screen / frontend and require continues location.
  3. Request Location using Pending Intent: Use when application in background and require continues location.

References :

Official site : http://developer.android.com/google/play-services/location.html

Fused location provider example: GIT : https://github.com/kpbird/fused-location-provider-example

http://blog.lemberg.co.uk/fused-location-provider

--------------------------------------------------------

How to tell if string starts with a number with Python?

Try this:

if string[0] in range(10):

Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

Settings to Windows Firewall to allow Docker for Windows to share drive

My G drive stopped being shared with Docker after a recent Windows 10 update. I was getting the same problem saying it was blocked by the Windows firewall when attempting to reshare it.

Then I had tried to solve this issues by couple of suggestion but i cant resolve that issue after that I have tried to Reset credentials below of Shared Drives and my issue was solved.

So If you want then you can try to do this-

enter image description here

Run certain code every n seconds

Save yourself a schizophrenic episode and use the Advanced Python scheduler: http://pythonhosted.org/APScheduler

The code is so simple:

from apscheduler.scheduler import Scheduler

sched = Scheduler()
sched.start()

def some_job():
    print "Every 10 seconds"

sched.add_interval_job(some_job, seconds = 10)

....
sched.shutdown()

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

How to get all the AD groups for a particular user?

If you have a LDAP connection with a username and password to connect to Active Directory, here is the code I used to connect properly:

using System.DirectoryServices.AccountManagement;

// ...

// Connection information
var connectionString = "LDAP://domain.com/DC=domain,DC=com";
var connectionUsername = "your_ad_username";
var connectionPassword = "your_ad_password";

// Get groups for this user
var username = "myusername";

// Split the LDAP Uri
var uri = new Uri(connectionString);
var host = uri.Host;
var container = uri.Segments.Count() >=1 ? uri.Segments[1] : "";

// Create context to connect to AD
var princContext = new PrincipalContext(ContextType.Domain, host, container, connectionUsername, connectionPassword);

// Get User
UserPrincipal user = UserPrincipal.FindByIdentity(princContext, IdentityType.SamAccountName, username);

// Browse user's groups
foreach (GroupPrincipal group in user.GetGroups())
{
    Console.Out.WriteLine(group.Name);
}

How to remove leading whitespace from each line in a file

Use:

sed -e **'s/^[ \t]*//'**  name_of_file_from_which_you_want_to_remove_space > 'name _file_where_you_want_to_store_output'

For example:

sed -e 's/^[ \t]*//'  file1.txt > output.txt

Note:

s/: Substitute command ~ replacement for pattern (^[ \t]*) on each addressed line

^[ \t]*: Search pattern ( ^ – start of the line; [ \t]* match one or more blank spaces including tab)

//: Replace (delete) all matched patterns

Using Postman to access OAuth 2.0 Google APIs

  1. go to https://console.developers.google.com/apis/credentials
  2. create web application credentials.

Postman API Access

  1. use these settings with oauth2 in Postman:

SCOPE = https: //www.googleapis.com/auth/admin.directory.userschema

post https: //www.googleapis.com/admin/directory/v1/customer/customer-id/schemas

{
  "fields": [
    {
      "fieldName": "role",
      "fieldType": "STRING",
      "multiValued": true,
      "readAccessType": "ADMINS_AND_SELF"
    }
  ],
  "schemaName": "SAML"
}
  1. to patch user use:

SCOPE = https://www.googleapis.com/auth/admin.directory.user

PATCH https://www.googleapis.com/admin/directory/v1/users/[email protected]

 {
  "customSchemas": {
     "SAML": {
       "role": [
         {
          "value": "arn:aws:iam::123456789123:role/Admin,arn:aws:iam::123456789123:saml-provider/GoogleApps",
          "customType": "Admin"
         }
       ]
     }
   }
}

Using command line arguments in VBscript

If you need direct access:

WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...

How do I cancel a build that is in progress in Visual Studio?

This is crude, but it works well. The Visual Studio on one of my projects (I turn MVC view building on to catch markup errors), well, the project becomes unresponsive while building. I can't cancel the build using the keyboard shortcuts.

So I made this batch file that sits on my quick launch task bar.

@echo off
echo KILL BILLd
for /L %%i in (1,1,10) do (
   Taskkill /IM aspnet_compiler.exe /F
   timeout 1
)

I also made the batch file launch minimized. The build stops and Visual Studio just throws in the error window that there was a problem building.

how to customise input field width in bootstrap 3

In Bootstrap 3, .form-control (the class you give your inputs) has a width of 100%, which allows you to wrap them into col-lg-X divs for arrangement. Example from the docs:

<div class="row">
  <div class="col-lg-2">
    <input type="text" class="form-control" placeholder=".col-lg-2">
  </div>
  <div class="col-lg-3">
    <input type="text" class="form-control" placeholder=".col-lg-3">
  </div>
  <div class="col-lg-4">
    <input type="text" class="form-control" placeholder=".col-lg-4">
  </div>
</div>

See under Column sizing.

It's a bit different than in Bootstrap 2.3.2, but you get used to it quickly.

Reduce left and right margins in matplotlib plot

plt.savefig("circle.png", bbox_inches='tight',pad_inches=-1)

ImportError: No module named apiclient.discovery

I got this same error when working on a project to parse recent calendar events from Google Calendar.

Using the standard install with pip did not work for me, here is what I did to get the packages I needed.

Go directly to the source, here is a link for the google-api-python-client, but if you need a different language it should not be too different.

https://github.com/google/google-api-python-client

Click on the green "Clone or Download" button near the top left and save it as a zip file. Move the zip to your project folder and extract it there. Then cut all the files from the folder it creates back into the root of your project folder.

Yes, this does clutter your work space, but many compilers have ways to hide files.

After doing this the standard

from googleapiclient import discovery

works great.

Hope this helps.

Free ASP.Net and/or CSS Themes

Microsoft hired one fo the kids from A List Apart to whip some out. The .Net projects are free of charge for download.

http://msdn.microsoft.com/en-us/asp.net/aa336613.aspx

The process cannot access the file because it is being used by another process (File is created but contains nothing)

You are writing to the file prior to closing your filestream:

using(FileStream fs=new FileStream(path,FileMode.OpenOrCreate))
using (StreamWriter str=new StreamWriter(fs))
{
   str.BaseStream.Seek(0,SeekOrigin.End); 
   str.Write("mytext.txt.........................");
   str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
   string addtext="this line is added"+Environment.NewLine;

   str.Flush();

}

File.AppendAllText(path,addtext);  //Exception occurrs ??????????
string readtext=File.ReadAllText(path);
Console.WriteLine(readtext);

The above code should work, using the methods you are currently using. You should also look into the using statement and wrap your streams in a using block.

Tar archiving that takes input from a list of files

You can also pipe in the file names which might be useful:

find /path/to/files -name \*.txt | tar -cvf allfiles.tar -T -

Change user-agent for Selenium web-driver

This is a short solution to change the request UserAgent on the fly.

Change UserAgent of a request with Chrome

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = webdriver.Chrome(driver_path)
driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent":"python 2.7", "platform":"Windows"})
driver.get('http://amiunique.org')

then return your useragent:

agent = driver.execute_script("return navigator.userAgent")

Some sources

The source code of webdriver.py from SeleniumHQ (https://github.com/SeleniumHQ/selenium/blob/11c25d75bd7ed22e6172d6a2a795a1d195fb0875/py/selenium/webdriver/chrome/webdriver.py) extends its functionalities through the Chrome Devtools Protocol

def execute_cdp_cmd(self, cmd, cmd_args):
        """
        Execute Chrome Devtools Protocol command and get returned result

We can use the Chrome Devtools Protocol Viewer to list more extended functionalities (https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) as well as the parameters type to use.

Converting double to string

The exception probably comes from the parseDouble() calls. Check that the values given to that function really reflect a double.

Laravel orderBy on a relationship

Try this solution.

$mainModelData = mainModel::where('column', $value)
    ->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
    ->orderBy('relation_table.title', 'ASC')
    ->with(['relationModal' => function ($q) {
        $q->where('column', 'value');
    }])->get();

Example:

$user = User::where('city', 'kullu')
    ->join('salaries', 'users.id', '=', 'salaries.user_id')
    ->orderBy('salaries.amount', 'ASC')
    ->with(['salaries' => function ($q) {
        $q->where('amount', '>', '500000');
    }])->get();

You can change the column name in join() as per your database structure.

Ctrl+click doesn't work in Eclipse Juno

For me it helped to simply close the edited source file and reopen it. If this doesn't work THEN you can try restarting whole IDE.

Get an array of list element contents in jQuery

Without redundant intermediate arrays:

arr = $('li').map(function(i,el) {
    return $(el).text();
}).get();

See jsfiddle demo

How to use systemctl in Ubuntu 14.04

So you want to remove dangling images? Am I correct?

systemctl enable docker-container-cleanup.timer
systemctl start docker-container-cleanup.timer
systemctl enable docker-image-cleanup.timer 
systemctl start docker-image-cleanup.timer

https://github.com/larsks/docker-tools/tree/master/docker-maintenance-units

How do I escape a single quote in SQL Server?

The following syntax will escape you ONLY ONE quotation mark:

SELECT ''''

The result will be a single quote. Might be very helpful for creating dynamic SQL :). enter image description here

How to calculate cumulative normal distribution?

Here's an example:

>>> from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435

In other words, approximately 95% of the standard normal interval lies within two standard deviations, centered on a standard mean of zero.

If you need the inverse CDF:

>>> norm.ppf(norm.cdf(1.96))
array(1.9599999999999991)

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

You can make a text align to the right inside of any element, including labels.

Html:

<label>Text</label>

Css:

label {display:block; width:x; height:y; text-align:right;}

This way, you give a width and height to your label and make any text inside of it align to the right.

How to copy a collection from one database to another in MongoDB

I know this question has been answered however I personally would not do @JasonMcCays answer due to the fact that cursors stream and this could cause an infinite cursor loop if the collection is still being used. Instead I would use a snapshot():

http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database

@bens answer is also a good one and works well for hot backups of collections not only that but mongorestore does not need to share the same mongod.

How to Call VBA Function from Excel Cells?

The issue you have encountered is that UDFs cannot modify the Excel environment, they can only return a value to the calling cell.

There are several alternatives

  1. For the sample given you don't actually need VBA. This formula will work
    ='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2

  2. Use a rather messy work around: See this answer

  3. You can use ExecuteExcel4Macro or OLEDB

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.

Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.

Try something like this:

var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

How to detect iPhone 5 (widescreen devices)?

CGFloat height = [UIScreen mainScreen].bounds.size.height;

NSLog(@"screen soze is %f",height);

  if (height>550) {

          // 4" screen-do some thing
     }

  else if (height<500) {

        // 3.5 " screen- do some thing

     }

SSRS chart does not show all labels on Horizontal axis

image: reporting services line chart horizontal axis properties

To see all dates on the report; Set Axis Type to Scalar, Set Interval to 1 -Jump Labels section Set disable auto-fit set label rotation angle as you desire.

These would help.

Environment Variable with Maven

I suggest using the amazing tool direnv. With it you can inject environment variables once you cd into the project. These steps worked for me:

.envrc file

source_up
dotenv

.env file

_JAVA_OPTIONS="-DYourEnvHere=123"

How does cookie based authentication work?

I realize this is years late, but I thought I could expand on Conor's answer and add a little bit more to the discussion.

Can someone give me a step by step description of how cookie based authentication works? I've never done anything involving either authentication or cookies. What does the browser need to do? What does the server need to do? In what order? How do we keep things secure?

Step 1: Client > Signing up

Before anything else, the user has to sign up. The client posts a HTTP request to the server containing his/her username and password.

Step 2: Server > Handling sign up

The server receives this request and hashes the password before storing the username and password in your database. This way, if someone gains access to your database they won't see your users' actual passwords.

Step 3: Client > User login

Now your user logs in. He/she provides their username/password and again, this is posted as a HTTP request to the server.

Step 4: Server > Validating login

The server looks up the username in the database, hashes the supplied login password, and compares it to the previously hashed password in the database. If it doesn't check out, we may deny them access by sending a 401 status code and ending the request.

Step 5: Server > Generating access token

If everything checks out, we're going to create an access token, which uniquely identifies the user's session. Still in the server, we do two things with the access token:

  1. Store it in the database associated with that user
  2. Attach it to a response cookie to be returned to the client. Be sure to set an expiration date/time to limit the user's session

Henceforth, the cookies will be attached to every request (and response) made between the client and server.

Step 6: Client > Making page requests

Back on the client side, we are now logged in. Every time the client makes a request for a page that requires authorization (i.e. they need to be logged in), the server obtains the access token from the cookie and checks it against the one in the database associated with that user. If it checks out, access is granted.

This should get you started. Be sure to clear the cookies upon logout!

Set Background color programmatically

In my case it wasn't changing the color because I was setting the color in my xml resource.

After delete the line that set the color it worked perfectly programmatically

This is an example I did in a RecyclerView

final Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_icon).mutate();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    holder.image.setBackground(drawable);
} else {
    holder.image.setBackgroundDrawable(drawable);
}

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

How to annotate MYSQL autoincrement field with JPA annotations

can you check whether you connected to the correct database. as i was faced same issue, but finally i found that i connected to different database.

identity supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

More Info : http://docs.jboss.org/hibernate/orm/3.5/reference/en/html/mapping.html#mapping-declaration-id

How to change Jquery UI Slider handle

This change only first handle in multihandle slider. In apiDoc you can see:"For example, if you specify values: [ 1, 5, 18 ] and create one custom handle, the plugin will create the other two."

How to add message box with 'OK' button?

@Override
protected Dialog onCreateDialog(int id)
{
    switch(id)
    {
    case 0:
    {               
        return new AlertDialog.Builder(this)
        .setMessage("text here")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {                   
            @Override
            public void onClick(DialogInterface arg0, int arg1) 
            {
                try
                {

                }//end try
                catch(Exception e)
                {
                    Toast.makeText(getBaseContext(),  "", Toast.LENGTH_LONG).show();
                }//end catch
            }//end onClick()
        }).create();                
    }//end case
  }//end switch
    return null;
}//end onCreateDialog

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

Thanks above all of you contributions! however for my case I finally realized that my dependency above "spring-web" was destroyed on my .m2/repository/org/springframework/spring-web, I just deleted the folder and update Maven again. it got fixed.

How to use "/" (directory separator) in both Linux and Windows in Python?

Use:

import os
print os.sep

to see how separator looks on a current OS.
In your code you can use:

import os
path = os.path.join('folder_name', 'file_name')

Where does Android emulator store SQLite database?

The databases are stored as SQLite files in /data/data/PACKAGE/databases/DATABASEFILE where:

You can see (copy from/to filesystem) the database file in the emulator selecting DDMS perspective, in the File Explorer tab.

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Simply use This:

driver.find_elements_by_xpath('//*[text() = "My Button"]')

How to use enums in C++

Sadly, elements of the enum are 'global'. You access them by doing day = Saturday. That means that you cannot have enum A { a, b } ; and enum B { b, a } ; for they are in conflict.

grep a file, but show several surrounding lines?

Use grep

$ grep --help | grep -i context
Context control:
  -B, --before-context=NUM  print NUM lines of leading context
  -A, --after-context=NUM   print NUM lines of trailing context
  -C, --context=NUM         print NUM lines of output context
  -NUM                      same as --context=NUM

How to get current relative directory of your Makefile?

Solution found here : https://sourceforge.net/p/ipt-netflow/bugs-requests-patches/53/

The solution is : $(CURDIR)

You can use it like that :

CUR_DIR = $(CURDIR)

## Start :
start:
    cd $(CUR_DIR)/path_to_folder

Mock a constructor with parameter

The code you posted works for me with the latest version of Mockito and Powermockito. Maybe you haven't prepared A? Try this:

A.java

public class A {
     private final String test;

    public A(String test) {
        this.test = test;
    }

    public String check() {
        return "checked " + this.test;
    }
}

MockA.java

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
    @Test
    public void test_not_mocked() throws Throwable {
        assertThat(new A("random string").check(), equalTo("checked random string"));
    }
    @Test
    public void test_mocked() throws Throwable {
         A a = mock(A.class); 
         when(a.check()).thenReturn("test");
         PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
         assertThat(new A("random string").check(), equalTo("test"));
    }
}

Both tests should pass with mockito 1.9.0, powermockito 1.4.12 and junit 4.8.2

How do I UPDATE from a SELECT in SQL Server?

like this; but you must sure update table and table after from have be same.

UPDATE Table SET col1, col2
FROM table
inner join other_table Table.id = other_table.id
WHERE sql = 'cool'

insert password into database in md5 format?

Darren Davies is partially correct in saying that you should use a salt - there are several issues with his claim that MD5 is insecure.

You've said that you have to insert the password using an Md5 hash, but that doesn't really tell us why. Is it because that's the format used when validatinb the password? Do you have control over the code which validates the password?

The thing about using a salt is that it avoids the problem where 2 users have the same password - they'll also have the same hash - not a desirable outcome. By using a diferent salt for each password then this does not arise (with very large volumes of data there is still a risk of collisions arising from 2 different passwords - but we'll ignore that for now).

So you can aither generate a random value for the salt and store that in the record too, or you could use some of the data you already hold - such as the username:

$query="INSERT INTO ptb_users (id,
        user_id,
        first_name,
        last_name,
        email )
        VALUES('NULL',
        'NULL',
        '".$firstname."',
        '".$lastname."',
        '".$email."',
        MD5('"$user_id.$password."')
        )";

(I am assuming that you've properly escaped all those strings earlier in your code)

Sql Server : How to use an aggregate function like MAX in a WHERE clause

As you've noticed, the WHERE clause doesn't allow you to use aggregates in it. That's what the HAVING clause is for.

HAVING t1.field3=MAX(t1.field3)

How to remove focus around buttons on click

Another possible solution is to add a class using a Javascript listener when the user clicks on the button and then remove that class on focus with another listener. This maintains accessibility (visible tabbing) while also preventing Chrome's quirky behaviour of considering a button focused when clicked.

JS:

$('button').click(function(){
    $(this).addClass('clicked');
});
$('button').focus(function(){
    $(this).removeClass('clicked');
});

CSS:

button:focus {
    outline: 1px dotted #000;
}
button.clicked {
    outline: none;
}

Full example here: https://jsfiddle.net/4bbb37fh/

Java switch statement multiple cases

This is possible with switch enhancements in Java 14. Following is a fairly intuitive example of how the same can be achieved.

switch (month) {
    case 1, 3, 5, 7, 8, 10, 12 -> System.out.println("this month has 31 days");
    case 4, 6, 9 -> System.out.println("this month has 30 days");
    case 2 -> System.out.println("February can have 28 or 29 days");
    default -> System.out.println("invalid month");
}

Exiting out of a FOR loop in a batch file?

Assuming that the OP is invoking a batch file with cmd.exe, to properly break out of a for loop just goto a label;

Change this:

For /L %%f In (1,1,1000000) Do If Not Exist %%f Goto :EOF

To this:

For /L %%f In (1,1,1000000) Do If Not Exist %%f Goto:fileError
.. do something
.. then exit or do somethign else

:fileError
GOTO:EOF

Better still, add some error reporting:

set filename=
For /L %%f In (1,1,1000000) Do(
    set filename=%%f
    If Not Exist %%f set tempGoto:fileError
)
.. do something
.. then exit or do somethign else

:fileError
echo file does not exist '%filename%'
GOTO:EOF

I find this to be a helpful site about lesser known cmd.exe/DOS batch file functions and tricks: https://www.dostips.com/

C++ Array Of Pointers

I would do it something along these lines:

class Foo{
...
};

int main(){
  Foo* arrayOfFoo[100]; //[1]

  arrayOfFoo[0] = new Foo; //[2]
}

[1] This makes an array of 100 pointers to Foo-objects. But no Foo-objects are actually created.

[2] This is one possible way to instantiate an object, and at the same time save a pointer to this object in the first position of your array.

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Use Paulo Freitas suggestion instead.


Until Laravel fixes this, you can run a standard database query after the Schema::create have been run.

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

It worked wonders for me.

How to call a JavaScript function within an HTML body

Just to clarify things, you don't/can't "execute it within the HTML body".

You can modify the contents of the HTML using javascript.

You decide at what point you want the javascript to be executed.

For example, here is the contents of a html file, including javascript, that does what you want.

<html>
  <head>
    <script>
    // The next line document.addEventListener....
    // tells the browser to execute the javascript in the function after
    // the DOMContentLoaded event is complete, i.e. the browser has
    // finished loading the full webpage
    document.addEventListener("DOMContentLoaded", function(event) { 
      var col1 = ["Full time student checking (Age 22 and under) ", "Customers over age 65", "Below  $500.00" ];
      var col2 = ["None", "None", "$8.00"];
      var TheInnerHTML ="";
      for (var j = 0; j < col1.length; j++) {
        TheInnerHTML += "<tr><td>"+col1[j]+"</td><td>"+col2[j]+"</td></tr>";
    }
    document.getElementById("TheBody").innerHTML = TheInnerHTML;});
    </script>
  </head>
  <body>
    <table>
    <thead>
      <tr>
        <th>Balance</th>
        <th>Fee</th>        
      </tr>
    </thead>
    <tbody id="TheBody">
    </tbody>
  </table>
</body>

Enjoy !

Converting 'ArrayList<String> to 'String[]' in Java

List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
  array[i++] = s;
}

How to import js-modules into TypeScript file?

I tested 3 methods to do that...

Method1:

      const FriendCard:any = require('./../pages/FriendCard')

Method2:

      import * as FriendCard from './../pages/FriendCard';

Method3:

if you can find something like this in tsconfig.json:

      { "compilerOptions": { ..., "allowJs": true }

then you can write: import FriendCard from './../pages/FriendCard';

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

How to center align the cells of a UICollectionView?

You can use https://github.com/keighl/KTCenterFlowLayout like this:

KTCenterFlowLayout *layout = [[KTCenterFlowLayout alloc] init];

[self.collectionView setCollectionViewLayout:layout];

How to get to Model or Viewbag Variables in a Script Tag

try this method

<script type="text/javascript">

    function set(value) {
        return value;
    }

    alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
    alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));

</script>

Thanks

Comparing two strings in C?

You are currently comparing the addresses of the two strings.

Use strcmp to compare the values of two char arrays

 if (strcmp(namet2, nameIt2) != 0)

Maven compile with multiple src directories

This can be done in two steps:

  • For each source directory you should create own module.
  • In all modules you should specify the same build directory: ${build.directory}

If you work with started Jetty (jetty:run), then recompilation of any class in any module (with Maven, IDEA or Eclipse) will lead to Jetty's restart. The same behavior you'll get for modified resources.

How to list files and folder in a dir (PHP)

//path to directory to scan
$directory = "../data/team/";

//get all text files with a .txt extension.
$texts = glob($directory . "*.txt");

//print each file name
foreach($texts as $text)
{
    echo $text;
}

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

Finding the layers and layer sizes for each Docker image

They have a very good answer here: https://stackoverflow.com/a/32455275/165865

Just run below images:

docker run --rm -v /var/run/docker.sock:/var/run/docker.sock nate/dockviz images -t

How to get error message when ifstream open fails

Following on @Arne Mertz's answer, as of C++11 std::ios_base::failure inherits from system_error (see http://www.cplusplus.com/reference/ios/ios_base/failure/), which contains both the error code and message that strerror(errno) would return.

std::ifstream f;

// Set exceptions to be thrown on failure
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);

try {
    f.open(fileName);
} catch (std::system_error& e) {
    std::cerr << e.code().message() << std::endl;
}

This prints No such file or directory. if fileName doesn't exist.

Backup/Restore a dockerized PostgreSQL database

dksnap (https://github.com/kelda/dksnap) automates the process of running pg_dumpall and loading the dump via /docker-entrypoint-initdb.d.

It shows you a list of running containers, and you pick which one you want to backup. The resulting artifact is a regular Docker image, so you can then docker run it, or share it by pushing it to a Docker registry.

(disclaimer: I'm a maintainer on the project)

window.location.href not working

Please check you are using // not \\ by-mistake , like below

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"

Are there any Java method ordering conventions?

  1. Class (static) variables: First the public class variables, then the protected, and then the private.

  2. Instance variables: First public, then protected, and then private.

  3. Constructors

  4. Methods: These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.

Source: http://www.oracle.com/technetwork/java/codeconventions-141855.html

What is the difference between map and flatMap and a good use case for each?

If you are asking the difference between RDD.map and RDD.flatMap in Spark, map transforms an RDD of size N to another one of size N . eg.

myRDD.map(x => x*2)

for example, if myRDD is composed of Doubles .

While flatMap can transform the RDD into anther one of a different size: eg.:

myRDD.flatMap(x =>new Seq(2*x,3*x))

which will return an RDD of size 2*N or

myRDD.flatMap(x =>if x<10 new Seq(2*x,3*x) else new Seq(x) )

How can I echo a newline in a batch file?

When echoing something to redirect to a file, multiple echo commands will not work. I think maybe the ">>" redirector is a good choice:

echo hello > temp
echo world >> temp

How can I run MongoDB as a Windows service?

Consider using

mongod --install --rest --master

getOutputStream() has already been called for this response

JSP is s presentation framework, and is generally not supposed to contain any program logic in it. As skaffman suggested, use pure servlets, or any MVC web framework in order to achieve what you want.

Searching for UUIDs in text with regex

For bash:

grep -E "[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}"

For example:

$> echo "f2575e6a-9bce-49e7-ae7c-bff6b555bda4" | grep -E "[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}"
f2575e6a-9bce-49e7-ae7c-bff6b555bda4

Bootstrap 4 navbar color

I got it. This is very simple. Using the class bg you can achieve this easily.

Let me show you:

<nav class="navbar navbar-expand-lg navbar-dark navbar-full bg-primary"></nav>

This gives you the default blue navbar

If you want to change your favorite color, then simply use the style tag within the nav:

<nav class="navbar navbar-expand-lg navbar-dark navbar-full" style="background-color: #FF0000">

How to debug in Django, the good way?

One of your best option to debug Django code is via wdb: https://github.com/Kozea/wdb

wdb works with python 2 (2.6, 2.7), python 3 (3.2, 3.3, 3.4, 3.5) and pypy. Even better, it is possible to debug a python 2 program with a wdb server running on python 3 and vice-versa or debug a program running on a computer with a debugging server running on another computer inside a web page on a third computer! Even betterer, it is now possible to pause a currently running python process/thread using code injection from the web interface. (This requires gdb and ptrace enabled) In other words it's a very enhanced version of pdb directly in your browser with nice features.

Install and run the server, and in your code add:

import wdb
wdb.set_trace()

According to the author, main differences with respect to pdb are:

For those who don’t know the project, wdb is a python debugger like pdb, but with a slick web front-end and a lot of additional features, such as:

  • Source syntax highlighting
  • Visual breakpoints
  • Interactive code completion using jedi
  • Persistent breakpoints
  • Deep objects inspection using mouse Multithreading / Multiprocessing support
  • Remote debugging
  • Watch expressions
  • In debugger code edition
  • Popular web servers integration to break on error
  • In exception breaking during trace (not post-mortem) in contrary to the werkzeug debugger for instance
  • Breaking in currently running programs through code injection (on supported systems)

It has a great browser-based user interface. A joy to use! :)

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

The problem is in this method:

  public static byte[] encrypt(String toEncrypt) throws Exception{

This is the method signature which pretty much says:

  • what the method name is: encrypt
  • what parameter it receives: a String named toEncrypt
  • its access modifier: public static
  • and if it may or not throw an exception when invoked.

In this case the method signature says that when invoked this method "could" potentially throw an exception of type "Exception".

    ....
    concatURL = padString(concatURL, ' ', 16);
    byte[] encrypted = encrypt(concatURL); <-- HERE!!!!!
    String encryptedString = bytesToHex(encrypted);
    content.removeAll();
    ......

So the compilers is saying: Either you surround that with a try/catch construct or you declare the method ( where is being used ) to throw "Exception" it self.

The real problem is the "encrypt" method definition. No method should ever return "Exception", because it is too generic and may hide some other kinds of exception better is to have an specific exception.

Try this:

public static byte[] encrypt(String toEncrypt) {
    try{
      String plaintext = toEncrypt;
      String key = "01234567890abcde";
      String iv = "fedcba9876543210";

      SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
      IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

      Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
      byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());

      return encrypted;
    } catch ( NoSuchAlgorithmException nsae ) { 
        // What can you do if the algorithm doesn't exists??
        // this usually won't happen because you would test 
        // your code before shipping. 
        // So in this case is ok to transform to another kind 
        throw new IllegalStateException( nsae );
    } catch ( NoSuchPaddingException nspe ) { 
       // What can you do when there is no such padding ( whatever that means ) ??
       // I guess not much, in either case you won't be able to encrypt the given string
        throw new IllegalStateException( nsae );
    }
    // line 109 won't say it needs a return anymore.
  }

Basically in this particular case you should make sure the cryptography package is available in the system.

Java needs an extension for the cryptography package, so, the exceptions are declared as "checked" exceptions. For you to handle when they are not present.

In this small program you cannot do anything if the cryptography package is not available, so you check that at "development" time. If those exceptions are thrown when your program is running is because you did something wrong in "development" thus a RuntimeException subclass is more appropriate.

The last line don't need a return statement anymore, in the first version you were catching the exception and doing nothing with it, that's wrong.

try { 
    // risky code ... 
} catch( Exception e ) { 
    // a bomb has just exploited
    // you should NOT ignore it 
} 

// The code continues here, but what should it do???

If the code is to fail, it is better to Fail fast

Here are some related answers:

Can I do Android Programming in C++, C?

You should look at MoSync too, MoSync gives you standard C/C++, easy-to-use well-documented APIs, and a full-featured Eclipse-based IDE. Its now a open sourced IDE still pretty cool but not maintained anymore.

What is an optional value in Swift?

From https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html:

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

To understand deeper, read the link above.

How to position two elements side by side using CSS

For your iframe give an outer div with style display:inline-block, And for your paragraph div also give display:inline-block

HTML

<div class="side">
    <iframe></iframe>
</div>
<div class="side">
    <p></p>
</div>

CSS

.side {
   display:inline-block;
}

Is it possible to use JavaScript to change the meta-tags of the page?

have this in index

<link rel="opengraph" href="{http://yourPage.com/subdomain.php}"/>

have this in ajaxfiles og:type"og:title"og:description and og: image

and add this also

<link rel="origin" href={http://yourPage.com}/>

then add in js after the ajaxCall

FB.XFBML.parse();

Edit: You can then display the correct title and image to facebook in txt/php douments(mine are just named .php as extensions, but are more txt files). I then have the meta tags in these files, and the link back to index in every document, also a meta link in the index file for every subfile..

if anyone knows a better way of doing this I would appreciate any additions :)

Print string to text file

If you are using numpy, printing a single (or multiply) strings to a file can be done with just one line:

numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...

@Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)

This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...

model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;

May not be the best way, but it does work.

Change a Nullable column to NOT NULL with Default Value

If its SQL Server you can do it on the column properties within design view

Try this?:

ALTER TABLE dbo.TableName 
  ADD CONSTRAINT DF_TableName_ColumnName
    DEFAULT '01/01/2000' FOR ColumnName

Error: "Could Not Find Installable ISAM"

Just use Jet OLEDB: in your connection string. it solved for me.

an example is below:

"Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=E:\Database.mdb;Jet OLEDB:Database Password=b10w"

Easiest way to detect Internet connection on iOS?

I did a little more research and I am updating my answer with a more current solution. I am not sure if you have already looked at it but there is a nice sample code provided by Apple.

Download the sample code here

Include the Reachability.h and Reachability.m files in your project. Take a look at ReachabilityAppDelegate.m to see an example on how to determine host reachability, reachability by WiFi, by WWAN etc. For a very simply check of network reachability, you can do something like this

Reachability *networkReachability = [Reachability reachabilityForInternetConnection];   
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];    
if (networkStatus == NotReachable) {        
    NSLog(@"There IS NO internet connection");        
} else {        
     NSLog(@"There IS internet connection");        
}

@BenjaminPiette's: Don't forget to add SystemConfiguration.framework to your project.

Binding arrow keys in JS/jQuery

You can check wether an arrow key is pressed by:

$(document).keydown(function(e){
    if (e.keyCode > 36 && e.keyCode < 41) { 
       alert( "arrowkey pressed" );
       return false;
    }
});

Dynamically creating keys in a JavaScript associative array

All modern browsers support a Map, which is a key/value data structure. There are a couple of reasons that make using a Map better than Object:

  • An Object has a prototype, so there are default keys in the map.
  • The keys of an Object are strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to keep track of size for an Object.

Example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

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

Shortcuts that worked for me in Versions Oxygen.2 Release (PHP/WINDOWS 7) were

  1. Collapse all code blocks: CTRL + SHIFT + NUMPAD_DIVIDE
  2. Expand all code blocks : CTRL + NUMPAD_MULTIPLY

A completely free agile software process tool

Trello.com Trello is free for unlimited users. Period.

You almost definitely don't need "Sub-cards". Use the checklists instead, or if you REALLY need sub-cards, don't have a parent sub-card. Just name the tickets something like "Epic - Story A" or "Story - task Z" or whatever.

Another idea is to create two boards (did I mention you can have unlimited boards for free too?). One for your epics and one for your stories. Call one your product management board and the other your sprint board, or whatever you like.

I'm not sure what you need different roles for - but, people aren't crazy - they know their job. As a startup if you already have problems getting people to not do crazy things (Where you need to restrict their permissions) you have much much bigger issues.

The point is that you need a SMALL tool to help you track stuff. Not a super rigid tool that makes you work in a super specific way. As a new (I assume?) startup, you should let your process grow into a tool. Don't beef up your process to fit a tool.

android set button background programmatically

Using setBackgroundColor() affects the style. So, declare a new style of the same properties with respect to the previous button, with a a different color.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/green"/>
<corners android:radius="10dp"/>
</shape>

Now, use OnClick method.

location.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            location.setBackgroundResource(R.drawable.green);

        }
    });

this changes the button but looks similar to changing the background.

Python Key Error=0 - Can't find Dict error in code

The error you're getting is that self.adj doesn't already have a key 0. You're trying to append to a list that doesn't exist yet.

Consider using a defaultdict instead, replacing this line (in __init__):

self.adj = {}

with this:

self.adj = defaultdict(list)

You'll need to import at the top:

from collections import defaultdict

Now rather than raise a KeyError, self.adj[0].append(edge) will create a list automatically to append to.

How to change the status bar color in Android?

One more solution:

final View decorView = w.getDecorView();
View view = new View(BaseControllerActivity.this);
final int statusBarHeight = UiUtil.getStatusBarHeight(ContextHolder.get());
view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight));
view.setBackgroundColor(colorValue);
((ViewGroup)decorView).addView(view);

CSS rotate property in IE

Usefull Link for IE transform

This tool converts CSS3 Transform properties (which almost all modern browsers use) to the equivalent CSS using Microsoft's proprietary Visual Filters technology.

Android webview & localStorage

setDatabasePath() method was deprecated in API level 19. I advise you to use storage locale like this:

webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
}

Explain the "setUp" and "tearDown" Python methods used in test cases

Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.

setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites

How and when to use ‘async’ and ‘await’

On a higher level:

1) Async keyword enables the await and that's all it does. Async keyword does not run the method in a separate thread. The beginning f async method runs synchronously until it hits await on a time-consuming task.

2) You can await on a method that returns Task or Task of type T. You cannot await on async void method.

3) The moment main thread encounters await on time-consuming task or when the actual work is started, the main thread returns to the caller of the current method.

4) If the main thread sees await on a task that is still executing, it doesn't wait for it and returns to the caller of the current method. In this way, the application remains responsive.

5) Await on processing task, will now execute on a separate thread from the thread pool.

6) When this await task is completed, all the code below it will be executed by the separate thread

Below is the sample code. Execute it and check the thread id

using System;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncAwaitDemo
{
    class Program
    {
        public static async void AsynchronousOperation()
        {
            Console.WriteLine("Inside AsynchronousOperation Before AsyncMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
            //Task<int> _task = AsyncMethod();
            int count = await AsyncMethod();

            Console.WriteLine("Inside AsynchronousOperation After AsyncMethod Before Await, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            //int count = await _task;

            Console.WriteLine("Inside AsynchronousOperation After AsyncMethod After Await Before DependentMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            DependentMethod(count);

            Console.WriteLine("Inside AsynchronousOperation After AsyncMethod After Await After DependentMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
        }

        public static async Task<int> AsyncMethod()
        {
            Console.WriteLine("Inside AsyncMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
            int count = 0;

            await Task.Run(() =>
            {
                Console.WriteLine("Executing a long running task which takes 10 seconds to complete, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(20000);
                count = 10;
            });

            Console.WriteLine("Completed AsyncMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            return count;
        }       

        public static void DependentMethod(int count)
        {
            Console.WriteLine("Inside DependentMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId + ". Total count is " + count);
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Started Main method, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            AsynchronousOperation();

            Console.WriteLine("Completed Main method, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            Console.ReadKey();
        }

    }
}

Animate a custom Dialog

For right to left (entry animation) and left to right (exit animation):

styles.xml:

<style name="CustomDialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowAnimationStyle">@style/CustomDialogAnimation</item>
</style>

<style name="CustomDialogAnimation">
    <item name="android:windowEnterAnimation">@anim/translate_left_side</item>
    <item name="android:windowExitAnimation">@anim/translate_right_side</item>
</style>

Create two files in res/anim/:

translate_right_side.xml:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%" android:toXDelta="100%"
    android:fromYDelta="0%" android:toYDelta="0%"
    android:duration="600"/>

translate_left_side.xml:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="600"
    android:fromXDelta="100%"
    android:toXDelta="0%"/>

In you Fragment/Activity:

Dialog dialog = new Dialog(getActivity(), R.style.CustomDialog);

What are the options for storing hierarchical data in a relational database?

Adjacency Model + Nested Sets Model

I went for it because I could insert new items to the tree easily (you just need a branch's id to insert a new item to it) and also query it quite fast.

+-------------+----------------------+--------+-----+-----+
| category_id | name                 | parent | lft | rgt |
+-------------+----------------------+--------+-----+-----+
|           1 | ELECTRONICS          |   NULL |   1 |  20 |
|           2 | TELEVISIONS          |      1 |   2 |   9 |
|           3 | TUBE                 |      2 |   3 |   4 |
|           4 | LCD                  |      2 |   5 |   6 |
|           5 | PLASMA               |      2 |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |      1 |  10 |  19 |
|           7 | MP3 PLAYERS          |      6 |  11 |  14 |
|           8 | FLASH                |      7 |  12 |  13 |
|           9 | CD PLAYERS           |      6 |  15 |  16 |
|          10 | 2 WAY RADIOS         |      6 |  17 |  18 |
+-------------+----------------------+--------+-----+-----+
  • Every time you need all children of any parent you just query the parent column.
  • If you needed all descendants of any parent you query for items which have their lft between lft and rgt of parent.
  • If you needed all parents of any node up to the root of the tree, you query for items having lft lower than the node's lft and rgt bigger than the node's rgt and sort the by parent.

I needed to make accessing and querying the tree faster than inserts, that's why I chose this

The only problem is to fix the left and right columns when inserting new items. well I created a stored procedure for it and called it every time I inserted a new item which was rare in my case but it is really fast. I got the idea from the Joe Celko's book, and the stored procedure and how I came up with it is explained here in DBA SE https://dba.stackexchange.com/q/89051/41481

How to determine whether code is running in DEBUG / RELEASE build?

Apple already includes a DEBUG flag in debug builds, so you don't need to define your own.

You might also want to consider just redefining NSLog to a null operation when not in DEBUG mode, that way your code will be more portable and you can just use regular NSLog statements:

//put this in prefix.pch

#ifndef DEBUG
#undef NSLog
#define NSLog(args, ...)
#endif

How add spaces between Slick carousel item

Yup, I have found the solution for dis issue.

  • Create one slider box with extra width from both side( Which we can use to add item space from both sides ).
  • Create Inner Item Content with proper width & margin from both sides( This should be your actual wrapper size )
  • Done

How to add http:// if it doesn't exist in the URL

A modified version of @nickf code:

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

Recognizes ftp://, ftps://, http:// and https:// in a case insensitive way.

Python Matplotlib figure title overlaps axes label when using twiny

A temporary solution if you don't want to get into the x, y position of your title.

Following worked for me.

plt.title('Capital Expenditure\n') # Add a next line after your title

kudos.

Setting up connection string in ASP.NET to SQL SERVER

in header

using System.Configuration;

in code

SqlConnection conn = new SqlConnection(*ConfigurationManager.ConnectionStrings["connstrname"].ConnectionString*);

Basic Python client socket example

You might be confusing compilation from execution. Python has no compilation step! :) As soon as you type python myprogram.py the program runs and, in your case, tries to connect to an open port 5000, giving an error if no server program is listening there. It sounds like you are familiar with two-step languages, that require compilation to produce an executable — and thus you are confusing Python's runtime compilaint that “I can't find anyone listening on port 5000!” with a compile-time error. But, in fact, your Python code is fine; you just need to bring up a listener before running it!

Showing Difference between two datetime values in hours

you may also want to look at

var hours = (datevalue1 - datevalue2).TotalHours;

Can I use return value of INSERT...RETURNING in another INSERT?

table_ex

id default nextval('table_id_seq'::regclass),

camp1 varchar

camp2 varchar

INSERT INTO table_ex(camp1,camp2) VALUES ('xxx','123') RETURNING id 

Timeout on a function call

There are a lot of suggestions, but none using concurrent.futures, which I think is the most legible way to handle this.

from concurrent.futures import ProcessPoolExecutor

# Warning: this does not terminate function if timeout
def timeout_five(fnc, *args, **kwargs):
    with ProcessPoolExecutor() as p:
        f = p.submit(fnc, *args, **kwargs)
        return f.result(timeout=5)

Super simple to read and maintain.

We make a pool, submit a single process and then wait up to 5 seconds before raising a TimeoutError that you could catch and handle however you needed.

Native to python 3.2+ and backported to 2.7 (pip install futures).

Switching between threads and processes is as simple as replacing ProcessPoolExecutor with ThreadPoolExecutor.

If you want to terminate the Process on timeout I would suggest looking into Pebble.

How can I change the thickness of my <hr> tag

For consistency remove any borders and use the height for the <hr> thickness. Adding a background color will style your <hr> with the height and color specified.

In your stylesheet:

hr {
    border: none;
    height: 1px;
    /* Set the hr color */
    color: #333; /* old IE */
    background-color: #333; /* Modern Browsers */
}

Or inline as you have it:

<hr style="height:1px;border:none;color:#333;background-color:#333;" />

Longer explanation here

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

I had the similar issue, then I found out that wifi was not connected in my smartphone. After I turned on the wifi and connected to the similar network (with my laptop), there was another issue - laptop's firewall was blocking incoming connections. Once I fixed the firewall, I was able to communicate from my android app with the web service running on the laptop.

Converting Columns into rows with their respective data in sql server

select 'ScriptName', scriptName from table
union all
select 'ScriptCode', scriptCode from table
union all
select 'Price', price from table

How to add external fonts to android application

I recommend this approach it very nice with adding name of custom font in typeface to styles.xml and putting your set of fonts into assets folder.

Php $_POST method to get textarea value

Try this:

<?php /* the php */ ?>
<?php 
    if ($_POST['submit']) {
        // must work
        echo $_POST['contact_list'];
    };
?>


 <?php /* and the html */ ?>

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>teszt</title>
    </head>
    <body>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
            <textarea id="contact_list" name="contact_list"></textarea>
            <input type="submit" name="submit" value="Send" id="submit"/>
        </form>
    </body>
</html>

bootstrap 3 tabs not working properly

Use this for your code

<ul class="nav nav-tabs" style="margin-top:10em;">
  <li class="active" data-toggle="tab"><a href="#">Assign</a></li>
<li data-toggle="tab"><a href="#">Two</a></li>
<li data-toggle="tab"><a href="#">Three</a></li>

How to add Options Menu to Fragment in Android

TL;DR

Use the android.support.v7.widget.Toolbar and just do:

toolbar.inflateMenu(R.menu.my_menu)
toolbar.setOnMenuItemClickListener {
    onOptionsItemSelected(it)
}

Standalone Toolbar

Most of the suggested solutions like setHasOptionsMenu(true) are only working when the parent Activity has the Toolbar in its layout and declares it via setSupportActionBar(). Then the Fragments can participate in the menu population of this exact ActionBar:

Fragment.onCreateOptionsMenu(): Initialize the contents of the Fragment host's standard options menu.

If you want a standalone toolbar and menu for one specific Fragment you can to do the following:

menu_custom_fragment.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/menu_save"
        android:title="SAVE" />
</menu>

custom_fragment.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    ...

CustomFragment.kt

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater.inflate(layout.custom_fragment, container, false)
    val toolbar = view.findViewById<Toolbar>(R.id.toolbar)
    toolbar.inflateMenu(R.menu.menu_custom_fragment)
    toolbar.setOnMenuItemClickListener {
        onOptionsItemSelected(it)
    }
    return view
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        R.id.menu_save -> {
            // TODO: User clicked the save button
            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

Yes, it's that easy. You don't even need to override onCreate() or onCreateOptionsMenu().

PS: This is only working with android.support.v4.app.Fragment and android.support.v7.widget.Toolbar (also be sure to use AppCompatActivity and an AppCompat theme in your styles.xml).

How to compile python script to binary executable

# -*- mode: python -*-

block_cipher = None

a = Analysis(['SCRIPT.py'],
             pathex=[
                 'folder path',
                 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_50c6cb8431e7428f',
                 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_c4f50889467f081d'
             ],
             binaries=[(''C:\\Users\\chromedriver.exe'')],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='NAME OF YOUR EXE',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

Convert regular Python string to raw string

raw strings apply only to string literals. they exist so that you can more conveniently express strings that would be modified by escape sequence processing. This is most especially useful when writing out regular expressions, or other forms of code in string literals. if you want a unicode string without escape processing, just prefix it with ur, like ur'somestring'.

How to get a list of sub-folders and their files, ordered by folder-names

How about using sort?

dir /b /s | sort

Here's an example I tested with:


dir /s /b /o:gn

d:\root0
d:\root0\root1
d:\root0\root1\folderA
d:\root0\root1\folderB
d:\root0\root1\file00.txt
d:\root0\root1\file01.txt
d:\root0\root1\folderA\fileA00.txt
d:\root0\root1\folderA\fileA01.txt
d:\root0\root1\folderB\fileB00.txt
d:\root0\root1\folderB\fileB01.txt

dir /s /b | sort

d:\root0
d:\root0\root1
d:\root0\root1\file00.txt
d:\root0\root1\file01.txt
d:\root0\root1\folderA
d:\root0\root1\folderA\fileA00.txt
d:\root0\root1\folderA\fileA01.txt
d:\root0\root1\folderB
d:\root0\root1\folderB\fileB00.txt
d:\root0\root1\folderB\fileB01.txt

To just get directories, use the /A:D parameter:

dir /a:d /s /b | sort

How to check for DLL dependency?

  1. There is a program called "Depends"
  2. If you have cygwin installed, nothing simpler then ldd file.exe

Remove innerHTML from div

divToUpdate.innerHTML =     "";   

MySQL: How to copy rows, but change a few fields?

As long as Event_ID is Integer, do this:

INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, (Event_ID + 155)
  FROM Table
WHERE Event_ID = "120"

Updating a java map entry

Use

table.put(key, val);

to add a new key/value pair or overwrite an existing key's value.

From the Javadocs:

V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

PHP: Read Specific Line From File

You have to loop the file till end of file.

  while(!feof($file))
  {
     echo fgets($file). "<br />";
  }
  fclose($file);

IIS7: Setup Integrated Windows Authentication like in IIS6

There's another thread elsewhere on Stack with a similar topic and the best solution I've come across is to use the free version of Helicon Ape

Once you've got that installed, follow the steps at the page Titled "HTTP Authentication and Authorization"

How to import JsonConvert in C# application?

JsonConvert is from the namespace Newtonsoft.Json, not System.ServiceModel.Web

Use NuGet to download the package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

scp files from local to remote machine error: no such file or directory

You also need to make sure what is in the .bashrc file of the user.

I've also got this ridiculous error because I put cd and ls commands in there, as it was mean to let them see the current files & directories when the user is has logged in from ssh.

Simple and fast method to compare images for similarity

Can the screenshot or icon be transformed (scaled, rotated, skewed ...)? There are quite a few methods on top of my head that could possibly help you:

  • Simple euclidean distance as mentioned by @carlosdc (doesn't work with transformed images and you need a threshold).
  • (Normalized) Cross Correlation - a simple metrics which you can use for comparison of image areas. It's more robust than the simple euclidean distance but doesn't work on transformed images and you will again need a threshold.
  • Histogram comparison - if you use normalized histograms, this method works well and is not affected by affine transforms. The problem is determining the correct threshold. It is also very sensitive to color changes (brightness, contrast etc.). You can combine it with the previous two.
  • Detectors of salient points/areas - such as MSER (Maximally Stable Extremal Regions), SURF or SIFT. These are very robust algorithms and they might be too complicated for your simple task. Good thing is that you do not have to have an exact area with only one icon, these detectors are powerful enough to find the right match. A nice evaluation of these methods is in this paper: Local invariant feature detectors: a survey.

Most of these are already implemented in OpenCV - see for example the cvMatchTemplate method (uses histogram matching): http://dasl.mem.drexel.edu/~noahKuntz/openCVTut6.html. The salient point/area detectors are also available - see OpenCV Feature Detection.

Custom domain for GitHub project pages

If you are wondering how to get your domain to appear as www.mydomain.com instead of redirecting the www request to mydomain.com, try this:

CNAME file on gh-pages branch will have one line:

www.mydomain.com (instead of mydomain.com)

No matter your preference on redirection (in other words, no matter what is in your CNAME file on the gs-pages branch), with your DNS provider, you should set it up like this:

A      @    192.30.252.154
A      @    192.30.252.153
CNAME  www  username.github.io

Error 1022 - Can't write; duplicate key in table

I had this problem when creating a new table. It turns out the Foreign Key name I gave was already in use. Renaming the key fixed it.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

Factory method: You have a factory that creates objects that derive from a particular base class

Abstract factory: You have a factory that creates other factories, and these factories in turn create objects derived from base classes. You do this because you often don't just want to create a single object (as with Factory method) - rather, you want to create a collection of related objects.

Difference between $(document.body) and $('body')

There should be no difference at all maybe the first is a little more performant but i think it's trivial ( you shouldn't worry about this, really ).

With both you wrap the <body> tag in a jQuery object

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

Hiding the address bar of a browser (popup)

In the Edge browser as of build 20.10240.16384.0 you can hide the address bar by setting location=no in the window.open features.

How to find the largest file in a directory and its subdirectories?

find . -type f | xargs ls -lS | head -n 1

outputs

-rw-r--r--  1 nneonneo  staff  9274991 Apr 11 02:29 ./devel/misc/test.out

If you just want the filename:

find . -type f | xargs ls -1S | head -n 1

This avoids using awk and allows you to use whatever flags you want in ls.

Caveat. Because xargs tries to avoid building overlong command lines, this might fail if you run it on a directory with a lot of files because ls ends up executing more than once. It's not an insurmountable problem (you can collect the head -n 1 output from each ls invocation, and run ls -S again, looping until you have a single file), but it does mar this approach somewhat.

Why does intellisense and code suggestion stop working when Visual Studio is open?

What worked for me is by disabling and then re-enabling the Resharper

Goto
Tools -> Options-> Resharper ->General

Click
Suspend -> This disables the resharper

Then check your Intellisense is working or not. In my case, it did and then I resumed the Resharper.

If this does not work, you might need to Goto
Resharper -> Options-> Environment -> Intellisense -> General

And
Change Intellisense to Visual Studio

batch to copy files with xcopy

Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)

xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J

Python Pandas: Get index of rows which column matches certain value

First you may check query when the target column is type bool (PS: about how to use it please check link )

df.query('BoolCol')
Out[123]: 
    BoolCol
10     True
40     True
50     True

After we filter the original df by the Boolean column we can pick the index .

df=df.query('BoolCol')
df.index
Out[125]: Int64Index([10, 40, 50], dtype='int64')

Also pandas have nonzero, we just select the position of True row and using it slice the DataFrame or index

df.index[df.BoolCol.nonzero()[0]]
Out[128]: Int64Index([10, 40, 50], dtype='int64')

High CPU Utilization in java application - why?

You may be victim of a garbage collection problem.

When your application requires memory and it's getting low on what it's configured to use the garbage collector will run often which consume a lot of CPU cycles. If it can't collect anything your memory will stay low so it will be run again and again. When you redeploy your application the memory is cleared and the garbage collection won't happen more than required so the CPU utilization stays low until it's full again.

You should check that there is no possible memory leak in your application and that it's well configured for memory (check the -Xmx parameter, see What does Java option -Xmx stand for?)

Also, what are you using as web framework? JSF relies a lot on sessions and consumes a lot of memory, consider being stateless at most!

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

I'm using eclipse neon 3. I just wanted to use javafx.application.Application, so I followed Christian Hujer's answer above and it worked. Just some tips: the access rules are very similar to the import statement. For me, the access rules I added was "javafx/application/**". Just replace the dot in the import statement with forward slash and that's the rule. Hope that helps.

how to assign a block of html code to a javascript variable

 var test = "<div class='saved' >"+
 "<div >test.test</div> <div class='remove'>[Remove]</div></div>";

You can add "\n" if you require line-break.

iOS 7 status bar overlapping UI

Here is my approach using CSS and Javascript:

1) Define the following in your CSS:

#ios7-statusbar-fix {
    width:100%;
    height:20px;
    background-color:white;
    position:fixed;
    z-index:10000;
    margin-top:-20px;
    display:none;
}

2) Add div-container with this id as very first element after your <body>-tag:

<body>
    <div id="ios7-statusbar-fix"></div>
…

3) Filter iOS 7 devices and apply changes via Javascript:

if (navigator.userAgent.match(/(iPad.*|iPhone.*|iPod.*);.*CPU.*OS 7_\d/i)) {
        document.body.style.marginTop = '20px';
        document.getElementById('ios7-statusbar-fix').style.display = 'block';
}

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

The DLL you're looking for that contains that namespace is

Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll

Note that unit testing cannot be used in Visual Studio Express.

Split files using tar, gz, zip, or bzip2

If you are splitting from Linux, you can still reassemble in Windows.

copy /b file1 + file2 + file3 + file4 filetogether

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

Python Variable Declaration

Variables have scope, so yes it is appropriate to have variables that are specific to your function. You don't always have to be explicit about their definition; usually you can just use them. Only if you want to do something specific to the type of the variable, like append for a list, do you need to define them before you start using them. Typical example of this.

list = []
for i in stuff:
  list.append(i)

By the way, this is not really a good way to setup the list. It would be better to say:

list = [i for i in stuff] # list comprehension

...but I digress.

Your other question. The custom object should be a class itself.

class CustomObject(): # always capitalize the class name...this is not syntax, just style.
  pass
customObj = CustomObject()

How to define the css :hover state in a jQuery selector?

I would suggest to use CSS over jquery ( if possible) otherwise you can use something like this

$("div.myclass").hover(function() {
  $(this).css("background-color","red")
});

You can change your selector as per your need.

As commented by @A.Wolff, If you want to use this hover effect to multiple classes, you can use it like this

$(".myclass, .myclass2").hover(function(e) { 
    $(this).css("background-color",e.type === "mouseenter"?"red":"transparent") 
})

Js Fiddle Demo

How do I prevent the padding property from changing width or height in CSS?

when I add the padding-left property, the width of the DIV changes to 220px

Yes, that is exactly according to the standards. That's how it's supposed to work.

Let's say I create another DIV named anotherdiv exactly the same as newdiv, and put it inside of newdiv but newdiv has no padding and anotherdiv has padding-left: 20px. I get the same thing, newdiv's width will be 220px;

No, newdiv will remain 200px wide.

API pagination best practices

I'm not completely sure how your data is handled, so this may or may not work, but have you considered paginating with a timestamp field?

When you query /foos you get 100 results. Your API should then return something like this (assuming JSON, but if it needs XML the same principles can be followed):

{
    "data" : [
        {  data item 1 with all relevant fields    },
        {  data item 2   },
        ...
        {  data item 100 }
    ],
    "paging":  {
        "previous":  "http://api.example.com/foo?since=TIMESTAMP1" 
        "next":  "http://api.example.com/foo?since=TIMESTAMP2"
    }

}

Just a note, only using one timestamp relies on an implicit 'limit' in your results. You may want to add an explicit limit or also use an until property.

The timestamp can be dynamically determined using the last data item in the list. This seems to be more or less how Facebook paginates in its Graph API (scroll down to the bottom to see the pagination links in the format I gave above).

One problem may be if you add a data item, but based on your description it sounds like they would be added to the end (if not, let me know and I'll see if I can improve on this).

HTTP Status 404 - The requested resource (/) is not available

For me, my Eclipse installation was hosed - I think because I'd installed struts. After trying a dozen remedies for this error, I re-installed Eclipse, made a new workspace and it was OK. Using Kepler-64-Windows, Tomcat 7, Windows 7.

Convert generic list to dataset in C#

I apologize for putting an answer up to this question, but I figured it would be the easiest way to view my final code. It includes fixes for nullable types and null values :-)

    public static DataSet ToDataSet<T>(this IList<T> list)
    {
        Type elementType = typeof(T);
        DataSet ds = new DataSet();
        DataTable t = new DataTable();
        ds.Tables.Add(t);

        //add a column to table for each public property on T
        foreach (var propInfo in elementType.GetProperties())
        {
            Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

            t.Columns.Add(propInfo.Name, ColType);
        }

        //go through each property on T and add each value to the table
        foreach (T item in list)
        {
            DataRow row = t.NewRow();

            foreach (var propInfo in elementType.GetProperties())
            {
                row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
            }

            t.Rows.Add(row);
        }

        return ds;
    }

How to find the minimum value in an ArrayList, along with the index number? (Java)

You have to traverse the whole array and keep two auxiliary values:

  • The minimum value you find (on your way towards the end)
  • The index of the place where you found the min value

Suppose your array is called myArray. At the end of this code minIndex has the index of the smallest value.

var min = Number.MAX_VALUE; //the largest number possible in JavaScript
var minIndex = -1;

for (int i=0; i<myArray.length; i++){
   if (myArray[i] < min){
      min = myArray[i];
      minIndex = i;
   }
}

This is assuming the worst case scenario: a totally random array. It is an O(n) algorithm or order n algorithm, meaning that if you have n elements in your array, then you have to look at all of them before knowing your answer. O(n) algorithms are the worst ones because they take a lot of time to solve the problem.

If your array is sorted or has any other specific structure, then the algorithm can be optimized to be faster.

Having said that, though, unless you have a huge array of thousands of values then don't worry about optimization since the difference between an O(n) algorithm and a faster one would not be noticeable.

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

In my case was a ?> at the end of the routes.php. Spent a lot of time there...

Why does Google prepend while(1); to their JSON responses?

That would be to make it difficult for a third-party to insert the JSON response into an HTML document with the <script> tag. Remember that the <script> tag is exempt from the Same Origin Policy.

stopPropagation vs. stopImmediatePropagation

A small example to demonstrate how both these propagation stoppages work.

_x000D_
_x000D_
var state = {_x000D_
  stopPropagation: false,_x000D_
  stopImmediatePropagation: false_x000D_
};_x000D_
_x000D_
function handlePropagation(event) {_x000D_
  if (state.stopPropagation) {_x000D_
    event.stopPropagation();_x000D_
  }_x000D_
_x000D_
  if (state.stopImmediatePropagation) {_x000D_
    event.stopImmediatePropagation();_x000D_
  }_x000D_
}_x000D_
_x000D_
$("#child").click(function(e) {_x000D_
  handlePropagation(e);_x000D_
  console.log("First event handler on #child");_x000D_
});_x000D_
_x000D_
_x000D_
$("#child").click(function(e) {_x000D_
  handlePropagation(e);_x000D_
  console.log("Second event handler on #child");_x000D_
});_x000D_
_x000D_
// First this event will fire on the child element, then propogate up and_x000D_
// fire for the parent element._x000D_
$("div").click(function(e) {_x000D_
  handlePropagation(e);_x000D_
  console.log("Event handler on div: #" + this.id);_x000D_
});_x000D_
_x000D_
_x000D_
// Enable/disable propogation_x000D_
$("button").click(function() {_x000D_
  var objectId = this.id;_x000D_
  $(this).toggleClass('active');_x000D_
  state[objectId] = $(this).hasClass('active');_x000D_
  console.log('---------------------');_x000D_
});
_x000D_
div {_x000D_
  padding: 1em;_x000D_
}_x000D_
_x000D_
#parent {_x000D_
  background-color: #CCC;_x000D_
}_x000D_
_x000D_
#child {_x000D_
  background-color: #000;_x000D_
  padding: 5em;_x000D_
}_x000D_
_x000D_
button {_x000D_
  padding: 1em;_x000D_
  font-size: 1em;_x000D_
}_x000D_
_x000D_
.active {_x000D_
  background-color: green;_x000D_
  color: white;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="parent">_x000D_
  <div id="child">&nbsp;</div>_x000D_
</div>_x000D_
_x000D_
<button id="stopPropagation">Stop Propogation</button>_x000D_
<button id="stopImmediatePropagation" ">Stop Immediate Propogation</button>
_x000D_
_x000D_
_x000D_

There are three event handlers bound. If we don’t stop any propagation, then there should be four alerts - three on the child div, and one on the parent div.

If we stop the event from propagating, then there will be 3 alerts (all on the inner child div). Since the event won’t propagate up the DOM hierarchy, the parent div won’t see it, and its handler won’t fire.

If we stop propagation immediately, then there will only be 1 alert. Even though there are three event handlers attached to the inner child div, only 1 is executed and any further propagation is killed immediately, even within the same element.

Checking Date format from a string in C#

you can use DateTime.ParseExact with the format string

DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);

Above will throw an exception if the given string not in given format.

use DateTime.TryParseExact if you don't need exception in case of format incorrect but you can check the return value of that method to identify whether parsing value success or not.

check Custom Date and Time Format Strings

How to split the filename from a full path in batch?

@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%

shift a std_logic_vector of n bit to right or left

There are two ways that you can achieve this. Concatenation, and shift/rotate functions.

  • Concatenation is the "manual" way of doing things. You specify what part of the original signal that you want to "keep" and then concatenate on data to one end or the other. For example: tmp <= tmp(14 downto 0) & '0';

  • Shift functions (logical, arithmetic): These are generic functions that allow you to shift or rotate a vector in many ways. The functions are: sll (shift left logical), srl (shift right logical). A logical shift inserts zeros. Arithmetric shifts (sra/sla) insert the left most or right most bit, but work in the same way as logical shift. Note that for all of these operations you specify what you want to shift (tmp), and how many times you want to perform the shift (n bits)

  • Rotate functions: rol (rotate left), ror (rotate right). Rotating does just that, the MSB ends up in the LSB and everything shifts left (rol) or the other way around for ror.

Here is a handy reference I found (see the first page).

new Runnable() but no new thread?

If you want to create a new Thread...you can do something like this...

Thread t = new Thread(new Runnable() { public void run() { 
  // your code goes here... 
}});