Programs & Examples On #Jython

Jython is an open-source implementation of the Python programming language in Java.

Calling Python in Java?

It's not smart to have python code inside java. Wrap your python code with flask or other web framework to make it as a microservice. Make your java program able to call this microservice (e.g. via REST).

Beleive me, this is much simple and will save you tons of issues. And the codes are loosely coupled so they are scalable.

Updated on Mar 24th 2020: According to @stx's comment, the above approach is not suitable for massive data transfer between client and server. Here is another approach I recommended: Connecting Python and Java with Rust(C/C++ also ok). https://medium.com/@shmulikamar/https-medium-com-shmulikamar-connecting-python-and-java-with-rust-11c256a1dfb0

Is there a way to run Python on Android?

You can use QPython:

It has a Python Console, Editor, as well as Package Management / Installers

http://qpython.com/

It's an open source project with both Python 2 and Python 3 implementations. You can download the source and the Android .apk files directly from github.

QPython 2: https://github.com/qpython-android/qpython/releases

QPython 3: https://github.com/qpython-android/qpython3/releases

Automated Python to Java translation

to clarify your question:

From Python Source code to Java source code? (I don't think so)

.. or from Python source code to Java Bytecode? (Jython does this under the hood)

Want to download a Git repository, what do I need (windows machine)?

Install mysysgit. (Same as Greg Hewgill's answer.)

Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)

After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.

This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

"HTTP 415 Unsupported Media Type response" stems from Content-Type in header of your request. for example in javascript by axios:

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/json'},
            url: '/',
            data: data,  // an object u want to send
          }).then(function (response) {
            console.log(response);
          });

Change line width of lines in matplotlib pyplot legend

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

Method 1

import numpy as np
import matplotlib.pyplot as plt

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

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

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

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

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

Method 2

import numpy as np
import matplotlib.pyplot as plt

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

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

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

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

The above two methods produce the same output image:

output image

DOUBLE vs DECIMAL in MySQL

From your comments,

the tax amount rounded to the 4th decimal and the total price rounded to the 2nd decimal.

Using the example in the comments, I might foresee a case where you have 400 sales of $1.47. Sales-before-tax would be $588.00, and sales-after-tax would sum to $636.51 (accounting for $48.51 in taxes). However, the sales tax of $0.121275 * 400 would be $48.52.

This was one way, albeit contrived, to force a penny's difference.

I would note that there are payroll tax forms from the IRS where they do not care if an error is below a certain amount (if memory serves, $0.50).

Your big question is: does anybody care if certain reports are off by a penny? If the your specs say: yes, be accurate to the penny, then you should go through the effort to convert to DECIMAL.

I have worked at a bank where a one-penny error was reported as a software defect. I tried (in vain) to cite the software specifications, which did not require this degree of precision for this application. (It was performing many chained multiplications.) I also pointed to the user acceptance test. (The software was verified and accepted.)

Alas, sometimes you just have to make the conversion. But I would encourage you to A) make sure that it's important to someone and then B) write tests to show that your reports are accurate to the degree specified.

Access multiple viewchildren using @viewchild

Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"

@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;

Doing something with each child looks like: this.customComponentChildren.forEach((child) => { child.stuff = 'y' })

There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild

Javascript Array of Functions

Or just:

var myFuncs = {
  firstFun: function(string) {
    // do something
  },

  secondFunc: function(string) {
    // do something
  },

  thirdFunc: function(string) {
    // do something
  }
}

Git Stash vs Shelve in IntelliJ IDEA

git shelve doesn't exist in Git.

Only git stash:

  • when you want to record the current state of the working directory and the index, but want to go back to a clean working directory.
  • which saves your local modifications away and reverts the working directory to match the HEAD commit.

You had a 2008 old project git shelve to isolate modifications in a branch, but that wouldn't be very useful nowadays.

As documented in Intellij IDEA shelve dialog, the feature "shelving and unshelving" is not linked to a VCS (Version Control System tool) but to the IDE itself, to temporarily storing pending changes you have not committed yet in changelist.

Note that since Git 2.13 (Q2 2017), you now can stash individual files too.

Unable to create migrations after upgrading to ASP.NET Core 2.0

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
    }
}

Just rename BuildWebHost() to CreateWebHostBuilder(), because migrations use this method by default.

How to remove "Server name" items from history of SQL Server Management Studio

Rather than deleting or renaming this file:

  1. Close SQL Server Management Studio.
  2. Find the appropriate file (see the other posts).
  3. Open the .bin in a text/hex editior like NotePad++.
  4. Search for the name of one of the servers and identify the line number.
  5. Make a copy of the .bin/.dat file.
  6. Delete that line. Make sure you delete the entire line, it's possible if you have many the line could wrap.
  7. Open SQL Server Management Studio. Your dropdown will be blank.

Git fast forward VS no fast forward merge

It is possible also that one may want to have personalized feature branches where code is just placed at the end of day. That permits to track development in finer detail.

I would not want to pollute master development with non-working code, thus doing --no-ff may just be what one is looking for.

As a side note, it may not be necessary to commit working code on a personalized branch, since history can be rewritten git rebase -i and forced on the server as long as nobody else is working on that same branch.

Shuffling a list of objects

from random import random
my_list = range(10)
shuffled_list = sorted(my_list, key=lambda x: random())

This alternative may be useful for some applications where you want to swap the ordering function.

Eloquent ->first() if ->exists()

(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:

$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();

Oh, also: count() instead if exists but this could be something used after get.

Run exe file with parameters in a batch file

This should work:

start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2

The start command interprets the first argument as a window title if it contains spaces. In this case, that means start considers your whole argument a title and sees no command. Passing "" (an empty title) as the first argument to start fixes the problem.

how to run a command at terminal from java program?

As others said, you may run your external program without xterm. However, if you want to run it in a terminal window, e.g. to let the user interact with it, xterm allows you to specify the program to run as parameter.

xterm -e any command

In Java code this becomes:

String[] command = { "xterm", "-e", "my", "command", "with", "parameters" };
Runtime.getRuntime().exec(command);

Or, using ProcessBuilder:

String[] command = { "xterm", "-e", "my", "command", "with", "parameters" };
Process proc = new ProcessBuilder(command).start();

Sum all values in every column of a data.frame in R

We can use dplyr to select only numeric columns and purr to get sum for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )

library("dplyr")
library("purrr")

people %>%
    select_if(is.numeric) %>%
    map_dbl(sum)

Or another easy way by only using dplyr

library("dplyr")
people %>%
    summarize_if(is.numeric, sum, na.rm=TRUE)

TypeError: worker() takes 0 positional arguments but 1 was given

another use case for this error is when you import functions within the class definition. this makes the subsequent function calls a part of the class object. In this case you can use @staticmethod on the library import function or make a static path call directly to the function. see example below

In this example "self.bar()" will throw a TypeError, but it can be fixed in two ways

# in lib.py
def bar():
  print('something to do')

# in foo.py
class foo():
  from .lib import bar

  def __init__(self):
    self.bar()

Option 1:

# in lib.py
def bar():
  print('something to do')

# in foo.py
class foo():
  from .lib import bar

  def __init__(self):
    lib.bar()

Option 2:

# in lib.py:
@staticmethod
def bar():
  print('something to do')

# in foo.py
class foo():
  from .lib import bar

  def __init__(self):
    self.bar()

nodemon command is not recognized in terminal for node js server

You need to install it globally

npm install -g nodemon
# or if using yarn
yarn global add nodemon

And then it will be available on the path (I see now that you have tried this and it didn't work, your path may be messed up)

If you want to use the locally installed version, rather than installing globally then you can create a script in your package.json

"scripts": {
    "serve": "nodemon server.js"
  },

and then use

npm run serve

optionally if using yarn

# without adding serve in package.json
yarn run nodemon server.js
# with serve script in package.json
yarn run serve

npm will then look in your local node_modules folder before looking for the command in your global modules

T-SQL split string

Personnaly I use this function :

ALTER FUNCTION [dbo].[CUST_SplitString]
(
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
)
RETURNS TABLE 
AS
RETURN 
(
    WITH Split(stpos,endpos) 
    AS(
        SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1) 
        FROM Split
        WHERE endpos > 0
    )
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
        'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
    FROM Split
)

How to split a string between letters and digits (or between digits and letters)?

I was doing this sort of thing for mission critical code. Like every fraction of a second counts because I need to process 180k entries in an unnoticeable amount of time. So I skipped the regex and split altogether and allowed for inline processing of each element (though adding them to an ArrayList<String> would be fine). If you want to do this exact thing but need it to be something like 20x faster...

void parseGroups(String text) {
    int last = 0;
    int state = 0;
    for (int i = 0, s = text.length(); i < s; i++) {
        switch (text.charAt(i)) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                if (state == 2) {
                    processElement(text.substring(last, i));
                    last = i;
                }
                state = 1;
                break;
            default:
                if (state == 1) {
                    processElement(text.substring(last, i));
                    last = i;
                }
                state = 2;
                break;
        }
    }
    processElement(text.substring(last));
}

XPath to select element based on childs child value

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

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

to either

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

or

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

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

Angular2 set value for formGroup

"NgModel doesn't work with new forms api".

That's not true. You just need to use it correctly. If you are using the reactive forms, the NgModel should be used in concert with the reactive directive. See the example in the source.

/*
 * @Component({
 *      selector: "login-comp",
 *      directives: [REACTIVE_FORM_DIRECTIVES],
 *      template: `
 *        <form [formGroup]="myForm" (submit)='onLogIn()'>
 *          Login <input type='text' formControlName='login' [(ngModel)]="credentials.login">
 *          Password <input type='password' formControlName='password'
 *                          [(ngModel)]="credentials.password">
 *          <button type='submit'>Log in!</button>
 *        </form>
 *      `})
 * class LoginComp {
 *  credentials: {login:string, password:string};
 *  myForm = new FormGroup({
 *    login: new Control(this.credentials.login),
 *    password: new Control(this.credentials.password)
 *  });
 *
 *  onLogIn(): void {
 *    // this.credentials.login === "some login"
 *    // this.credentials.password === "some password"
 *  }
 * }
 */

Though it looks like from the TODO comments, this will likely be removed and replaced with a reactive API.

// TODO(kara):  Replace ngModel with reactive API
@Input('ngModel') model: any;

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

$.ajax( type: "POST" POST method to php

Check whether title has any value or not. If not, then retrive the value using Id.

<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
    var title=jQuery('#title').val();
    $.ajax({
      type: "POST",
      url: "edit.php",
      data: {title:title} ,
      success: function(data) {
    $('.center').html(data); 
}
});
}
</script>

Try this code.

In php code, use echo instead of return. Only then, javascript data will have its value.

Run "mvn clean install" in Eclipse

If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.

You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?

I'm quoting the steps here:

Step 1: Setup a new External Configuration Tool

In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.

Step 2: Click New Launch Configuration option in Create, manage and run configuration screen

Step 3: New Configuration screen for configuring the command prompt

Step 4: Provide configuration details of the Command Prompt in the Main tab

Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt

Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.

Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory

IP to Location using Javascript

You can use this google service free IP geolocation webservice

update

the link is broken, I put here other link that include @NickSweeting in the comments:

ip-api.com

and you can get the data in json format:

http://ip-api.com/docs/api:json

Angular 4/5/6 Global Variables

I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)

Installing PG gem on OS X - failure to build native extension

Same error for me and I didn't experience it until I downloaded OS X 10.9 (Mavericks). Sigh, another OS upgrade headache.

Here's how I fixed it (with homebrew):

  • Install another build of Xcode Tools (typing brew update in the terminal will prompt you to update the Xcode build tools)
  • brew update
  • brew install postgresql

After that gem install pg worked for me.

How do I specify the exit code of a console application in .NET?

As an update to Scott Munro's answer:

  • In C# 6.0 and VB.NET 14.0 (VS 2015), either Environment.ExitCode or Environment.Exit(exitCode) is required to return an non-zero code from a console application. Changing the return type of Main has no effect.
  • In F# 4.0 (VS 2015), the return value of the main entry point is respected.

Making an API call in Python with an API that requires a bearer token

Here is full example of implementation in cURL and in Python - for authorization and for making API calls

cURL

1. Authorization

You have received access data like this:

Username: johndoe

Password: zznAQOoWyj8uuAgq

Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa

Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga

Which you can call in cURL like this:

curl -k -d "grant_type=password&username=Username&password=Password" \

                    -H "Authorization: Basic Base64(consumer-key:consumer-secret)" \

                       https://somedomain.test.com/token

or for this case it would be:

curl -k -d "grant_type=password&username=johndoe&password=zznAQOoWyj8uuAgq" \

                    -H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \

                      https://somedomain.test.com/token

Answer would be something like:

{
    "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
    "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
    "scope": "default",
    "token_type": "Bearer",
    "expires_in": 3600
}

2. Calling API

Here is how you call some API that uses authentication from above. Limit and offset are just examples of 2 parameters that API could implement. You need access_token from above inserted after "Bearer ".So here is how you call some API with authentication data from above:

curl -k -X GET "https://somedomain.test.com/api/Users/Year/2020/Workers?offset=1&limit=100" -H "accept: application/json" -H "Authorization: Bearer zz8d62zz-56zz-34zz-9zzf-azze1b8057f8"

Python

Same thing from above implemented in Python. I've put text in comments so code could be copy-pasted.

# Authorization data

import base64
import requests

username = 'johndoe'
password= 'zznAQOoWyj8uuAgq'
consumer_key = 'ggczWttBWlTjXCEtk3Yie_WJGEIa'
consumer_secret = 'uuzPjjJykiuuLfHkfgSdXLV98Ciga'
consumer_key_secret = consumer_key+":"+consumer_secret
consumer_key_secret_enc = base64.b64encode(consumer_key_secret.encode()).decode()

# Your decoded key will be something like:
#zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh


headersAuth = {
    'Authorization': 'Basic '+ str(consumer_key_secret_enc),
}

data = {
  'grant_type': 'password',
  'username': username,
  'password': password
}

## Authentication request

response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
j = response.json()

# When you print that response you will get dictionary like this:

    {
        "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
        "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
        "scope": "default",
        "token_type": "Bearer",
        "expires_in": 3600
    }

# You have to use `access_token` in API calls explained bellow.
# You can get `access_token` with j['access_token'].


# Using authentication to make API calls   

## Define header for making API calls that will hold authentication data

headersAPI = {
    'accept': 'application/json',
    'Authorization': 'Bearer '+j['access_token'],
}

### Usage of parameters defined in your API
params = (
    ('offset', '0'),
    ('limit', '20'),
)

# Making sample API call with authentication and API parameters data

response = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, params=params, verify=True)
api_response = response.json()

Putting images with options in a dropdown list

This code will work only in Firefox:

<select>
    <option value="volvo" style="background-image:url(images/volvo.png);">Volvo</option>
    <option value="saab"  style="background-image:url(images/saab.png);">Saab</option>
    <option value="honda" style="background-image:url(images/honda.png);">Honda</option>
    <option value="audi"  style="background-image:url(images/audi.png);">Audi</option>
</select>

Edit (April 2018):

Firefox does not support this anymore.

Adding options to a <select> using jQuery?

There are two ways. You can use either of these two.

First:

$('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');

Second:

$.each(dataCollecton, function(val, text) {            
    options.append($('<option></option>').val(text.route).html(text.route));
});

SQLite table constraint - unique on multiple columns

Be careful how you define the table for you will get different results on insert. Consider the following



CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
INSERT INTO t1 (a, b) VALUES
    ('Alice', 'Some title'),
    ('Bob', 'Palindromic guy'),
    ('Charles', 'chucky cheese'),
    ('Alice', 'Some other title') 
    ON CONFLICT(a) DO UPDATE SET b=excluded.b;
CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
INSERT INTO t2 (a, b) VALUES
    ('Alice', 'Some title'),
    ('Bob', 'Palindromic guy'),
    ('Charles', 'chucky cheese'),
    ('Alice', 'Some other title');

$ sqlite3 test.sqlite
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
sqlite> INSERT INTO t1 (a, b) VALUES
   ...>     ('Alice', 'Some title'),
   ...>     ('Bob', 'Palindromic guy'),
   ...>     ('Charles', 'chucky cheese'),
   ...>     ('Alice', 'Some other title') 
   ...>     ON CONFLICT(a) DO UPDATE SET b=excluded.b;
sqlite> CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
sqlite> INSERT INTO t2 (a, b) VALUES
   ...>     ('Alice', 'Some title'),
   ...>     ('Bob', 'Palindromic guy'),
   ...>     ('Charles', 'chucky cheese'),
   ...>     ('Alice', 'Some other title');
sqlite> .mode col
sqlite> .headers on
sqlite> select * from t1;
id          a           b               
----------  ----------  ----------------
1           Alice       Some other title
2           Bob         Palindromic guy 
3           Charles     chucky cheese   
sqlite> select * from t2;
id          a           b              
----------  ----------  ---------------
2           Bob         Palindromic guy
3           Charles     chucky cheese  
4           Alice       Some other titl
sqlite> 

While the insert/update effect is the same, the id changes based on the table definition type (see the second table where 'Alice' now has id = 4; the first table is doing more of what I expect it to do, keep the PRIMARY KEY the same). Be aware of this effect.

How can I scale an image in a CSS sprite

try using background size: http://webdesign.about.com/od/styleproperties/p/blspbgsize.htm

is there something stopping you from rendering the images at the size you want them in the first place?

Adding a newline character within a cell (CSV)

On Excel for Mac 2011, the newline had to be a \r instead of an \n

So

"\"first line\rsecond line\""

would show up as a cell with 2 lines

SQL query to get most recent row for each instance of a given key

I've been using this because I'm returning results from another table. Though I'm trying to avoid the nested join if it helps w/ one less step. Oh well. It returns the same thing.

select
users.userid
, lastIP.IP
, lastIP.maxdate

from users

inner join (
    select userid, IP, datetime
    from IPAddresses
    inner join (
        select userid, max(datetime) as maxdate
        from IPAddresses
        group by userid
        ) maxIP on IPAddresses.datetime = maxIP.maxdate and IPAddresses.userid = maxIP.userid
    ) as lastIP on users.userid = lastIP.userid

How can I commit files with git?

This happens when you do not include a message when you try to commit using:

git commit

It launches an editor environment. Quit it by typing :q! and hitting enter.

It's going to take you back to the terminal without committing, so make sure to try again, this time pass in a message:

git commit -m 'Initial commit'

null terminating a string

Be very careful: NULL is a macro used mainly for pointers. The standard way of terminating a string is:

char *buffer;
...
buffer[end_position] = '\0';

This (below) works also but it is not a big difference between assigning an integer value to a int/short/long array and assigning a character value. This is why the first version is preferred and personally I like it better.

buffer[end_position] = 0; 

How do I properly 'printf' an integer and a string in C?

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

Let's talk through the changes:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

Call an activity method from a fragment

I have tried with all the methods shown in this thread and none worked for me, try this one. It worked for me.

((MainActivity) getContext().getApplicationContext()).Method();

PowerShell script to return members of multiple security groups

Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv

I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard. I did pre-load AD into PowerShell before hand:

Get-Module -ListAvailable | Import-Module

Pass parameter to controller from @Html.ActionLink MVC 4

You are using a wrong overload of the Html.ActionLink helper. What you think is routeValues is actually htmlAttributes! Just look at the generated HTML, you will see that this anchor's href property doesn't look as you expect it to look.

Here's what you are using:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // routeValues
    new {                                                     // htmlAttributes
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    }
)

and here's what you should use:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // controllerName
    new {                                                     // routeValues
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    },
    null                                                      // htmlAttributes
)

Also there's another very serious issue with your code. The following routeValue:

replyblogPostmodel = Model

You cannot possibly pass complex objects like this in an ActionLink. So get rid of it and also remove the BlogPostModel parameter from your controller action. You should use the blogPostId parameter to retrieve the model from wherever this model is persisted, or if you prefer from wherever you retrieved the model in the GET action:

public ActionResult BlogReplyCommentAdd(int blogPostId, bool captchaValid)
{
    BlogPostModel model = repository.Get(blogPostId);
    ...
}

As far as your initial problem is concerned with the wrong overload I would recommend you writing your helpers using named parameters:

@Html.ActionLink(
    linkText: "Reply",
    actionName: "BlogReplyCommentAdd",
    controllerName: "Blog",
    routeValues: new {
        blogPostId = blogPostId, 
        captchaValid = Model.AddNewComment.DisplayCaptcha
    },
    htmlAttributes: null
)

Now not only that your code is more readable but you will never have confusion between the gazillions of overloads that Microsoft made for those helpers.

Ways to iterate over a list in Java

For a backward search you should use the following:

for (ListIterator<SomeClass> iterator = list.listIterator(list.size()); iterator.hasPrevious();) {
    SomeClass item = iterator.previous();
    ...
    item.remove(); // For instance.
}

If you want to know a position, use iterator.previousIndex(). It also helps to write an inner loop that compares two positions in the list (iterators are not equal).

Concat all strings inside a List<string> using LINQ

String.Join(delimiter, list);

is sufficient.

convert an enum to another type of enum

Using an extension method works quite neatly, when using the two conversion methods suggested by Nate:

public static class TheirGenderExtensions
{
    public static MyGender ToMyGender(this TheirGender value)
    {
        // insert switch statement here
    }
}

public static class MyGenderExtensions
{
    public static TheirGender ToTheirGender(this MyGender value)
    {
        // insert switch statement here
    }
}

Obviously there's no need to use separate classes if you don't want to. My preference is to keep extension methods grouped by the classes/structures/enumerations they apply to.

Adding a regression line on a ggplot

If you want to fit other type of models, like a dose-response curve using logistic models you would also need to create more data points with the function predict if you want to have a smoother regression line:

fit: your fit of a logistic regression curve

#Create a range of doses:
mm <- data.frame(DOSE = seq(0, max(data$DOSE), length.out = 100))
#Create a new data frame for ggplot using predict and your range of new 
#doses:
fit.ggplot=data.frame(y=predict(fit, newdata=mm),x=mm$DOSE)

ggplot(data=data,aes(x=log10(DOSE),y=log(viability)))+geom_point()+
geom_line(data=fit.ggplot,aes(x=log10(x),y=log(y)))

Generating a SHA-256 hash from the Linux command line

I believe that echo outputs a trailing newline. Try using -n as a parameter to echo to skip the newline.

Bootstrap Navbar toggle button not working

Your code looks great, the only thing i see is that you did not include the collapsed class in your button selector. http://www.bootply.com/cpHugxg2f8 Note: Requires JavaScript plugin If JavaScript is disabled and the viewport is narrow enough that the navbar collapses, it will be impossible to expand the navbar and view the content within the .navbar-collapse.

The responsive navbar requires the collapse plugin to be included in your version of Bootstrap.

<div class="navbar-wrapper">
      <div class="container">

        <nav class="navbar navbar-inverse navbar-static-top">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Project name</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
              <ul class="nav navbar-nav">
                    <li><a href="">Page 1</a>
                    </li>
                    <li><a href="">Page 2</a>
                    </li>
                    <li><a href="">Page 3</a>
                    </li>

              </ul>
            </div>
          </div>
        </nav>

      </div>
    </div>

PHP array printing using a loop

Another advanced method is called an ArrayIterator. It’s part of a wider class that exposes many accessible variables and functions. You are more likely to see this as part of PHP classes and heavily object-oriented projects.

$fnames = ["Muhammed", "Ali", "Fatimah", "Hasan", "Hussein"];

$arrObject = new ArrayObject($fnames);
$arrayIterator = $arrObject->getIterator();

while( $arrayIterator->valid() ){
echo $arrayIterator->current() . "<br />";
$arrayIterator->next();
}

Renaming Column Names in Pandas Groupby function

The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename method. See this deprecation note in the documentation for more detail.

Deprecated Answer as of pandas version 0.20

This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg method.

These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.

Before we get there, let's create a four column DataFrame.

df = pd.DataFrame({'A' : list('wwwwxxxx'), 
                   'B':list('yyzzyyzz'), 
                   'C':np.random.rand(8), 
                   'D':np.random.rand(8)})

   A  B         C         D
0  w  y  0.643784  0.828486
1  w  y  0.308682  0.994078
2  w  z  0.518000  0.725663
3  w  z  0.486656  0.259547
4  x  y  0.089913  0.238452
5  x  y  0.688177  0.753107
6  x  z  0.955035  0.462677
7  x  z  0.892066  0.368850

Let's say we want to group by columns A, B and aggregate column C with mean and median and aggregate column D with max. The following code would do this.

df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})

            D         C          
          max      mean    median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:

df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'}, 
                            'D':{'D_max': 'max'}})

            D         C          
        D_max    C_mean  C_median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0).

How do you get the length of a string?

It's not jquery you need, it's JS:

alert(str.length);

how to show calendar on text box click in html

What you need is a jQuery UI Datepicker

Check out the demo and the source code.

What is the difference between cache and persist?

Cache() and persist() both the methods are used to improve performance of spark computation. These methods help to save intermediate results so they can be reused in subsequent stages.

The only difference between cache() and persist() is ,using Cache technique we can save intermediate results in memory only when needed while in Persist() we can save the intermediate results in 5 storage levels(MEMORY_ONLY, MEMORY_AND_DISK, MEMORY_ONLY_SER, MEMORY_AND_DISK_SER, DISK_ONLY).

Google Geocoding API - REQUEST_DENIED

I got this problem as well using the drupal 7 Location module. Autofilling all empty locations resulted in this error. Executing one of the requests to the location api manually resulted in this error in the returned JSON:

"Browser API keys cannot have referer restrictions when used with this API."

Resolving the problem then was easy: create a new key without any restrictions and use it only for Geocoding.

Note for those new to google api keys: by restrictions they mean limiting requests using an api key to specific domains / subdomains. (eg. only request from http://yourdomain.com are allowed).

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

It means that one of the dependent dlls is compiled with a different run-time library.

Project -> Properties -> C/C++ -> Code Generation -> Runtime Library

Go over all the libraries and see that they are compiled in the same way.

More about this error in this link:

warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs

Inserting HTML elements with JavaScript

Instead of directly messing with innerHTML it might be better to create a fragment and then insert that:

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }
    return frag;
}

var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);

Benefits:

  1. You can use native DOM methods for insertion such as insertBefore, appendChild etc.
  2. You have access to the actual DOM nodes before they're inserted; you can access the fragment's childNodes object.
  3. Using document fragments is very quick; faster than creating elements outside of the DOM and in certain situations faster than innerHTML.

Even though innerHTML is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...

Bootstrap 3 navbar active li not changing background-color

in my case just removing background-image from nav-bar item solved the problem

.navbar-default .navbar-nav > .active > a:focus {
    .
    .
    .


    background-image: none;
}

jQuery Mobile - back button

This is for version 1.4.4

  <div data-role="header" >
        <h1>CHANGE HOUSE ANIMATION</h1>
        <a href="#" data-rel="back" class="ui-btn-left ui-btn ui-icon-back ui-btn-icon-notext ui-shadow ui-corner-all"  data-role="button" role="button">Back</a>
    </div>

Print array to a file

You can try this, $myArray as the Array

$filename = "mylog.txt";
$text = "";
foreach($myArray as $key => $value)
{
    $text .= $key." : ".$value."\n";
}
$fh = fopen($filename, "w") or die("Could not open log file.");
fwrite($fh, $text) or die("Could not write file!");
fclose($fh);

How can I get the Google cache age of any URL or web page?

Use the URL

https://webcache.googleusercontent.com/search?q=cache:<your url without "http://">

Example:

https://webcache.googleusercontent.com/search?q=cache:stackoverflow.com

It contains a header like this:

This is Google's cache of https://stackoverflow.com/. It is a snapshot of the page as it appeared on 21 Aug 2012 11:33:38 GMT. The current page could have changed in the meantime. Learn more
Tip: To quickly find your search term on this page, press Ctrl+F or ?+F (Mac) and use the find bar.

Good Hash Function for Strings

// djb2 hash function
unsigned long hash(unsigned char *str)
{
    unsigned long hash = 5381;
    int c;

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

source Logic behind djb2 hash function - SO

How do I use brew installed Python as the default Python?

You need to edit your PATH environmental variable to make sure wherever the homebrew python is located is searched before /usr/bin. You could also set things up in your shell config to have a variable like PYTHON be set to your desired version of python and call $PYTHON rather than python from the command line.

Also, as another poster stated (and especially on mac) DO NOT mess with the python in /usr/bin to point it to another python install. You're just asking for trouble if you do.

How to verify CuDNN installation?

Run ./mnistCUDNN in /usr/src/cudnn_samples_v7/mnistCUDNN

Here is an example:

cudnnGetVersion() : 7005 , CUDNN_VERSION from cudnn.h : 7005 (7.0.5)
Host compiler version : GCC 5.4.0
There are 1 CUDA capable devices on your machine :
device 0 : sms 30  Capabilities 6.1, SmClock 1645.0 Mhz, MemSize (Mb) 24446, MemClock 4513.0 Mhz, Ecc=0,    boardGroupID=0
Using device 0

Can RDP clients launch remote applications and not desktops

At least on 2008R2 if the accounts are only used for RDP and not for local logins then you can set this on a per-account basis. That should work for thin clients. If the accounts are also used on local desktops then this would also affect those logins.

In ADUsers&Computers, open the properties for the account and go to the Environment tab. On that tab, check "Start the following program at logon" and specify the path and executable for the program.

How do I create a link using javascript?

With JavaScript

  1. var a = document.createElement('a');
    a.setAttribute('href',desiredLink);
    a.innerHTML = desiredText;
    // apend the anchor to the body
    // of course you can append it almost to any other dom element
    document.getElementsByTagName('body')[0].appendChild(a);
    
  2. document.getElementsByTagName('body')[0].innerHTML += '<a href="'+desiredLink+'">'+desiredText+'</a>';
    

    or, as suggested by @travis :

    document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
    
  3. <script type="text/javascript">
    //note that this case can be used only inside the "body" element
    document.write('<a href="'+desiredLink+'">'+desiredText+'</a>');
    </script>
    

With JQuery

  1. $('<a href="'+desiredLink+'">'+desiredText+'</a>').appendTo($('body'));
    
  2. $('body').append($('<a href="'+desiredLink+'">'+desiredText+'</a>'));
    
  3. var a = $('<a />');
    a.attr('href',desiredLink);
    a.text(desiredText);
    $('body').append(a);
    

In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink is a variable that holds the address that your anchor element points to, and desiredText is a variable that holds the text that will be displayed in the anchor element.

AngularJS - Access to child scope

You can try this:

$scope.child = {} //declare it in parent controller (scope)

then in child controller (scope) add:

var parentScope = $scope.$parent;
parentScope.child = $scope;

Now the parent has access to the child's scope.

How to get back to most recent version in Git?

I am just beginning to dig deeper into git, so not sure if I understand correctly, but I think the correct answer to the OP's question is that you can run git log --all with a format specification like this: git log --all --pretty=format:'%h: %s %d'. This marks the current checked out version as (HEAD) and you can just grab the next one from the list.

BTW, add an alias like this to your .gitconfig with a slightly better format and you can run git hist --all:

  hist = log --pretty=format:\"%h %ai | %s%d [%an]\" --graph

Regarding the relative versions, I found this post, but it only talks about older versions, there is probably nothing to refer to the newer versions.

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

JavaScript .replace only replaces first Match

textTitle.replace(/ /g, '%20');

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

How to vertically center a <span> inside a div?

As in a similar question, use display: inline-block with a placeholder element to vertically center the span inside of a block element:

_x000D_
_x000D_
html, body, #container, #placeholder { height: 100%; }_x000D_
_x000D_
#content, #placeholder { display:inline-block; vertical-align: middle; }
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="container">_x000D_
      <span id="content">_x000D_
        Content_x000D_
      </span>_x000D_
      <span id="placeholder"></span>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Vertical alignment is only applied to inline elements or table cells, so use it along with display:inline-block or display:table-cell with a display:table parent when vertically centering block elements.

References:

CSS Horizontal and Vertical Centering

Allow all remote connections, MySQL

You can disable all security by editing /etc/my.cnf:

[mysqld]
skip-grant-tables

Angular + Material - How to refresh a data source (mat-table)

Best way to do this is by adding an additional observable to your Datasource implementation.

In the connect method you should already be using Observable.merge to subscribe to an array of observables that include the paginator.page, sort.sortChange, etc. You can add a new subject to this and call next on it when you need to cause a refresh.

something like this:

export class LanguageDataSource extends DataSource<any> {

    recordChange$ = new Subject();

    constructor(private languages) {
      super();
    }

    connect(): Observable<any> {

      const changes = [
        this.recordChange$
      ];

      return Observable.merge(...changes)
        .switchMap(() => return Observable.of(this.languages));
    }

    disconnect() {
      // No-op
    }
}

And then you can call recordChange$.next() to initiate a refresh.

Naturally I would wrap the call in a refresh() method and call it off of the datasource instance w/in the component, and other proper techniques.

How to clear a chart from a canvas so that hover events cannot be triggered?

We can update the chart data in Chart.js V2.0 as follows:

var myChart = new Chart(ctx, data);
myChart.config.data = new_data;
myChart.update();

Create a rounded button / button with border-radius in Flutter

Now we have Icon Button to achieve rounded button click and overlay. However background color is not yet available but the same can be achieved by Circle avatar widget as follows:

CircleAvatar(
            backgroundColor: const Color(0xffF4F3FA),
            child: IconButton(
              onPressed: () => FlushbarHelper.createInformation(
                      message: 'Work in progress...')
                  .show(context),
              icon: Icon(Icons.more_vert),
            ),
          ),

Hope this helps some one.

How to Get enum item name from its value

If you know the actual enum labels correlated to their values, you can use containers and C++17's std::string_view to quickly access values and their string representations with the [ ] operator while tracking it yourself. std::string_view will only allocate memory when created. They can also be designated with static constexpr if you want them available at run-time for more performance savings. This little console app should be fairly fast.

#include <iostream>
#include <string_view>
#include <tuple>    
int main() {
    enum class Weekdays { //default behavior starts at 0 and iterates by 1 per entry
        Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
    };

    static constexpr std::string_view Monday    = "Monday";
    static constexpr std::string_view Tuesday   = "Tuesday";
    static constexpr std::string_view Wednesday = "Wednesday";
    static constexpr std::string_view Thursday  = "Thursday";
    static constexpr std::string_view Friday    = "Friday";
    static constexpr std::string_view Saturday  = "Saturday";
    static constexpr std::string_view Sunday    = "Sunday";
    static constexpr std::string_view opener    = "enum[";
    static constexpr std::string_view closer    = "] is ";
    static constexpr std::string_view semi      = ":";

    std::pair<Weekdays, std::string_view> Weekdays_List[] = {
        std::make_pair(Weekdays::Monday,    Monday),
        std::make_pair(Weekdays::Tuesday,   Tuesday),
        std::make_pair(Weekdays::Wednesday, Wednesday),
        std::make_pair(Weekdays::Thursday,  Thursday),
        std::make_pair(Weekdays::Friday,    Friday),
        std::make_pair(Weekdays::Saturday,  Saturday),
        std::make_pair(Weekdays::Sunday,    Sunday)
    };

    for (int i=0;i<sizeof(Weekdays_List)/sizeof(Weekdays_List[0]);i++) {
        std::cout<<opener<<i<<closer<<Weekdays_List[(int)i].second<<semi\
        <<(int)Weekdays_List[(int)i].first<<std::endl;
    }    
    return 0;
}

Output:

enum[0] is Monday:0
enum[1] is Tuesday:1
enum[2] is Wednesday:2
enum[3] is Thursday:3
enum[4] is Friday:4
enum[5] is Saturday:5
enum[6] is Sunday:6

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

You can edit the ~/.gitconfig file in your home folder. This is where all --global settings are saved.

How to fix a Div to top of page with CSS only

Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following

#term-defs {
height: 300px;
overflow: scroll; }

This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.

#top {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 23px;
}

This will fix it to the top, on top of other content with a height of 23px.

The final implementation will depend on what effect you really want.

How to set max_connections in MySQL Programmatically

How to change max_connections

You can change max_connections while MySQL is running via SET:

mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 5000  |
+-----------------+-------+
1 row in set (0.00 sec)

To OP

timeout related

I had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.

I suggest that you increase this value to 100k or disable connection pooling Pooling=false

UPDATED

he has two questions.

Q1 - what happens if I disable pooling Slow down making DB connection. connection pooling is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool

Q2 - Can the value of pooling be increased or the maximum is 100?

you can increase but I'm sure what is MAX value, maybe max_connections in my.cnf

My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.

If you have Stress Test tool like JMeter you can test youself.

DataColumn Name from DataRow (not DataTable)

use DataTable object instead:

 private void doMore(DataTable dt)
    {
    foreach(DataColumn dc in dt.Columns)
    {
    MessageBox.Show(dc.ColumnName);
    }
    }

std::queue iteration

Why not just make a copy of the queue that you want to iterate over, and remove items one at a time, printing them as you go? If you want to do more with the elements as you iterate, then a queue is the wrong data structure.

Removing elements with Array.map in JavaScript

You should use the filter method rather than map unless you want to mutate the items in the array, in addition to filtering.

eg.

var filteredItems = items.filter(function(item)
{
    return ...some condition...;
});

[Edit: Of course you could always do sourceArray.filter(...).map(...) to both filter and mutate]

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

PHP doesn't really get compiled as with many programs. You can use Zend's encoder to make it unreadable though.

npm install doesn't create node_modules directory

For node_modules you have to follow the below steps

1) In Command prompt -> Goto your project directory.

2) Command :npm init

3) It asks you to set up your package.json file

4) Command: npm install or npm update

Android: show/hide status bar/power bar

I know its a very old question, but just in case anyone lands here looking for the newest supported way to hide status bar on the go programmatically, you can do it as follows:

window.insetsController?.hide(WindowInsets.Type.statusBars())

and to show it again:

window.insetsController?.show(WindowInsets.Type.statusBars())

Auto increment in phpmyadmin

@AmitKB, Your procedure is correct. Although this error

Query error: #1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key

can be solved by first marking the field as key(using the key icon with label primary),unless you have other key then it may not work.

Installing Apple's Network Link Conditioner Tool

Update on the answer December 2019 Xcode 11.1.2

Apple has moved Network Link Conditioner Tool to additional tools for Xcode

Go to the below link

https://developer.apple.com/download/more/?q=Additional%20Tools

enter image description here

Install the dmg file, select hardware from installer

enter image description here

select Network Link conditioner prefpane enter image description here

Return row of Data Frame based on value in a column - R

@Zelazny7's answer works, but if you want to keep ties you could do:

df[which(df$Amount == min(df$Amount)), ]

For example with the following data frame:

df <- data.frame(Name = c("A", "B", "C", "D", "E"), 
                 Amount = c(150, 120, 175, 160, 120))

df[which.min(df$Amount), ]
#   Name Amount
# 2    B    120

df[which(df$Amount == min(df$Amount)), ]
#   Name Amount
# 2    B    120
# 5    E    120

Edit: If there are NAs in the Amount column you can do:

df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]

Bootstrap 3: how to make head of dropdown link clickable in navbar

No need of use addition CSS/JS (Tested)

  1. data-toggle="dropdown" - for Clickable (can use Mobile as well web)
  2. data-hover="dropdown" - for Hover (web only, because mobile doesn't have feature HOVER)

Works fine on Mobile as well :)


Code Example for Clickable(data-toggle="dropdown")

_x000D_
_x000D_
/*!
 * this CSS code just  for snippet preview purpose. Please omit when using  it. 
 */

#bs-example-navbar-collapse-1 ul li {
  float: left;
}

#bs-example-navbar-collapse-1 ul li ul li {
  float: none !important;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav">
    <li>
      <a class="" href="">Home</a>
    </li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                subnav1
            </a>
      <ul class="dropdown-menu">
        <li><a href="">Sub1</a></li>
        <li><a href="">Sub2</a></li>
        <li><a href="">Sub3</a></li>
        <li><a href="">Sub4</a></li>
        <li><a href="">Sub5</a></li>
        <li><a href="">Sub6</a></li>
      </ul>
      <div class="clear"></div>
    </li>
    <li class="dropdown">
      <a href="" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">
            subnav2
            </a>
      <ul class="dropdown-menu">
        <li><a href="">Sub1</a></li>
        <li><a href="">Sub2</a></li>
        <li><a href="">Sub3</a></li>
        <li><a href="">Sub4</a></li>
        <li><a href="">Sub5</a></li>
        <li><a href="">Sub6</a></li>
      </ul>
      <div class="clear"></div>
    </li>
  </ul>
</div>

<br>
<br>
<p><b>Please Note:</b> added css code not related to Bootstrap navigation. It's just for snippet preview purpose </p>
_x000D_
_x000D_
_x000D_

Output

output enter image description here

Reference - What does this error mean in PHP?

Fatal error: Undefined class constant

This error means that you have attempted to use a class constant that does not exist. Unlike other "undefined" notices and warnings, this is a fatal error and will stop the script immediately.

The first thing to be checked should be typographic errors. Confirm the constant is defined in the class, and that it is called using the appropriate namespace. Confirm also that all appropriate files have been included to resolve the constant.

Is there a job scheduler library for node.js?

You can use timexe

It's simple to use, light weight, has no dependencies, has an improved syntax over cron, with a resolution in milliseconds and works in the browser.

Install:

npm install timexe

Use:

var timexe = require('timexe');
var res = timexe("* * * 15 30", function(){ console.log("It's now 3:30 pm"); });

(I'm the author)

How to enter a series of numbers automatically in Excel

Use formula =row(b2)-x, where x will adjust the entries so that the first S/No is marked as 1 and will increment with the rows.

Permutations in JavaScript?

function swap(array1, index1, index2) {
    var temp;
    temp = array1[index1];
    array1[index1] = array1[index2];
    array1[index2] = temp;
}

function permute(a, l, r) {
    var i;
    if (l == r) {
        console.log(a.join(''));
    } else {
        for (i = l; i <= r; i++) {
            swap(a, l, i);
            permute(a, l + 1, r);
            swap(a, l, i);
        }
    }
}


permute(["A","B","C", "D"],0,3);

// sample execution //for more details refer this link

// http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/

How to Apply Gradient to background view of iOS Swift App

And if you need to change the direction of the gradient you have to use startPoint and endPoint.

let gradient: CAGradientLayer = CAGradientLayer()

gradient.colors = [UIColor.blue.cgColor, UIColor.red.cgColor]
gradient.locations = [0.0 , 1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height)

self.view.layer.insertSublayer(gradient, at: 0)

How to disassemble a binary executable in Linux to get the assembly code?

You can come pretty damn close (but no cigar) to generating assembly that will reassemble, if that's what you are intending to do, using this rather crude and tediously long pipeline trick (replace /bin/bash with the file you intend to disassemble and bash.S with what you intend to send the output to):

objdump --no-show-raw-insn -Matt,att-mnemonic -Dz /bin/bash | grep -v "file format" | grep -v "(bad)" | sed '1,4d' | cut -d' ' -f2- | cut -d '<' -f2 | tr -d '>' | cut -f2- | sed -e "s/of\ section/#Disassembly\ of\ section/" | grep -v "\.\.\." > bash.S

Note how long this is, however. I really wish there was a better way (or, for that matter, a disassembler capable of outputting code that an assembler will recognize), but unfortunately there isn't.

Loop inside React JSX

Since you are writing Javascript syntax inside JSX code, you need to wrap your Javascript in curly braces.

row = () => {
   var rows = [];
   for (let i = 0; i<numrows; i++) {
       rows.push(<ObjectRow/>);
   }
   return rows;
}
<tbody>
{this.row()}  
</tbody>

ProgressDialog spinning circle

I was using View.INVISIBLE and View.VISIBLE and the ProgressBar would slowly flash instead of constantly being visible, switched to View.GONE and View.VISIBLE and it works perfectly

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

How to store NULL values in datetime fields in MySQL?

I had this problem on windows.

This is the solution:

To pass '' for NULL you should disable STRICT_MODE (which is enabled by default on Windows installations)

BTW It's funny to pass '' for NULL. I don't know why they let this kind of behavior.

Database Structure for Tree Data Structure

If anyone using MS SQL Server 2008 and higher lands on this question: SQL Server 2008 and higher has a new "hierarchyId" feature designed specifically for this task.

More info at https://docs.microsoft.com/en-us/sql/relational-databases/hierarchical-data-sql-server

Failed to load the JNI shared Library (JDK)

I had a similar problem. It was solved doing the following.

  • Move Eclipse to Program Files (not to Program Files (x86)).
  • Remove the path to the 32-bit version of Java from the 'path' environment variable.

I have both versions of Java installed, but Eclipse kept trying to use the 32-bit one.

Combining C++ and C - how does #ifdef __cplusplus work?

  1. extern "C" doesn't change the presence or absence of the __cplusplus macro. It just changes the linkage and name-mangling of the wrapped declarations.

  2. You can nest extern "C" blocks quite happily.

  3. If you compile your .c files as C++ then anything not in an extern "C" block, and without an extern "C" prototype will be treated as a C++ function. If you compile them as C then of course everything will be a C function.

  4. Yes

  5. You can safely mix C and C++ in this way.

How can prepared statements protect from SQL injection attacks?

When you create and send a prepared statement to the DBMS, it's stored as the SQL query for execution.

You later bind your data to the query such that the DBMS uses that data as the query parameters for execution (parameterization). The DBMS doesn't use the data you bind as a supplemental to the already compiled SQL query; it's simply the data.

This means it's fundamentally impossible to perform SQL injection using prepared statements. The very nature of prepared statements and their relationship with the DBMS prevents this.

File Not Found when running PHP with Nginx

In my case, it was because the permissions on the root web directory were not set correctly. To do this, you need to be in the parent folder when you run this in terminal:

sudo chmod -R 755 htmlfoldername

This will chmod all files in your html folder, which is not recommended for production for security reasons, but should let you see the files in that folder, to be sure that isn't the issue while troubleshooting.

How do I find ' % ' with the LIKE operator in SQL Server?

Try this:

declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%' 

You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _

How to export data to an excel file using PHPExcel

Try the below complete example for the same

<?php
  $objPHPExcel = new PHPExcel();
  $query1 = "SELECT * FROM employee";
  $exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
  $serialnumber=0;
  //Set header with temp array
  $tmparray =array("Sr.Number","Employee Login","Employee Name");
  //take new main array and set header array in it.
  $sheet =array($tmparray);

  while ($res1 = mysql_fetch_array($exec1))
  {
    $tmparray =array();
    $serialnumber = $serialnumber + 1;
    array_push($tmparray,$serialnumber);
    $employeelogin = $res1['employeelogin'];
    array_push($tmparray,$employeelogin);
    $employeename = $res1['employeename'];
    array_push($tmparray,$employeename);   
    array_push($sheet,$tmparray);
  }
   header('Content-type: application/vnd.ms-excel');
   header('Content-Disposition: attachment; filename="name.xlsx"');
  $worksheet = $objPHPExcel->getActiveSheet();
  foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
  }

  //make first row bold
  $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
  $objPHPExcel->setActiveSheetIndex(0);
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>

Get HTML source of WebElement in Selenium WebDriver using Python

The method to get the rendered HTML I prefer is the following:

driver.get("http://www.google.com")
body_html = driver.find_element_by_xpath("/html/body")
print body_html.text

However, the above method removes all the tags (yes, the nested tags as well) and returns only text content. If you interested in getting the HTML markup as well, then use the method below.

print body_html.getAttribute("innerHTML")

Sorted array list in Java

Just make a new class like this:

public class SortedList<T> extends ArrayList<T> {

private final Comparator<? super T> comparator;

public SortedList() {
    super();
    this.comparator = null;
}

public SortedList(Comparator<T> comparator) {
    super();
    this.comparator = comparator;
}

@Override
public boolean add(T item) {
    int index = comparator == null ? Collections.binarySearch((List<? extends Comparable<? super T>>)this, item) :
            Collections.binarySearch(this, item, comparator);
    if (index < 0) {
        index = index * -1 - 2;
    }
    super.add(index+1, item);
    return true;
}

@Override
public void add(int index, T item) {
    throw new UnsupportedOperationException("'add' with an index is not supported in SortedArrayList");
}

@Override
public boolean addAll(Collection<? extends T> items) {
    boolean allAdded = true;
    for (T item : items) {
        allAdded = allAdded && add(item);
    }
    return allAdded;
}

@Override
public boolean addAll(int index, Collection<? extends T> items) {
    throw new UnsupportedOperationException("'addAll' with an index is not supported in SortedArrayList");
}

}

You can test it like this:

    List<Integer> list = new SortedArrayList<>((Integer i1, Integer i2) -> i1.compareTo(i2));
    for (Integer i : Arrays.asList(4, 7, 3, 8, 9, 25, 20, 23, 52, 3)) {
        list.add(i);
    }
    System.out.println(list);

How to have multiple conditions for one if statement in python

Might be a bit odd or bad practice but this is one way of going about it.

(arg1, arg2, arg3) = (1, 2, 3)

if (arg1 == 1)*(arg2 == 2)*(arg3 == 3):
    print('Example.')

Anything multiplied by 0 == 0. If any of these conditions fail then it evaluates to false.

LINQ to SQL - How to select specific columns and return strongly typed list

The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.

Thank you all for your help!

How can I force a long string without any blank to be wrapped?

just setting width and adding float worked for me :-)

width:100%;
float:left;

Find the min/max element of an array in JavaScript

This may suit your purposes.

Array.prototype.min = function(comparer) {

    if (this.length === 0) return null;
    if (this.length === 1) return this[0];

    comparer = (comparer || Math.min);

    var v = this[0];
    for (var i = 1; i < this.length; i++) {
        v = comparer(this[i], v);    
    }

    return v;
}

Array.prototype.max = function(comparer) {

    if (this.length === 0) return null;
    if (this.length === 1) return this[0];

    comparer = (comparer || Math.max);

    var v = this[0];
    for (var i = 1; i < this.length; i++) {
        v = comparer(this[i], v);    
    }

    return v;
}

Swift_TransportException Connection could not be established with host smtp.gmail.com

I had the same problem for a while, replacing: smtp.gmail.com with 173.194.65.108 actually worked for me!

JavaScript/jQuery - How to check if a string contain specific words

This will

/\bword\b/.test("Thisword is not valid");

return false, when this one

/\bword\b/.test("This word is valid");

will return true.

Check if record exists from controller in Rails

When you call Business.where(:user_id => current_user.id) you will get an array. This Array may have no objects or one or many objects in it, but it won't be null. Thus the check == nil will never be true.

You can try the following:

if Business.where(:user_id => current_user.id).count == 0

So you check the number of elements in the array and compare them to zero.

or you can try:

if Business.find_by_user_id(current_user.id).nil?

this will return one or nil.

is python capable of running on multiple cores?

CPython (the classic and prevalent implementation of Python) can't have more than one thread executing Python bytecode at the same time. This means compute-bound programs will only use one core. I/O operations and computing happening inside C extensions (such as numpy) can operate simultaneously.

Other implementation of Python (such as Jython or PyPy) may behave differently, I'm less clear on their details.

The usual recommendation is to use many processes rather than many threads.

Sorting HTML table with JavaScript

It does WAY more than "just sorting", but dataTables.net does what you need. I use it daily and is well supported and VERY fast (does require jQuery)

http://datatables.net/

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.

Google Visualizations is another option, but requires a bit more setup that dataTables, but does NOT require any particular framework/library (other than google.visualizations):

http://code.google.com/apis/ajax/playground/?type=visualization#table

And there are other options to... especially if you're using one of the other JS frameworks. Dojo, Prototype, etc all have usable "table enhancement" plugins that provide at minimum table sorting functionality. Many provide more, but I'll restate...I've yet to come across one as powerful and as FAST as datatables.net.

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

To select the item from the contextual menu, you have to just move your mouse positions with the use of Key down event like this:-

Actions action= new Actions(driver);
action.contextClick(productLink).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();

hope this will works for you. Have a great day :)

Is either GET or POST more secure than the other?

Consider this situation: A sloppy API accepts GET requests like:

http://www.example.com/api?apikey=abcdef123456&action=deleteCategory&id=1

In some settings, when you request this URL and if there is an error/warning regarding the request, this whole line gets logged in the log file. Worse yet: if you forget to disable error messages in the production server, this information is just displayed in plain in the browser! Now you've just given your API key away to everyone.

Unfortunately, there are real API's working this way.

I wouldn't like the idea of having some sensitive info in the logs or displaying them in the browser. POST and GET is not the same. Use each where appropriate.

Select Pandas rows based on list index

you can also use iloc:

df.iloc[[1,3],:]

This will not work if the indexes in your dataframe do not correspond to the order of the rows due to prior computations. In that case use:

df.index.isin([1,3])

... as suggested in other responses.

Getting a map() to return a list in Python 3.x

Do this:

list(map(chr,[66,53,0,94]))

In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster.

If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the map object like so:

# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
    print(ch)

Add a link to an image in a css style sheet

You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.

Based only on your style you would have:

<a href="home.com" id="logo"></a>

Force index use in Oracle

There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.

Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.

begin 
   DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
                                 , INDNAME=>IndexName);
end;

For table.

begin 
   DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
                                 , TABNAME=>TableName);
end;

In extreme cases, you can try setting up the statistics on your own.

MySQL Results as comma separated list

Instead of using group concat() you can use just concat()

Select concat(Col1, ',', Col2) as Foo_Bar from Table1;

edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.

Detecting touch screen devices with Javascript

Found testing for window.Touch didn't work on android but this does:

function is_touch_device() {
  return !!('ontouchstart' in window);
}

See article: What's the best way to detect a 'touch screen' device using JavaScript?

Line Break in XML?

<song>
  <title>Song Tigle</title>
  <lyrics>
    <line>The is the very first line</line>
    <line>Number two and I'm still feeling fine</line>
    <line>Number three and a pattern begins</line>
    <line>Add lines like this and everyone wins!</line>
  </lyrics>
</song>

(Sung to the tune of Home on the Range)

If it was mine I'd wrap the choruses and verses in XML elements as well.

How to Detect if I'm Compiling Code with a particular Visual Studio version?

_MSC_VER should be defined to a specific version number. You can either #ifdef on it, or you can use the actual define and do a runtime test. (If for some reason you wanted to run different code based on what compiler it was compiled with? Yeah, probably you were looking for the #ifdef. :))

How to save a PNG image server-side, from a base64 data string

You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.

$data = 'data:image/png;base64,AAAFBfj42Pj4';

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);

file_put_contents('/tmp/image.png', $data);

And as a one-liner:

$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

An efficient method for extracting, decoding, and checking for errors is:

if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
    $data = substr($data, strpos($data, ',') + 1);
    $type = strtolower($type[1]); // jpg, png, gif

    if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
        throw new \Exception('invalid image type');
    }
    $data = str_replace( ' ', '+', $data );
    $data = base64_decode($data);

    if ($data === false) {
        throw new \Exception('base64_decode failed');
    }
} else {
    throw new \Exception('did not match data URI with image data');
}

file_put_contents("img.{$type}", $data);

Check if all elements in a list are identical

You can use .nunique() to find number of unique items in a list.

def identical_elements(list):
    series = pd.Series(list)
    if series.nunique() == 1: identical = True
    else:  identical = False
    return identical



identical_elements(['a', 'a'])
Out[427]: True

identical_elements(['a', 'b'])
Out[428]: False

javascript pushing element at the beginning of an array

For an uglier version of unshift use splice:

TheArray.splice(0, 0, TheNewObject);

jQuery: Clearing Form Inputs

I'd recomment using good old javascript:

document.getElementById("addRunner").reset();

Equal sized table cells to fill the entire width of the containing table

You don't even have to set a specific width for the cells, table-layout: fixed suffices to spread the cells evenly.

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid hotpink;_x000D_
    vertical-align: middle;_x000D_
    word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note that for table-layout to work the table styled element must have a width set (100% in my example).

Determining image file size + dimensions via Javascript?

Most folks have answered how a downloaded image's dimensions can be known so I'll just try to answer other part of the question - knowing downloaded image's file-size.

You can do this using resource timing api. Very specifically transferSize, encodedBodySize and decodedBodySize properties can be used for the purpose.

Check out my answer here for code snippet and more information if you seek : JavaScript - Get size in bytes from HTML img src

Get filename and path from URI from mediastore

Just a simple update on the first answer: mActivity.managedQuery() is now deprecated. I've updated the code with the new method.

private String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String result = cursor.getString(column_index);
    cursor.close();
    return result;
}

android dev source

How to enable Logger.debug() in Log4j

You probably have a log4j.properties file somewhere in the project. In that file you can configure which level of debug output you want. See this example:

log4j.rootLogger=info, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

log4j.logger.com.example=debug

The first line sets the log level for the root logger to "info", i.e. only info, warn, error and fatal will be printed to the console (which is the appender defined a little below that).

The last line sets the logger for com.example.* (if you get your loggers via LogFactory.getLogger(getClass())) will be at debug level, i.e. debug will also be printed.

How to convert timestamp to datetime in MySQL?

You can use

select from_unixtime(1300464000,"%Y-%m-%d %h %i %s") from table;

For in details description about

  1. from_unixtime()
  2. unix_timestamp()

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

If you are 100% sure that directories and files are ok, have a look at the project location.

There is a limit on the path length of files in the Operating System. Perhaps this limit is being exceded in your project files.

Move the project to a shorter folder (say C:/MyProject) and try again!

This was the problem for me!

jQuery & CSS - Remove/Add display:none

For some reason, toggle didn't work for me, and I received the error uncaught type error toggle is not a function when inspecting the element in browser. So I used the following code and it started working for me.

$(".trigger").click(function () {
    $('.news').attr('style', 'display:none');
})

Used jquery script file jquery-2.1.3.min.js.

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

enter image description here

How about just > Format only cells that contain - in the drop down box select Blanks

Best way to initialize (empty) array in PHP

There is no other way, so this is the best.

Edit: This answer is not valid since PHP 5.4 and higher.

performSelector may cause a leak because its selector is unknown

Here is an updated macro based on the answer given above. This one should allow you to wrap your code even with a return statement.

#define SUPPRESS_PERFORM_SELECTOR_LEAK_WARNING(code)                        \
    _Pragma("clang diagnostic push")                                        \
    _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"")     \
    code;                                                                   \
    _Pragma("clang diagnostic pop")                                         \


SUPPRESS_PERFORM_SELECTOR_LEAK_WARNING(
    return [_target performSelector:_action withObject:self]
);

How do you get total amount of RAM the computer has?

Add a reference to Microsoft.VisualBasic.dll, as someone mentioned above. Then getting total physical memory is as simple as this (yes, I tested it):

static ulong GetTotalMemoryInBytes()
{
    return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}

How to set a default value for an existing column

cannot use alter column for that, use add instead

ALTER TABLE Employee 
ADD DEFAULT('SANDNES') FOR CityBorn

How can a file be copied?

For small files and using only python built-ins, you can use the following one-liner:

with open(source, 'rb') as src, open(dest, 'wb') as dst: dst.write(src.read())

As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.

Undoing accidental git stash pop

From git stash --help

Recovering stashes that were cleared/dropped erroneously
   If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the
   following incantation to get a list of stashes that are still in your repository, but not reachable any more:

       git fsck --unreachable |
       grep commit | cut -d\  -f3 |
       xargs git log --merges --no-walk --grep=WIP

This helped me better than the accepted answer with the same scenario.

How to increment a letter N times per iteration and store in an array?

ord() will not work because your end string is two characters long.

Returns the ASCII value of the first character of string.

Watch it break.

From my testing, you need to check that the end string doesn't get "stepped over". The perl-style character incrementation is a cool method, but it is a single-stepping method. For this reason, an inner loop helps it along when necessary. This is actually not a bother, in fact, it is useful because we need to check if the loop(s) should be broken on each single step.

Code: (Demo)

function excelCols($letter,$end,$step=1){  // function doesn't check that $end is "later" than $letter
    if($step==0)return [];  // prevent infinite loop
    do{
        $letters[]=$letter;  // store letter
        for($x=0; $x<$step; ++$x){  // increment in accordance with $step declaration
            if($letter===$end)break(2);  // break if end is "stepped on"
            ++$letter;
        }
    }while(true);
    return $letters;    
}
echo implode(' ',excelCols('A','JJ',4));
echo "\n --- \n";
echo implode(' ',excelCols('A','BB',3));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',1));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',3));

Output:

A E I M Q U Y AC AG AK AO AS AW BA BE BI BM BQ BU BY CC CG CK CO CS CW DA DE DI DM DQ DU DY EC EG EK EO ES EW FA FE FI FM FQ FU FY GC GG GK GO GS GW HA HE HI HM HQ HU HY IC IG IK IO IS IW JA JE JI
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ
 --- 
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ BA BB BC BD BE BF BG BH BI BJ BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ CA CB CC CD CE CF CG CH CI CJ CK CL CM CN CO CP CQ CR CS CT CU CV CW CX CY CZ DA DB DC DD DE DF DG DH DI DJ DK DL DM DN DO DP DQ DR DS DT DU DV DW DX DY DZ EA EB EC ED EE EF EG EH EI EJ EK EL EM EN EO EP EQ ER ES ET EU EV EW EX EY EZ FA FB FC FD FE FF FG FH FI FJ FK FL FM FN FO FP FQ FR FS FT FU FV FW FX FY FZ GA GB GC GD GE GF GG GH GI GJ GK GL GM GN GO GP GQ GR GS GT GU GV GW GX GY GZ HA HB HC HD HE HF HG HH HI HJ HK HL HM HN HO HP HQ HR HS HT HU HV HW HX HY HZ IA IB IC ID IE IF IG IH II IJ IK IL IM IN IO IP IQ IR IS IT IU IV IW IX IY IZ JA JB JC JD JE JF JG JH JI JJ JK JL JM JN JO JP JQ JR JS JT JU JV JW JX JY JZ KA KB KC KD KE KF KG KH KI KJ KK KL KM KN KO KP KQ KR KS KT KU KV KW KX KY KZ LA LB LC LD LE LF LG LH LI LJ LK LL LM LN LO LP LQ LR LS LT LU LV LW LX LY LZ MA MB MC MD ME MF MG MH MI MJ MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ OA OB OC OD OE OF OG OH OI OJ OK OL OM ON OO OP OQ OR OS OT OU OV OW OX OY OZ PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ QA QB QC QD QE QF QG QH QI QJ QK QL QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RD RE RF RG RH RI RJ RK RL RM RN RO RP RQ RR RS RT RU RV RW RX RY RZ SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SP SQ SR SS ST SU SV SW SX SY SZ TA TB TC TD TE TF TG TH TI TJ TK TL TM TN TO TP TQ TR TS TT TU TV TW TX TY TZ UA UB UC UD UE UF UG UH UI UJ UK UL UM UN UO UP UQ UR US UT UU UV UW UX UY UZ VA VB VC VD VE VF VG VH VI VJ VK VL VM VN VO VP VQ VR VS VT VU VV VW VX VY VZ WA WB WC WD WE WF WG WH WI WJ WK WL WM WN WO WP WQ WR WS WT WU WV WW WX WY WZ XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YA YB YC YD YE YF YG YH YI YJ YK YL YM YN YO YP YQ YR YS YT YU YV YW YX YY YZ ZA ZB ZC ZD ZE ZF ZG ZH ZI ZJ ZK ZL ZM ZN ZO ZP ZQ ZR ZS ZT ZU ZV ZW ZX ZY ZZ
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ BC BF BI BL BO BR BU BX CA CD CG CJ CM CP CS CV CY DB DE DH DK DN DQ DT DW DZ EC EF EI EL EO ER EU EX FA FD FG FJ FM FP FS FV FY GB GE GH GK GN GQ GT GW GZ HC HF HI HL HO HR HU HX IA ID IG IJ IM IP IS IV IY JB JE JH JK JN JQ JT JW JZ KC KF KI KL KO KR KU KX LA LD LG LJ LM LP LS LV LY MB ME MH MK MN MQ MT MW MZ NC NF NI NL NO NR NU NX OA OD OG OJ OM OP OS OV OY PB PE PH PK PN PQ PT PW PZ QC QF QI QL QO QR QU QX RA RD RG RJ RM RP RS RV RY SB SE SH SK SN SQ ST SW SZ TC TF TI TL TO TR TU TX UA UD UG UJ UM UP US UV UY VB VE VH VK VN VQ VT VW VZ WC WF WI WL WO WR WU WX XA XD XG XJ XM XP XS XV XY YB YE YH YK YN YQ YT YW YZ ZC ZF ZI ZL ZO ZR ZU ZX

Here is an array-functions approach:

Code: (Demo)

$start='C';
$end='DD';
$step=4;

// generate and store more than we need (this is an obvious method disadvantage)
$result=$array=range('A','Z',1);  // store A - Z as $array and $result
foreach($array as $a){
    foreach($array as $b){
        $result[]="$a$b";  // store double letter combinations
        if(in_array($end,$result)){break(2);}  // stop asap
    }
}
//echo implode(' ',$result),"\n\n";

// slice away from the front of the array
$result=array_slice($result,array_search($start,$result));  // reindex keys
//echo implode(' ',$result),"\n\n";

 // punch out elements that are not "stepped on"
$result=array_filter($result,function($k)use($step){return $k%$step==0;},ARRAY_FILTER_USE_KEY); // use modulo

// result is ready
echo implode(' ',$result);

Output:

C G K O S W AA AE AI AM AQ AU AY BC BG BK BO BS BW CA CE CI CM CQ CU CY DC

Current user in Magento?

$customer = Mage::getSingleton('customer/session')->getCustomer();
    $customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
    $address = Mage::getModel('customer/address')->load($customerAddressId);
    $fullname = $customer->getName();
    $firstname = $customer->getFirstname();
    $lastname = $customer->getLastname();
    $email = $customer->getEmail();
    $taxvat = $customer->getTaxvat();
    $tele = $customer->getTelephone();
    $telephone = $address->getTelephone();
    $street = $address->getStreet();
    $City = $address->getCity();
    $region = $address->getRegion();
    $postcode = $address->getPostcode();

Get customer Default Billing address

plot a circle with pyplot

You need to add it to an axes. A Circle is a subclass of an Patch, and an axes has an add_patch method. (You can also use add_artist but it's not recommended.)

Here's an example of doing this:

import matplotlib.pyplot as plt

circle1 = plt.Circle((0, 0), 0.2, color='r')
circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue')
circle3 = plt.Circle((1, 1), 0.2, color='g', clip_on=False)

fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot
# (or if you have an existing figure)
# fig = plt.gcf()
# ax = fig.gca()

ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)

fig.savefig('plotcircles.png')

This results in the following figure:

The first circle is at the origin, but by default clip_on is True, so the circle is clipped when ever it extends beyond the axes. The third (green) circle shows what happens when you don't clip the Artist. It extends beyond the axes (but not beyond the figure, ie the figure size is not automatically adjusted to plot all of your artists).

The units for x, y and radius correspond to data units by default. In this case, I didn't plot anything on my axes (fig.gca() returns the current axes), and since the limits have never been set, they defaults to an x and y range from 0 to 1.

Here's a continuation of the example, showing how units matter:

circle1 = plt.Circle((0, 0), 2, color='r')
# now make a circle with no fill, which is good for hi-lighting key results
circle2 = plt.Circle((5, 5), 0.5, color='b', fill=False)
circle3 = plt.Circle((10, 10), 2, color='g', clip_on=False)
    
ax = plt.gca()
ax.cla() # clear things for fresh plot

# change default range so that new circles will work
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
# some data
ax.plot(range(11), 'o', color='black')
# key data point that we are encircling
ax.plot((5), (5), 'o', color='y')
    
ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)
fig.savefig('plotcircles2.png')

which results in:

You can see how I set the fill of the 2nd circle to False, which is useful for encircling key results (like my yellow data point).

What's the difference between ASCII and Unicode?

Storage

Given numbers are only for storing 1 character

  • ASCII ? 27 bits (1 byte)
  • Extended ASCII ? 28 bits (1 byte)
  • UTF-8 ? minimum 28, maximum 232 bits (min 1, max 4 bytes)
  • UTF-16 ? minimum 216, maximum 232 bits (min 2, max 4 bytes)
  • UTF-32 ? 232 bits (4 bytes)

Usage (as of Feb 2020)

Percentages of websites using various character encodings

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

Static constant string (class member)

In C++11 you can do now:

class A {
 private:
  static constexpr const char* STRING = "some useful string constant";
};

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

Doing it in one bulk read:

import re

textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)

Line by line:

import re

textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += reg.findall(line)
textfile.close()

But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:

import re

textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += [(reg.findall(line),offset)]
    offset += len(line)
textfile.close()

But it still just makes more sense to read the whole file in at once.

Simple way to understand Encapsulation and Abstraction

Abstraction is Showing necessary info to the user where as Encapsulation hide the unwanted data from the user(Product from the user).

Encapsulation Implements the Abstraction.

Abstraction is the process where as Encapsulation actually implements it. For Eg. Adding user logic -> we need to validate the user , creating DB connection and insert the User. So user do not know fist need to call validate function , creating DB connection and then insert the Value in DB. He only call the AddUser function which call the internally all logic with in , this is only Encapsulation (Grouping the feature and hiding the methods).

How can I get Android Wifi Scan Results into a list?

Find a complete working example below:

The code by @Android is very good but has few issues, namely:

  1. Populating to ListView code needs to be moved to onReceive of BroadCastReceiver where only the result will be available. In the case result is obtained at 2nd attempt.
  2. BroadCastReceiver needs to be unregistered after the results are obtained.
  3. size = size -1 seems unnecessary.

Find below the modified code of @Android as a working example:

WifiScanner.java which is the Main Activity

package com.arjunandroid.wifiscanner;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class WifiScanner extends Activity implements View.OnClickListener{


    WifiManager wifi;
    ListView lv;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<String> arraylist = new ArrayList<>();
    ArrayAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getActionBar().setTitle("Widhwan Setup Wizard");

        setContentView(R.layout.activity_wifi_scanner);

        buttonScan = (Button) findViewById(R.id.scan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.wifilist);


        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }
        this.adapter =  new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arraylist);
        lv.setAdapter(this.adapter);

        scanWifiNetworks();
    }

    public void onClick(View view)
    {
        scanWifiNetworks();
    }

    private void scanWifiNetworks(){

        arraylist.clear();
        registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        wifi.startScan();

        Log.d("WifScanner", "scanWifiNetworks");

        Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();

    }

    BroadcastReceiver wifi_receiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context c, Intent intent)
        {
            Log.d("WifScanner", "onReceive");
            results = wifi.getScanResults();
            size = results.size();
            unregisterReceiver(this);

            try
            {
                while (size >= 0)
                {
                    size--;
                    arraylist.add(results.get(size).SSID);
                    adapter.notifyDataSetChanged();
                }
            }
            catch (Exception e)
            {
                Log.w("WifScanner", "Exception: "+e);

            }


        }
    };

}

activity_wifi_scanner.xml which is the layout file for the Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/wifilist"
        android:layout_width="match_parent"
        android:layout_height="312dp"
        android:layout_weight="0.97" />


    <Button
        android:id="@+id/scan"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="bottom"
        android:layout_margin="15dp"
        android:background="@android:color/holo_green_light"
        android:text="Scan Again" />
</LinearLayout>

Also as mentioned above, do not forget to add Wifi permissions in the AndroidManifest.xml

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

QByteArray to QString

Qt 4.8

QString(byteArray).toStdString();

Qt 5.12

byteArray.toStdString();

How can I determine the status of a job?

This is an old question, but I just had a similar situation where I needed to check on the status of jobs on SQL Server. A lot of people mentioned the sysjobactivity table and pointed to the MSDN documentation which is great. However, I'd also like to highlight the Job Activity Monitor which provides the status on all jobs that are defined on your server.

What is FCM token in Firebase?

I have an update about "Firebase Cloud Messaging token" which I could get an information.

I really wanted to know about that change so just sent a mail to Support team. The Firebase Cloud Messaging token will get back to Server key soon again. There will be nothing to change. We can see Server key again after soon.

How to add RSA key to authorized_keys file?

mkdir -p ~/.ssh/

To overwrite authorized_keys

cat your_key > ~/.ssh/authorized_keys

To append to the end of authorized_keys

cat your_key >> ~/.ssh/authorized_keys

how to setup ssh keys for jenkins to publish via ssh

For Windows:

  1. Install the necessary plugins for the repository (ex: GitHub install GitHub and GitHub Authentication plugins) in Jenkins.
  2. You can generate a key with Putty key generator, or by running the following command in git bash: $ ssh-keygen -t rsa -b 4096 -C [email protected]
  3. Private key must be OpenSSH. You can convert your private key to OpenSSH in putty key generator
  4. SSH keys come in pairs, public and private. Public keys are inserted in the repository to be cloned. Private keys are saved as credentials in Jenkins
  5. You need to copy the SSH URL not the HTTPS to work with ssh keys.

Is there a way to get the XPath in Google Chrome?

xpathOnClick has what you are looking for: https://chrome.google.com/extensions/detail/ikbfbhbdjpjnalaooidkdbgjknhghhbo

Read the comments though, it actually takes three clicks to get the xpath.

Using request.setAttribute in a JSP page

No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.

If you want to persist attributes through requests you need to either:

  1. Have a hidden input in your form, such as <input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />. This will then be available in the servlet as a request parameter.
  2. Put it in the session (see request.getSession() - in a JSP this is available as simply session)

I recommend using the Session as it's easier to manage.

count number of rows in a data frame in R based on group

Try using the count function in dplyr:

library(dplyr)
dat1_frame %>% 
    count(MONTH.YEAR)

I am not sure how you got MONTH-YEAR as a variable name. My R version does not allow for such a variable name, so I replaced it with MONTH.YEAR.

As a side note, the mistake in your code was that dat1_frame %.% group_by(MONTH-YEAR) without a summarise function returns the original data frame without any modifications. So, you want to use

dat1_frame %>%
    group_by(MONTH.YEAR) %>%
    summarise(count=n())

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

$date + 1 year?

//1 year from today's date
echo date('d-m-Y', strtotime('+1 year'));

//1 year from from specific date
echo date('22-09-Y', strtotime('+1 year'));

hope this simpler bit of code helps someone in future :)

Use sed to replace all backslashes with forward slashes

For me, this replaces one backslash with a forward slash.

sed -e "s/\\\\/\//"  file.txt

How to detect online/offline event cross-browser?

In HTML5 you can use the navigator.onLine property. Look here:

http://www.w3.org/TR/offline-webapps/#related

Probably your current behavior is random as the javascript only ready the "browser" variable and then knows if you're offline and online, but it doesn't actually check the Network Connection.

Let us know if this is what you're looking for.

Kind Regards,

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

head -1000 input > output && sed -i '1,+999d' input

For example:

$ cat input 
1
2
3
4
5
6
$ head -3 input > output && sed -i '1,+2d' input
$ cat input 
4
5
6
$ cat output 
1
2
3

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Post Django version 1.9, on_delete became a required argument, i.e. from Django 2.0.

In older versions, it defaults to CASCADE.

So, if you want to replicate the functionality that you used in earlier versions. Use the following argument.

categorie = models.ForeignKey('Categorie', on_delete = models.CASCADE)

This will have the same effect as that was in earlier versions, without specifying it explicitly.

Official Documentation on other arguments that go with on_delete

Remove all HTMLtags in a string (with the jquery text() function)

I created this test case: http://jsfiddle.net/ccQnK/1/ , I used the Javascript replace function with regular expressions to get the results that you want.

$(document).ready(function() {
    var myContent = '<div id="test">Hello <span>world!</span></div>';
    alert(myContent.replace(/(<([^>]+)>)/ig,""));
});

In C#, can a class inherit from another class and an interface?

I found the answer to the second part of my questions. Yes, a class can implement an interface that is in a different class as long that the interface is declared as public.

How to check user is "logged in"?

The simplest way:

if (Request.IsAuthenticated) ...

How to get the second column from command output?

Use -F [field separator] to split the lines on "s:

awk -F '"' '{print $2}' your_input_file

or for input from pipe

<some_command> | awk -F '"' '{print $2}'

output:

A B
C
D

$apply already in progress error

In my case i use $apply with angular calendar UI to link some event:

$scope.eventClick = function(event){           
    $scope.$apply( function() {
        $location.path('/event/' + event.id);
    });
};

After reading the doc of the problem: https://docs.angularjs.org/error/$rootScope/inprog

The part Inconsistent API (Sync/Async) is very interesting:

For example, imagine a 3rd party library that has a method which will retrieve data for us. Since it may be making an asynchronous call to a server, it accepts a callback function, which will be called when the data arrives.

Since, the MyController constructor is always instantiated from within an $apply call, our handler is trying to enter a new $apply block from within one.

I change the code to :

$scope.eventClick = function(event){           
    $timeout(function() {
        $location.path('/event/' + event.id);
    }, 0);
};

Works like a charm !

Here we have used $timeout to schedule the changes to the scope in a future call stack. By providing a timeout period of 0ms, this will occur as soon as possible and $timeout will ensure that the code will be called in a single $apply block.

How to position the div popup dialog to the center of browser screen?

Its a classical problem, when you scroll the modal popup generated on the screen stays at it place and does not scroll along, so the user might be blocked as he might not see the popup on his viewable screen.

The following link also provides CSS only code for generating a modal box along with its absolute position.

http://settledcuriosity.wordpress.com/2014/10/03/centering-a-popup-box-absolutely-at-the-center-of-screen/

How to use __doPostBack()

I'd just like to add something to this post for asp:button. I've tried clientId and it doesn't seem to work for me:

__doPostBack('<%= btn.ClientID%>', '');

However, getting the UniqueId seems to post back to the server, like below:

__doPostBack('<%= btn.UniqueID%>', '');

This might help someone else in future, hence posting this.

How to force div to appear below not next to another?

I think what you want requires an extra wrapper div.

_x000D_
_x000D_
#map {_x000D_
    float: left; _x000D_
    width: 700px; _x000D_
    height: 500px;_x000D_
}_x000D_
#wrapper {_x000D_
    float: left;_x000D_
    width: 200px;_x000D_
}_x000D_
#list {_x000D_
    background: #eee;_x000D_
    list-style: none; _x000D_
    padding: 0; _x000D_
}_x000D_
#similar {_x000D_
    background: #000; _x000D_
}
_x000D_
<div id="map">Lorem Ipsum</div>        _x000D_
<div id="wrapper">_x000D_
  <ul id="list"><li>Dolor</li><li>Sit</li><li>Amet</li></ul>_x000D_
  <div id ="similar">_x000D_
    this text should be below, not next to ul._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Git On Custom SSH Port

(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:

GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \ git clone myuser@myGitRemoteServer:/my/remote/git_repo/path

This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).

Laravel Rule Validation for Numbers

If I correctly got what you want:

$rules = ['Fno' => 'digits_between:2,5', 'Lno' => 'numeric|min:2'];

or

$rules = ['Fno' => 'numeric|min:2|max:5', 'Lno' => 'numeric|min:2'];

For all the available rules: http://laravel.com/docs/4.2/validation#available-validation-rules

digits_between :min,max

The field under validation must have a length between the given min and max.

numeric

The field under validation must have a numeric value.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

Preloading @font-face fonts?

Proper font pre-loading is a big hole in the HTML5 spec. I've gone through all of this stuff and the most reliable solution I've found is to use Font.js:

http://pomax.nihongoresources.com/pages/Font.js/

You can use it to load fonts using the same API you use to load images

var anyFont = new Font();
anyFont.src = "fonts/fileName.otf";
anyFont.onload = function () {
  console.log("font loaded");
}

It's much simpler and more lightweight than Google's hulking Webfont Loader

Here's the github repo for Font.js:

https://github.com/Pomax/Font.js

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

multiple where condition codeigniter

Try this

$data = array(
               'email' =>$email,
               'last_ip' => $last_ip
            );

$where = array('username ' => $username , 'status ' => $status);
$this->db->where($where);
$this->db->update('table_user ', $data); 

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

You may want to check out Eclipse CDT. It provides a C/C++ IDE that runs on multiple platforms (e.g. Windows, Linux, Mac OS X, etc.). Debugging with Eclipse CDT is comparable to using other tools such as Visual Studio.

You can check out the Eclipse CDT Debug tutorial that also includes a number of screenshots.

Django 1.7 - makemigrations not detecting changes

Just in case you have a specific field that does not get identified by makemigrations: check twice if you have a property with the same name.

example:

field = django.db.models.CharField(max_length=10, default = '', blank=True, null=True)

# ... later

@property
def field(self):
    pass

the property will "overwrite" the field definition so changes will not get identified by makemigrations

Set CSS property in Javascript?

For most styles do this:

var obj = document.createElement('select');
obj.style.width= "100px";

For styles that have hyphens in the name do this instead:

var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"

Google Play on Android 4.0 emulator

For future visitors.

As of now Android 4.2.2 platform includes Google Play services. Just use an emulator running Jelly Bean. Details can be found here:

Setup Google Play Services SDK

EDIT:

Another option is to use Genymotion (runs way faster)

EDIT 2:

As @gdw2 commented: "setting up the Google Play Services SDK does not install a working Google Play app -- it just enables certain services provided by the SDK"

After version 2.0 Genymotion does not come with Play Services by default, but it can be easily installed manually. Just download the right version from here and drag and drop into the virtual device (emulador).

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

How to load external scripts dynamically in Angular?

@rahul-kumar 's solution works good for me, but i wanted to call my javascript function in my typescript

foo.myFunctions() // works in browser console, but foo can't be used in typescript file

I fixed it by declaring it in my typescript :

import { Component } from '@angular/core';
import { ScriptService } from './script.service';
declare var foo;

And now, i can call foo anywhere in my typecript file

multiple axis in matplotlib with different scales

If I understand the question, you may interested in this example in the Matplotlib gallery.

enter image description here

Yann's comment above provides a similar example.


Edit - Link above fixed. Corresponding code copied from the Matplotlib gallery:

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right", axes=par2,
                                        offset=(offset, 0))

par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())

plt.draw()
plt.show()

#plt.savefig("Test")

Failed to authenticate on SMTP server error using gmail

If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"

You may try one of these methods:

Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.

Use double quote for your password: like - "Abc@%$67eSDu"

How to get evaluated attributes inside a custom directive

var myApp = angular.module('myApp',[]);

myApp .directive('myDirective', function ($timeout) {
    return function (scope, element, attr) {
        $timeout(function(){
            element.val("value = "+attr.value);
        });

    }
});

function MyCtrl($scope) {

}

Use $timeout because directive call after dom load so your changes doesn`'t apply

Using jQuery to test if an input has focus

As far as I know, you can't ask the browser if any input on the screen has focus, you have to set up some sort of focus tracking.

I usually have a variable called "noFocus" and set it to true. Then I add a focus event to all inputs that makes noFocus false. Then I add a blur event to all inputs that set noFocus back to true.

I have a MooTools class that handles this quite easily, I'm sure you could create a jquery plugin to do the same.

Once that's created, you could do check noFocus before doing any border swapping.

What is the difference between .text, .value, and .value2?

.Text gives you a string representing what is displayed on the screen for the cell. Using .Text is usually a bad idea because you could get ####

.Value2 gives you the underlying value of the cell (could be empty, string, error, number (double) or boolean)

.Value gives you the same as .Value2 except if the cell was formatted as currency or date it gives you a VBA currency (which may truncate decimal places) or VBA date.

Using .Value or .Text is usually a bad idea because you may not get the real value from the cell, and they are slower than .Value2

For a more extensive discussion see my Text vs Value vs Value2

How do I check for vowels in JavaScript?

benchmark

I think you can safely say a for loop is faster.

I do admit that a regexp looks cleaner in terms of code. If it's a real bottleneck then use a for loop, otherwise stick with the regular expression for reasons of "elegance"

If you want to go for simplicity then just use

function isVowel(c) {
    return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1
}

How to ignore the first line of data when processing CSV data?

use csv.DictReader instead of csv.Reader. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as field names. you would then be able to access field values using row["1"] etc

jQuery: how to find first visible input/select/textarea excluding buttons?

The JQuery code is fine. You must execute in the ready handler not in the window load event.

<script type="text/javascript">
$(function(){
  var aspForm  = $("form#aspnetForm");
  var firstInput = $(":input:not(input[type=button],input[type=submit],button):visible:first", aspForm);
  firstInput.focus();
});
</script>

Update

I tried with the example of Karim79(thanks for the example) and it works fine: http://jsfiddle.net/2sMfU/

Dockerfile copy keep subdirectory structure

If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.

COPY . destinatio-directory/ 

How do I check if an element is really visible with JavaScript?

Try element.getBoundingClientRect(). It will return an object with properties

  • bottom
  • top
  • right
  • left
  • width -- browser dependent
  • height -- browser dependent

Check that the width and height of the element's BoundingClientRect are not zero which is the value of hidden or non-visible elements. If the values are greater than zero the element should be visible in the body. Then check if the bottom property is less than screen.height which would imply that the element is withing the viewport. (Technically you would also have to account for the top of the browser window including the searchbar, buttons, etc.)