Programs & Examples On #Ii6

Google Maps how to Show city or an Area outline

I have try twitter geo api, failed.

Google map api, failed, so far, no way you can get city limit by any api.

twitter api geo endpoint will NOT give you city boundary,

what they provide you is ONLY bounding box with 5 point(lat, long)

this is what I get from twitter api geo for San Francisco enter image description here

Python base64 data decode

import base64
coded_string = '''Q5YACgA...'''
base64.b64decode(coded_string)

worked for me. At the risk of pasting an offensively-long result, I got:

>>> base64.b64decode(coded_string)
2: 'C\x96\x00\n\x00\x00\x00\x00C\x96\x00\x1b\x00\x00\x00\x00C\x96\x00-\x00\x00\x00\x00C\x96\x00?\x00\x00\x00\x00C\x96\x07M\x00\x00\x00\x00C\x96\x07_\x00\x00\x00\x00C\x96\x07p\x00\x00\x00\x00C\x96\x07\x82\x00\x00\x00\x00C\x96\x07\x94\x00\x00\x00\x00C\x96\x07\xa6Cq\xf0\x7fC\x96\x07\xb8DJ\x81\xc7C\x96\x07\xcaD\xa5\x9dtC\x96\x07\xdcD\xb6\x97\x11C\x96\x07\xeeD\x8b\x8flC\x96\x07\xffD\x03\xd4\xaaC\x96\x08\x11B\x05&\xdcC\x96\x08#\x00\x00\x00\x00C\x96\x085C\x0c\xc9\xb7C\x96\x08GCy\xc0\xebC\x96\x08YC\x81\xa4xC\x96\x08kC\x0f@\x9bC\x96\x08}\x00\x00\x00\x00C\x96\x08\x8e\x00\x00\x00\x00C\x96\x08\xa0\x00\x00\x00\x00C\x96\x08\xb2\x00\x00\x00\x00C\x96\x86\xf9\x00\x00\x00\x00C\x96\x87\x0b\x00\x00\x00\x00C\x96\x87\x1d\x00\x00\x00\x00C\x96\x87/\x00\x00\x00\x00C\x96\x87AA\x0b\xe7PC\x96\x87SCI\xf5gC\x96\x87eC\xd4J\xeaC\x96\x87wD\r\x17EC\x96\x87\x89D\x00F6C\x96\x87\x9bC\x9cg\xdeC\x96\x87\xadB\xd56\x0cC\x96\x87\xbf\x00\x00\x00\x00C\x96\x87\xd1\x00\x00\x00\x00C\x96\x87\xe3\x00\x00\x00\x00C\x96\x87\xf5\x00\x00\x00\x00C\x9cY}\x00\x00\x00\x00C\x9cY\x90\x00\x00\x00\x00C\x9cY\xa4\x00\x00\x00\x00C\x9cY\xb7\x00\x00\x00\x00C\x9cY\xcbC\x1f\xbd\xa3C\x9cY\xdeCCz{C\x9cY\xf1CD\x02\xa7C\x9cZ\x05C+\x9d\x97C\x9cZ\x18C\x03R\xe3C\x9cZ,\x00\x00\x00\x00C\x9cZ?
[stuff omitted as it exceeded SO's body length limits]
\xbb\x00\x00\x00\x00D\xc5!7\x00\x00\x00\x00D\xc5!\xb2\x00\x00\x00\x00D\xc7\x14x\x00\x00\x00\x00D\xc7\x14\xf6\x00\x00\x00\x00D\xc7\x15t\x00\x00\x00\x00D\xc7\x15\xf2\x00\x00\x00\x00D\xc7\x16pC5\x9f\xf9D\xc7\x16\xeeC[\xb5\xf5D\xc7\x17lCG\x1b;D\xc7\x17\xeaB\xe3\x0b\xa6D\xc7\x18h\x00\x00\x00\x00D\xc7\x18\xe6\x00\x00\x00\x00D\xc7\x19d\x00\x00\x00\x00D\xc7\x19\xe2\x00\x00\x00\x00D\xc7\xfe\xb4\x00\x00\x00\x00D\xc7\xff3\x00\x00\x00\x00D\xc7\xff\xb2\x00\x00\x00\x00D\xc8\x001\x00\x00\x00\x00'

What problem are you having, specifically?

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

Specified cast is not valid?

From your comment:

this line DateTime Date = reader.GetDateTime(0); was throwing the exception

The first column is not a valid DateTime. Most likely, you have multiple columns in your table, and you're retrieving them all by running this query:

SELECT * from INFO

Replace it with a query that retrieves only the two columns you're interested in:

SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO

Then try reading the values again:

var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1);  // equivalent to time(7) from your database

Or:

var Date = Convert.ToDateTime(reader["YOUR_DATE_COLUMN"]);
var Time = (TimeSpan)reader["YOUR_TIME_COLUMN"];

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

To prevent users from refreshing the page or pressing the back button and resubmitting the form I use the following neat little trick.

<?php

if (!isset($_SESSION)) {
    session_start();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION['postdata'] = $_POST;
    unset($_POST);
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}
?>

The POST data is now in a session and users can refresh however much they want. It will no longer have effect on your code.

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

Combine two integer arrays

Task: Given two int arrays array1 and array2 of the same length, zip should return an array that's twice as long, in which the elements of array1 and array2 are interleaved. That is, element #0 of the result array is array1[0], element #1 is array2[0], element #2 is array1[1], element #3 is array2[1], and so on.

public static int [] zip(int [ ] array1, int [] array2) {
//make sure both arrays have same length
if (array1.length != array2.length) {
    throw new IllegalArgumentException("Unequal array lengths - zip not possible");
}

int [] zippedArray = new int [array1.length+ array2.length]; 
int idx_1 = 0;
int idx_2 = 0;

//for each element of first array, add to new array if index of new array is even

for (int i=0; i < zippedArray.length; i+=2){
    zippedArray[i]= array1[idx_1++];
}
for (int i=1; i < zippedArray.length; i+=2){
    zippedArray[i]= array2[idx_2++];
}

//check contents of new array       
for (int item: zippedArray){
    System.out.print(item + " ");
}

return zippedArray;

}

Int or Number DataType for DataAnnotation validation attribute

almost a decade passed but the issue still valid with Asp.Net Core 2.2 as well.

I managed it by adding data-val-number to the input field the use localization on the message:

<input asp-for="Age" data-val-number="@_localize["Please enter a valid number."]"/>

In git how is fetch different than pull and how is merge different than rebase?

fetch vs pull

fetch will download any changes from the remote* branch, updating your repository data, but leaving your local* branch unchanged.

pull will perform a fetch and additionally merge the changes into your local branch.

What's the difference? pull updates you local branch with changes from the pulled branch. A fetch does not advance your local branch.

merge vs rebase

Given the following history:

          C---D---E local
         /
    A---B---F---G remote

merge joins two development histories together. It does this by replaying the changes that occurred on your local branch after it diverged on top of the remote branch, and record the result in a new commit. This operation preserves the ancestry of each commit.

The effect of a merge will be:

          C---D---E local
         /         \
    A---B---F---G---H remote

rebase will take commits that exist in your local branch and re-apply them on top of the remote branch. This operation re-writes the ancestors of your local commits.

The effect of a rebase will be:

                  C'--D'--E' local
                 /
    A---B---F---G remote

What's the difference? A merge does not change the ancestry of commits. A rebase rewrites the ancestry of your local commits.

* This explanation assumes that the current branch is a local branch, and that the branch specified as the argument to fetch, pull, merge, or rebase is a remote branch. This is the usual case. pull, for example, will download any changes from the specified branch, update your repository and merge the changes into the current branch.

Get all object attributes in Python?

Use the built-in function dir().

Moving Average Pandas

To get the moving average in pandas we can use cum_sum and then divide by count.

Here is the working example:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': range(5),
                   'value': range(100,600,100)})

# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']

# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()

print(df)

output

   id  value  cum_sum  count  mov_avg     rolling_mean2
0   0    100      100      1    100.0           NaN
1   1    200      300      2    150.0           150.0
2   2    300      600      3    200.0           250.0
3   3    400     1000      4    250.0           350.0
4   4    500     1500      5    300.0           450.0

Hibernate table not mapped error in HQL query

In the Spring configuration typo applicationContext.xml where the sessionFactory configured put this property

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="packagesToScan" value="${package.name}"/>

Saving excel worksheet to CSV files with filename+worksheet name using VB

Best way to find out is to record the macro and perform the exact steps and see what VBA code it generates. you can then go and replace the bits you want to make generic (i.e. file names and stuff)

SQL Server, division returns zero

Because it's an integer. You need to declare them as floating point numbers or decimals, or cast to such in the calculation.

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

Find duplicate characters in a String and count the number of occurances using Java

In java... using for loop:

import java.util.Scanner;

/**
 *
 * @author MD SADDAM HUSSAIN */
public class Learn {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        String input = sc.next();
        char process[] = input.toCharArray();
        boolean status = false;
        int index = 0;
        for (int i = 0; i < process.length; i++) {
            for (int j = 0; j < process.length; j++) {

                if (i == j) {
                    continue;
                } else {
                    if (process[i] == process[j]) {
                        status = true;
                        index = i;
                        break;
                    } else {
                        status = false;

                    }
                }

            }
            if (status) {
                System.out.print("" + process[index]);

            }
        }
    }
}

compareTo() vs. equals()

I believe equals and equalsIgnoreCase methods of String return true and false which is useful if you wanted to compare the values of the string object, But in case of implementing compareTo and compareToIgnoreCase methods returns positive, negative and zero value which will be useful in case of sorting.

Create a Cumulative Sum Column in MySQL

You could also create a trigger that will calculate the sum before each insert

delimiter |

CREATE TRIGGER calCumluativeSum  BEFORE INSERT ON someTable
  FOR EACH ROW BEGIN

  SET cumulative_sum = (
     SELECT SUM(x.count)
        FROM someTable x
        WHERE x.id <= NEW.id
    )

    set  NEW.cumulative_sum = cumulative_sum;
  END;
|

I have not tested this

Trying to retrieve first 5 characters from string in bash error?

This might work for you:

 printf "%.5s" $TESTSTRINGONE

Find Item in ObservableCollection without using a loop

You're looking for a hash based collection (like a Dictionary or Hashset) which the ObservableCollection is not. The best solution might be to derive from a hash based collection and implement INotifyCollectionChanged which will give you the same behavior as an ObservableCollection.

How to push a single file in a subdirectory to Github (not master)

git status #then file which you need to push git add example.FileExtension

git commit "message is example"

git push -u origin(or whatever name you used) master(or name of some branch where you want to push it)

Error in installation a R package

In my case, I had to close R session and reinstall all packages. In that session I worked with large tables, I suspect this might have had the effect.

Split string with JavaScript

Like this:

var myString = "19 51 2.108997";
var stringParts = myString.split(" ");
var html = "<span>" + stringParts[0] + " " + stringParts[1] + "</span> <span>" + stringParts[2] + "</span";

jQuery - Check if DOM element already exists

Also think about using

$(document).ready(function() {});

Don't know why no one here came up with this yet (kinda sad). When do you execute your code??? Right at the start? Then you might want to use upper mentioned ready() function so your code is being executed after the whole page (with all it's dom elements) has been loaded and not before! Of course this is useless if you run some code that adds dom elements after page load! Then you simply want to wait for those functions and execute your code afterwards...

Custom exception type

Yes. You can throw anything you want: integers, strings, objects, whatever. If you want to throw an object, then simply create a new object, just as you would create one under other circumstances, and then throw it. Mozilla's Javascript reference has several examples.

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon destroys the session as stated above so you should use this when logging someone out. I think a good use of Session.Clear would be for a shopping basket on an ecommerce website. That way the basket gets cleared without logging out the user.

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

If you support IE, for versions of Internet Explorer 8 and above, this:

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />

Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.

If you separate with semi-colon, it sets compatibility levels for different versions. For example:

<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />

Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

For this:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

It forces the browser the render at whatever the most recent version's standards are.

For more information, there is plenty to read about on MSDN,

How to run a javascript function during a mouseover on a div

This is badly formed HTML. You need to either have a single id or space separated classes. Either way if you're new I'd look into jQuery.

<div id="sub1">some text</div>

or

<div class="sub1 sub2 sub3">some text</div>

If you had the following HTML:

<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Some welcome message</div>

jQuery

$(document).ready(function() {
    $('#sub1').hover(
      function() { $('#welcome').show(); },
      function() { $('#welcome').hide(); }
    );
});

Javascript

you'd probably want to include the events on your html:

<div id="sub1" onmouseover="showWelcome();" onmouseout="hideWelcome();">some text</div>

then your javascript would have these two functions

function showWelcome()
{
   var welcome = document.getElementById('welcome');
   welcome.style.display = 'block';
}

function hideWelcome()
{
   var welcome = document.getElementById('welcome');
   welcome.style.display = 'none';
}

Please note: this javascript doesn't take cross browser issues into consideration. for this you'd need to elaborate on your code, just another reason to use jquery.

jQuery checkbox onChange

There is a typo error :

$('#activelist :checkbox')...

Should be :

$('#inactivelist:checkbox')...

What does a Status of "Suspended" and high DiskIO means from sp_who2?

This is a very broad question, so I am going to give a broad answer.

  1. A query gets suspended when it is requesting access to a resource that is currently not available. This can be a logical resource like a locked row or a physical resource like a memory data page. The query starts running again, once the resource becomes available. 
  2. High disk IO means that a lot of data pages need to be accessed to fulfill the request.

That is all that I can tell from the above screenshot. However, if I were to speculate, you probably have an IO subsystem that is too slow to keep up with the demand. This could be caused by missing indexes or an actually too slow disk. Keep in mind, that 15000 reads for a single OLTP query is slightly high but not uncommon.

COALESCE Function in TSQL

I'm not sure why you think the documentation is vague.

It simply goes through all the parameters one by one, and returns the first that is NOT NULL.

COALESCE(NULL, NULL, NULL, 1, 2, 3)
=> 1


COALESCE(1, 2, 3, 4, 5, NULL)
=> 1


COALESCE(NULL, NULL, NULL, 3, 2, NULL)
=> 3


COALESCE(6, 5, 4, 3, 2, NULL)
=> 6


COALESCE(NULL, NULL, NULL, NULL, NULL, NULL)
=> NULL

It accepts pretty much any number of parameters, but they should be the same data-type. (If they're not the same data-type, they get implicitly cast to an appropriate data-type using data-type order of precedence.)

It's like ISNULL() but for multiple parameters, rather than just two.

It's also ANSI-SQL, where-as ISNULL() isn't.

What does the DOCKER_HOST variable do?

Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:

$(boot2docker shellinit)

I had tested these commands:

>>  docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>>  boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
    export DOCKER_HOST=tcp://192.168.59.103:2376
    export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
    export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory

Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)...

>>  $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>>  docker info
Containers: 3
...

Convert string to JSON array

If having following JSON from web service, Json Array as a response :

       [3]
 0:  {
 id: 2
 name: "a561137"
 password: "test"
 firstName: "abhishek"
 lastName: "ringsia"
 organization: "bbb"
    }-
1:  {
 id: 3
 name: "a561023"
 password: "hello"
 firstName: "hello"
  lastName: "hello"
  organization: "hello"
 }-
 2:  {
  id: 4
  name: "a541234"
  password: "hello"
  firstName: "hello"
  lastName: "hello"
  organization: "hello"
    }

have To Accept it first as a Json Array ,then while reading its Object have to use Object Mapper.readValue ,because Json Object Still in String .

      List<User> list = new ArrayList<User>();
      JSONArray jsonArr = new JSONArray(response);


      for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject jsonObj = jsonArr.getJSONObject(i);
         ObjectMapper mapper = new ObjectMapper();
        User usr = mapper.readValue(jsonObj.toString(), User.class);      
        list.add(usr);

    }

mapper.read is correct function ,if u use mapper.convert(param,param) . It will give u error .

How to import a csv file into MySQL workbench?

It seems a little tricky since it really had bothered me for a long time.

You just need to open the table (right click the "Select Rows- Limit 10000") and you will open a new window. In this new window, you will find "import icon".

Proper use of const for defining functions in JavaScript

There's no problem with what you've done, but you must remember the difference between function declarations and function expressions.

A function declaration, that is:

function doSomething () {}

Is hoisted entirely to the top of the scope (and like let and const they are block scoped as well).

This means that the following will work:

doSomething() // works!
function doSomething() {}

A function expression, that is:

[const | let | var] = function () {} (or () =>

Is the creation of an anonymous function (function () {}) and the creation of a variable, and then the assignment of that anonymous function to that variable.

So the usual rules around variable hoisting within a scope -- block-scoped variables (let and const) do not hoist as undefined to the top of their block scope.

This means:

if (true) {
    doSomething() // will fail
    const doSomething = function () {}
}

Will fail since doSomething is not defined. (It will throw a ReferenceError)

If you switch to using var you get your hoisting of the variable, but it will be initialized to undefined so that block of code above will still not work. (This will throw a TypeError since doSomething is not a function at the time you call it)

As far as standard practices go, you should always use the proper tool for the job.

Axel Rauschmayer has a great post on scope and hoisting including es6 semantics: Variables and Scoping in ES6

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"

EDIT: actually, Chromium docs also indicate how to do it for other OS.

What are the differences between ArrayList and Vector?

Differences

  • Vectors are synchronized, ArrayLists are not.
  • Data Growth Methods

Use ArrayLists if there is no specific requirement to use Vectors.

Synchronization

If multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which modifies the list either structurally or simply modifies an element. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.

Collections.synchronizedList is normally used at the time of creation of the list to avoid any accidental unsynchronized access to the list.

Reference

Data growth

Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Reference

Why do I get the "Unhandled exception type IOException"?

Java has a feature called "checked exceptions". That means that there are certain kinds of exceptions, namely those that subclass Exception but not RuntimeException, such that if a method may throw them, it must list them in its throws declaration, say: void readData() throws IOException. IOException is one of those.

Thus, when you are calling a method that lists IOException in its throws declaration, you must either list it in your own throws declaration or catch it.

The rationale for the presence of checked exceptions is that for some kinds of exceptions, you must not ignore the fact that they may happen, because their happening is quite a regular situation, not a program error. So, the compiler helps you not to forget about the possibility of such an exception being raised and requires you to handle it in some way.

However, not all checked exception classes in Java standard library fit under this rationale, but that's a totally different topic.

mongodb: insert if not exists

You could always make a unique index, which causes MongoDB to reject a conflicting save. Consider the following done using the mongodb shell:

> db.getCollection("test").insert ({a:1, b:2, c:3})
> db.getCollection("test").find()
{ "_id" : ObjectId("50c8e35adde18a44f284e7ac"), "a" : 1, "b" : 2, "c" : 3 }
> db.getCollection("test").ensureIndex ({"a" : 1}, {unique: true})
> db.getCollection("test").insert({a:2, b:12, c:13})      # This works
> db.getCollection("test").insert({a:1, b:12, c:13})      # This fails
E11000 duplicate key error index: foo.test.$a_1  dup key: { : 1.0 }

Python: Fetch first 10 results from a list

check this

 list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

 list[0:10]

Outputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

How to make Bitmap compress without change the bitmap size?

Here's a short means I used to reduce the size of Images that have a high byteCount (basically pixels)

fun resizeImage(image: Bitmap): Bitmap {

    val width = image.width
    val height = image.height

    val scaleWidth = width / 10
    val scaleHeight = height / 10

    if (image.byteCount <= 1000000)
        return image

    return Bitmap.createScaledBitmap(image, scaleWidth, scaleHeight, false)
}

This returns a scaled Bitmap that is over 10 times smaller than the Bitmap passed as a parameter. Might not be the most ideal solution but it works.

Python functions call by reference

OK, I'll take a stab at this. Python passes by object reference, which is different from what you'd normally think of as "by reference" or "by value". Take this example:

def foo(x):
    print x

bar = 'some value'
foo(bar)

So you're creating a string object with value 'some value' and "binding" it to a variable named bar. In C, that would be similar to bar being a pointer to 'some value'.

When you call foo(bar), you're not passing in bar itself. You're passing in bar's value: a pointer to 'some value'. At that point, there are two "pointers" to the same string object.

Now compare that to:

def foo(x):
    x = 'another value'
    print x

bar = 'some value'
foo(bar)

Here's where the difference lies. In the line:

x = 'another value'

you're not actually altering the contents of x. In fact, that's not even possible. Instead, you're creating a new string object with value 'another value'. That assignment operator? It isn't saying "overwrite the thing x is pointing at with the new value". It's saying "update x to point at the new object instead". After that line, there are two string objects: 'some value' (with bar pointing at it) and 'another value' (with x pointing at it).

This isn't clumsy. When you understand how it works, it's a beautifully elegant, efficient system.

Python: IndexError: list index out of range

As the error notes, the problem is in the line:

if guess[i] == winning_numbers[i]

The error is that your list indices are out of range--that is, you are trying to refer to some index that doesn't even exist. Without debugging your code fully, I would check the line where you are adding guesses based on input:

for i in range(tickets):
    bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
    guess.append(bubble)
print(bubble)

The size of how many guesses you are giving your user is based on

# Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))

So if the number of tickets they want is less than 5, then your code here

for i in range(5):

if guess[i] == winning_numbers[i]:
    match = match+1

return match

will throw an error because there simply aren't that many elements in the guess list.

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)");

How do I get a list of locked users in an Oracle database?

select username,
       account_status 
  from dba_users 
 where lock_date is not null;

This will actually give you the list of locked users.

Oracle query to fetch column names

the point is that in toad u have to write table name capital, like this:

select *
FROM all_tab_columns
where table_name like 'IDECLARATION';

Object Dump JavaScript

Just use:

console.dir(object);

you will get a nice clickable object representation. Works in Chrome and Firefox

Close Form Button Event

If am not wrong

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   //You may decide to prompt to user
   //else just kill
   Process.GetCurrentProcess().Kill();
} 

How do I bind to list of checkbox values with AngularJS?

Here is the jsFillde link for the same, http://jsfiddle.net/techno2mahi/Lfw96ja6/.

This uses the directive which is available for download at http://vitalets.github.io/checklist-model/.

This is the good to have directive as your application will need this functionality much often.

The code is below:

HTML:

<div class="container">
    <div class="ng-scope" ng-app="app" ng-controller="Ctrl1">
        <div class="col-xs-12 col-sm-6">
            <h3>Multi Checkbox List Demo</h3>
            <div class="well">  <!-- ngRepeat: role in roles -->
                <label ng-repeat="role in roles">
                    <input type="checkbox" checklist-model="user.roles" checklist-value="role"> {{role}}
                </label>
            </div>

            <br>
            <button ng-click="checkAll()">check all</button>
            <button ng-click="uncheckAll()">uncheck all</button>
            <button ng-click="checkFirst()">check first</button>
            <div>
                <h3>Selected User Roles </h3>
                <pre class="ng-binding">{{user.roles|json}}</pre>
            </div>

            <br>
            <div><b/>Provided by techno2Mahi</b></div>
        </div>

JavaScript

var app = angular.module("app", ["checklist-model"]);
app.controller('Ctrl1', function($scope) {
  $scope.roles = [
    'guest',
    'user',
    'customer',
    'admin'
  ];
  $scope.user = {
    roles: ['user']
  };
  $scope.checkAll = function() {
    $scope.user.roles = angular.copy($scope.roles);
  };
  $scope.uncheckAll = function() {
    $scope.user.roles = [];
  };
  $scope.checkFirst = function() {
    $scope.user.roles.splice(0, $scope.user.roles.length);
    $scope.user.roles.push('guest');
  };
});

What is 'Context' on Android?

Context means component (or application) in various time-period. If I do eat so much food between 1 to 2 pm then my context of that time is used to access all methods (or resources) that I use during that time. Content is a component (application) for a particular time. The Context of components of the application keeps changing based on the underlying lifecycle of the components or application. For instance, inside the onCreate() of an Activity,

getBaseContext() -- gives the context of the Activity that is set (created) by the constructor of activity. getApplicationContext() -- gives the Context setup (created) during the creation of application.

Note: <application> holds all Android Components.

<application>
    <activity> .. </activity> 

    <service>  .. </service>

    <receiver> .. </receiver>

    <provider> .. </provider>
</application> 

It means, when you call getApplicationContext() from inside whatever component, you are calling the common context of the whole application.

Context keeps being modified by the system based on the lifecycle of components.

How to compile C programming in Windows 7?

You can get MinGW (as others have suggested) but I would recommend getting a simple IDE (not VS Express). You can try Dev C++ http://www.bloodshed.net/devcpp.html Its a simple IDE for C/C++ and uses MinGW internally. In this you can write and compile single C files without creating a full-blown "project".

Getting all selected checkboxes in an array

Pure JavaScript with no need for temporary variables:

Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked")).map(e => e.value)

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

ReactJS - Does render get called any time "setState" is called?

Not All Components.

the state in component looks like the source of the waterfall of state of the whole APP.

So the change happens from where the setState called. The tree of renders then get called from there. If you've used pure component, the render will be skipped.

Eclipse C++: Symbol 'std' could not be resolved

Try restart Eclipse first, in my case I change different Compiler setting of the project then it shows this message, after restart it works.

How to activate a specific worksheet in Excel?

I would recommend you to use worksheet's index instead of using worksheet's name, in this way you can also loop through sheets "dynamically"

for i=1 to thisworkbook.sheets.count
 sheets(i).activate
'You can add more code 
with activesheet
 'Code...
end with
next i

It will also, improve performance.

Exploitable PHP functions

I fear my answer might be a bit too negative, but...

IMHO, every single function and method out there can be used for nefarious purposes. Think of it as a trickle-down effect of nefariousness: a variable gets assigned to a user or remote input, the variable is used in a function, the function return value used in a class property, the class property used in a file function, and so forth. Remember: a forged IP address or a man-in-the-middle attack can exploit your entire website.

Your best bet is to trace from beginning to end any possible user or remote input, starting with $_SERVER, $_GET, $_POST, $_FILE, $_COOKIE, include(some remote file) (if allow_url_fopen is on), all other functions/classes dealing with remote files, etc. You programatically build a stack-trace profile of each user- or remote-supplied value. This can be done programatically by getting all repeat instances of the assigned variable and functions or methods it's used in, then recursively compiling a list of all occurrences of those functions/methods, and so on. Examine it to ensure it first goes through the proper filtering and validating functions relative to all other functions it touches. This is of course a manual examination, otherwise you'll have a total number of case switches equal to the number of functions and methods in PHP (including user defined).

Alternatively for handling only user input, have a static controller class initialized at the beginning of all scripts which 1) validates and stores all user-supplied input values against a white-list of allowed purposes; 2) wipes that input source (ie $_SERVER = null). You can see where this gets a little Naziesque.

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

How to join a slice of strings into a single string?

This is still relevant in 2018.

To String

import strings
stringFiles := strings.Join(fileSlice[:], ",")

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")

How to display .svg image using swift

You can use SVGKit for example.

1) Integrate it according to instructions. Drag&dropping the .framework file is fast and easy.

2) Make sure you have an Objective-C to Swift bridge file bridging-header.h with import code in it:

#import <SVGKit/SVGKit.h>
#import <SVGKit/SVGKImage.h>

3) Use the framework like this, assuming that dataFromInternet is NSData, previously downloaded from network:

let anSVGImage: SVGKImage = SVGKImage(data: dataFromInternet)
myIUImageView.image = anSVGImage.UIImage

The framework also allows to init an SVGKImage from other different sources, for example it can download image for you when you provide it with URL. But in my case it was crashing in case of unreachable url, so it turned out to be better to manage networking by myself. More info on it here.

Get UserDetails object from Security Context in Spring MVC controller

That's another solution (Spring Security 3):

public String getLoggedUser() throws Exception {
    String name = SecurityContextHolder.getContext().getAuthentication().getName();
    return (!name.equals("anonymousUser")) ? name : null;
}

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

How can I expose more than 1 port with Docker?

Use this as an example:

docker create --name new_ubuntu -it -p 8080:8080 -p  15672:15672 -p 5432:5432   ubuntu:latest bash

look what you've created(and copy its CONTAINER ID xxxxx):

docker ps -a 

now write the miracle maker word(start):

docker start xxxxx

good luck

What is the shortest function for reading a cookie by name in JavaScript?

this in an object that you can read, write, overWrite and delete cookies.

var cookie = {
    write : function (cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    },
    read : function (name) {
        if (document.cookie.indexOf(name) > -1) {
            return document.cookie.split(name)[1].split("; ")[0].substr(1)
        } else {
            return "";
        }
    },
    delete : function (cname) {
        var d = new Date();
        d.setTime(d.getTime() - 1000);
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=; " + expires;
    }
};

Java OCR implementation

There are a variety of OCR libraries out there. However, my experience is that the major commercial implementations, ABBYY, Omnipage, and ReadIris, far outdo the open-source or other minor implementations. These commercial libraries are not primarily designed to work with Java, though of course it is possible.

Of course, if your interest is to learn the code, the open-source implementations will do the trick.

How to add smooth scrolling to Bootstrap's scroll spy function

What onetrickpony posted is okay, but if you want to have a more general solution, you can just use the code below.

Instead of selecting just the id of the anchor, you can make it bit more standard-like and just selecting the attribute name of the <a>-Tag. This will save you from writing an extra id tag. Just add the smoothscroll class to the navbar element.

What changed

1) $('#nav ul li a[href^="#"]') to $('#nav.smoothscroll ul li a[href^="#"]')

2) $(this.hash) to $('a[name="' + this.hash.replace('#', '') + '"]')

Final Code

/* Enable smooth scrolling on all links with anchors */
$('#nav.smoothscroll ul li a[href^="#"]').on('click', function(e) {

  // prevent default anchor click behavior
  e.preventDefault();

  // store hash
  var hash = this.hash;

  // animate
  $('html, body').animate({
    scrollTop: $('a[name="' + this.hash.replace('#', '') + '"]').offset().top
  }, 300, function(){

    // when done, add hash to url
    // (default click behaviour)
    window.location.hash = hash;

  });
});

Where can I find the assembly System.Web.Extensions dll?

EDIT:

The info below is only applicable to VS2008 and the 3.5 framework. VS2010 has a new registry location. Further details can be found on MSDN: How to Add or Remove References in Visual Studio.

ORIGINAL

It should be listed in the .NET tab of the Add Reference dialog. Assemblies that appear there have paths in registry keys under:

HKLM\Software\Microsoft\.NETFramework\AssemblyFolders\

I have a key there named Microsoft .NET Framework 3.5 Reference Assemblies with a string value of:

C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\

Navigating there I can see the actual System.Web.Extensions dll.

EDIT:

I found my .NET 4.0 version in:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.Extensions.dll

I'm running Win 7 64 bit, so if you're on a 32 bit OS drop the (x86).

Best way to style a TextBox in CSS

You could target all text boxes with input[type=text] and then explicitly define the class for the textboxes who need it.

You can code like below :

_x000D_
_x000D_
input[type=text] {_x000D_
  padding: 0;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  outline: none;_x000D_
  border: 1px solid #cdcdcd;_x000D_
  border-color: rgba(0, 0, 0, .15);_x000D_
  background-color: white;_x000D_
  font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
  width: 526px;_x000D_
  margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
_x000D_
_x000D_

CardView background color always white

Kotlin for XML

app:cardBackgroundColor="@android:color/red"

code

cardName.setCardBackgroundColor(ContextCompat.getColor(this, R.color.colorGray));

Apply function to all elements of collection through LINQ

A common way to approach this is to add your own ForEach generic method on IEnumerable<T>. Here's the one we've got in MoreLINQ:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    source.ThrowIfNull("source");
    action.ThrowIfNull("action");
    foreach (T element in source)
    {
        action(element);
    }
}

(Where ThrowIfNull is an extension method on any reference type, which does the obvious thing.)

It'll be interesting to see if this is part of .NET 4.0. It goes against the functional style of LINQ, but there's no doubt that a lot of people find it useful.

Once you've got that, you can write things like:

people.Where(person => person.Age < 21)
      .ForEach(person => person.EjectFromBar());

Can .NET load and parse a properties file equivalent to Java Properties class?

C# generally uses xml-based config files rather than the *.ini-style file like you said, so there's nothing built-in to handle this. However, google returns a number of promising results.

What is the best data type to use for money in C#?

Decimal. If you choose double you're leaving yourself open to rounding errors

Display a tooltip over a button using Windows Forms

Sure, just handle the mousehover event and tell it to display a tool tip. t is a tooltip defined either in the globals or in the constructor using:

ToolTip t = new ToolTip();

then the event handler:

private void control_MouseHover(object sender, EventArgs e)
{
  t.Show("Text", (Control)sender);
}

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

If you use mod_rewrite to hide the extension of your scripts, or if you just like pretty URLs that end in /, then you might want to approach this from the other direction. Tell nginx to let anything with a non-static extension to go through to apache. For example:

location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
{
    root   /path/to/static-content;
}

location ~* ^!.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

I found the first part of this snippet over at: http://code.google.com/p/scalr/wiki/NginxStatic

How to get the month name in C#?

If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime

//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);

how to convert long date value to mm/dd/yyyy format

Refer Below code which give the date in String form.

import java.text.SimpleDateFormat;
import java.util.Date;



public class Test{

    public static void main(String[] args) {
        long val = 1346524199000l;
        Date date=new Date(val);
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        String dateText = df2.format(date);
        System.out.println(dateText);
    }
}

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

How to bind a List<string> to a DataGridView control?

Try this :

//i have a 
List<string> g_list = new List<string>();

//i put manually the values... (for this example)
g_list.Add("aaa");
g_list.Add("bbb");
g_list.Add("ccc");

//for each string add a row in dataGridView and put the l_str value...
foreach (string l_str in g_list)
{
    dataGridView1.Rows.Add(l_str);
}

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

  1. Declare the variable
  2. Set it by your command and add dynamic parts like use parameter values of sp(here @IsMonday and @IsTuesday are sp params)
  3. execute the command

    declare  @sql varchar (100)
    set @sql ='select * from #td1'
    
    if (@IsMonday+@IsTuesday !='')
    begin
    set @sql= @sql+' where PickupDay in ('''+@IsMonday+''','''+@IsTuesday+''' )'
    end
    exec( @sql)
    

How do I add indices to MySQL tables?

Indexes of two types can be added: when you define a primary key, MySQL will take it as index by default.

Explanation

Primary key as index

Consider you have a tbl_student table and you want student_id as primary key:

ALTER TABLE `tbl_student` ADD PRIMARY KEY (`student_id`)

Above statement adds a primary key, which means that indexed values must be unique and cannot be NULL.

Specify index name

ALTER TABLE `tbl_student` ADD INDEX student_index (`student_id`)

Above statement will create an ordinary index with student_index name.

Create unique index

ALTER TABLE `tbl_student` ADD UNIQUE student_unique_index (`student_id`)

Here, student_unique_index is the index name assigned to student_id and creates an index for which values must be unique (here null can be accepted).

Fulltext option

ALTER TABLE `tbl_student` ADD FULLTEXT student_fulltext_index (`student_id`)

Above statement will create the Fulltext index name with student_fulltext_index, for which you need MyISAM Mysql Engine.

How to remove indexes ?

DROP INDEX `student_index` ON `tbl_student`

How to check available indexes?

SHOW INDEX FROM `tbl_student`

Gson: How to exclude specific fields from Serialization without annotations

I came up with a class factory to support this functionality. Pass in any combination of either fields or classes you want to exclude.

public class GsonFactory {

    public static Gson build(final List<String> fieldExclusions, final List<Class<?>> classExclusions) {
        GsonBuilder b = new GsonBuilder();
        b.addSerializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                return fieldExclusions == null ? false : fieldExclusions.contains(f.getName());
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return classExclusions == null ? false : classExclusions.contains(clazz);
            }
        });
        return b.create();

    }
}

To use, create two lists (each is optional), and create your GSON object:

static {
 List<String> fieldExclusions = new ArrayList<String>();
 fieldExclusions.add("id");
 fieldExclusions.add("provider");
 fieldExclusions.add("products");

 List<Class<?>> classExclusions = new ArrayList<Class<?>>();
 classExclusions.add(Product.class);
 GSON = GsonFactory.build(null, classExclusions);
}

private static final Gson GSON;

public String getSomeJson(){
    List<Provider> list = getEntitiesFromDatabase();
    return GSON.toJson(list);
}

How to create Gmail filter searching for text only at start of subject line?

Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(

There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.

Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.

With the current search facility brackets of any form () {} [] are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb) and [aaa|bbb] are equivalent and will both find words aaa or bbb. Most other punctuation characters, including \, are treated as a space or a word-separator, + - : and " do have special meaning though, see the help.

As of 2016, only the form "{term1 term2}" is documented for this, and is equivalent to the search "term1 OR term2".

You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor to get the complete source).

You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.

For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected] it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

logout and redirecting session in php

<?php
session_start();
session_destroy();
header("Location: home.php");
?>

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

How to get 0-padded binary representation of an integer in java?

This method converts an int to a String, length=bits. Either padded with 0s or with the most significant bits truncated.

static String toBitString( int x, int bits ){
    String bitString = Integer.toBinaryString(x);
    int size = bitString.length();
    StringBuilder sb = new StringBuilder( bits );
    if( bits > size ){
        for( int i=0; i<bits-size; i++ )
            sb.append('0');
        sb.append( bitString );
    }else
        sb = sb.append( bitString.substring(size-bits, size) );

    return sb.toString();
}

how to concatenate two dictionaries to create a new one in Python?

Here's a one-liner (imports don't count :) that can easily be generalized to concatenate N dictionaries:

Python 3

from itertools import chain
dict(chain.from_iterable(d.items() for d in (d1, d2, d3)))

and:

from itertools import chain
def dict_union(*args):
    return dict(chain.from_iterable(d.items() for d in args))

Python 2.6 & 2.7

from itertools import chain
dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3))

Output:

>>> from itertools import chain
>>> d1={1:2,3:4}
>>> d2={5:6,7:9}
>>> d3={10:8,13:22}
>>> dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
{1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}

Generalized to concatenate N dicts:

from itertools import chain
def dict_union(*args):
    return dict(chain.from_iterable(d.iteritems() for d in args))

I'm a little late to this party, I know, but I hope this helps someone.

How to return a class object by reference in C++?

You can only return non-local objects by reference. The destructor may have invalidated some internal pointer, or whatever.

Don't be afraid of returning values -- it's fast!

Image overlay on responsive sized images bootstrap

Add a class to the containing div, then set the following css on it:

.img-overlay {
    position: relative;
    max-width: 500px; //whatever your max-width should be 
}

position: relative is required on a parent element of children with position: absolute for the children to be positioned in relation to that parent.

DEMO

How to check if any Checkbox is checked in Angular

This is re-post for insert code also. This example included: - One object list - Each object hast child list. Ex:

var list1 = {
    name: "Role A",
    name_selected: false,
    subs: [{
      sub: "Read",
      id: 1,
      selected: false
    }, {
      sub: "Write",
      id: 2,
      selected: false
    }, {
      sub: "Update",
      id: 3,
      selected: false
    }],
  };

I'll 3 list like above and i'll add to a one object list

newArr.push(list1);
  newArr.push(list2);
  newArr.push(list3);

Then i'll do how to show checkbox with multiple group:

$scope.toggleAll = function(item) {
    var toogleStatus = !item.name_selected;
    console.log(toogleStatus);
    angular.forEach(item, function() {
      angular.forEach(item.subs, function(sub) {
        sub.selected = toogleStatus;
      });
    });
  };

  $scope.optionToggled = function(item, subs) {
    item.name_selected = subs.every(function(itm) {
      return itm.selected;
    })
    $scope.txtRet = item.name_selected;
  }

HTML:

<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
      <div>
        <ul>
          <input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)"><span>{{item.name}}</span>
          <div>
            <li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
              <input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
            </li>
          </div>
        </ul>
      </div>
      <span>{{txtRet}}</span>
    </li>

Fiddle: example

how to convert .java file to a .class file

From the command line, run

javac ClassName.java

Get image dimensions

Using getimagesize function, we can also get these properties of that specific image-

<?php

list($width, $height, $type, $attr) = getimagesize("image_name.jpg");

echo "Width: " .$width. "<br />";
echo "Height: " .$height. "<br />";
echo "Type: " .$type. "<br />";
echo "Attribute: " .$attr. "<br />";

//Using array
$arr = array('h' => $height, 'w' => $width, 't' => $type, 'a' => $attr);
?>


Result like this -

Width: 200
Height: 100
Type: 2
Attribute: width='200' height='100'


Type of image consider like -

1 = GIF
2 = JPG
3 = PNG
4 = SWF
5 = PSD
6 = BMP
7 = TIFF(intel byte order)
8 = TIFF(motorola byte order)
9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM

Using WGET to run a cronjob PHP

wget -O- http://www.example.com/cronit.php >> /dev/null

This means send the file to stdout, and send stdout to /dev/null

Does Python's time.time() return the local or UTC timestamp?

time.time() return the unix timestamp. you could use datetime library to get local time or UTC time.

import datetime

local_time = datetime.datetime.now()
print(local_time.strftime('%Y%m%d %H%M%S'))

utc_time = datetime.datetime.utcnow() 
print(utc_time.strftime('%Y%m%d %H%M%S'))

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

try this

var express = require('express');

var mysql     =    require('mysql');

var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
console.log(app);
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "admin123",
  database: "sitepoint"
});

con.connect(function(err){
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});



module.exports = app;

Reading file line by line (with space) in Unix Shell scripting - Issue

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

Multiple modals overlay

Each modal should be given a different id and each link should be targeted to a different modal id. So it should be something like that:

<a href="#myModal" data-toggle="modal">
...
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
...
<a href="#myModal2" data-toggle="modal">
...
<div id="myModal2" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
...

What is the default value for enum variable?

It is whatever member of the enumeration represents the value 0. Specifically, from the documentation:

The default value of an enum E is the value produced by the expression (E)0.

As an example, take the following enum:

enum E
{
    Foo, Bar, Baz, Quux
}

Without overriding the default values, printing default(E) returns Foo since it's the first-occurring element.

However, it is not always the case that 0 of an enum is represented by the first member. For example, if you do this:

enum F
{
    // Give each element a custom value
    Foo = 1, Bar = 2, Baz = 3, Quux = 0
}

Printing default(F) will give you Quux, not Foo.

If none of the elements in an enum G correspond to 0:

enum G
{
    Foo = 1, Bar = 2, Baz = 3, Quux = 4
}

default(G) returns literally 0, although its type remains as G (as quoted by the docs above, a cast to the given enum type).

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

So I figured out a way to do this effectively. For my particular project I'm building an iPad website so I knew exactly what the pixel X/Y value would be to reach the edge of the screen. Your thisX and thisY values will vary.

Since the popovers are being placed by inline styling anyway, I simply grab the left and top values for each link to decide which direction the popover should be. This is done by appending html5 data- values that .popover() uses upon execution.

if ($('.infopoint').length>0){
    $('.infopoint').each(function(){
        var thisX = $(this).css('left').replace('px','');
        var thisY = $(this).css('top').replace('px','');
        if (thisX > 515)
            $(this).attr('data-placement','left');
        if (thisX < 515)
            $(this).attr('data-placement','right');
        if (thisY > 480)
            $(this).attr('data-placement','top');
        if (thisY < 110)
            $(this).attr('data-placement','bottom');
    });
    $('.infopoint').popover({
        trigger:'hover',
        animation: false,
        html: true
    });
}

Any comments/improvements are welcome but this gets the job done if you're willing to put the values in manually.

How is Pythons glob.glob ordered?

Please try this code:

sorted(glob.glob( os.path.join(path, '*.png') ),key=lambda x:float(re.findall("([0-9]+?)\.png",x)[0]))

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

How to break out of nested loops?

You'll need a boolean variable, if you want it readable:

bool broke = false;
for(int i = 0; i < 1000; i++) {
  for(int j = 0; j < 1000; i++) {
    if (condition) {
      broke = true;
      break;
    }
  }
  if (broke)
    break;
}

If you want it less readable you can join the boolean evaluation:

bool broke = false;
for(int i = 0; i < 1000 && !broke; i++) {
  for(int j = 0; j < 1000; i++) {
    if (condition) {
      broke = true;
      break;
    }
  }
}

As an ultimate way you can invalidate the initial loop:

for(int i = 0; i < size; i++) {
  for(int j = 0; j < 1000; i++) {
    if (condition) {
      i = size;
      break;
    }
  }
}

CORS: credentials mode is 'include'

Just add Axios.defaults.withCredentials=true instead of ({credentials: true}) in client side, and change app.use(cors()) to

app.use(cors(
  {origin: ['your client side server'],
  methods: ['GET', 'POST'],
  credentials:true,
}
))

Split string into string array of single characters

Strings in C# already have a char indexer

string test = "this is a test";
Console.WriteLine(test[0]);

And...

if(test[0] == 't')
  Console.WriteLine("The first letter is 't'");

This works too...

Console.WriteLine("this is a test"[0]);

And this...

foreach (char c in "this is a test")
  Console.WriteLine(c);

EDIT:

I noticed the question was updated with regards to char[] arrays. If you must have a string[] array, here's how you split a string at each character in c#:

string[] test = Regex.Split("this is a test", string.Empty);

foreach (string s in test)
{
  Console.WriteLine(s);
}

HTTP Get with 204 No Content: Is that normal

I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.

GET /items
    200: ["a", "b", null]

GET /items/0
    200: "a"

GET /items/1
    200: "b"

GET /items/2
    204:

GET /items/3
    404: Not Found

How to check if a column is empty or null using SQL query select statement?

Here is my preferred way to check for "if null or empty":

SELECT * 
FROM UserProfile 
WHERE PropertydefinitionID in (40, 53) 
AND NULLIF(PropertyValue, '') is null

Since it modifies the search argument (SARG) it might have performance issues because it might not use an existing index on the PropertyValue column.

Press enter in textbox to and execute button command

If buttonSearch has no code, and only action is to return dialog result then:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            DialogResult = DialogResult.OK;
    }

Reading and writing value from a textfile by using vbscript code

This script will read lines from large file and write to new small files. Will duplicate the header of the first line (Header) to all child files

Dim strLine
lCounter = 1
fCounter = 1
cPosition = 1
MaxLine = 1000
splitAt = MaxLine
Dim fHeader
sFile = "inputFile.txt"
dFile = LEFT(sFile, (LEN(sFile)-4))& "_0" & fCounter & ".txt"
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(sFile,1)
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
do while not objFileToRead.AtEndOfStream
        strLine = objFileToRead.ReadLine()
        objFileToWrite.WriteLine(strLine)
        If cPosition = 1 Then
            fHeader = strLine
        End If
        If cPosition = splitAt Then
            fCounter = fCounter + 1
            splitAt = splitAt + MaxLine
            objFileToWrite.Close
            Set objFileToWrite = Nothing
            If fCounter < 10 Then
                dFile=LEFT(dFile, (LEN(dFile)-5))& fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            ElseIf fCounter <100 Or fCounter = 100 Then
                dFile=LEFT(dFile, (LEN(dFile)-6))& fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            Else
                dFile=LEFT(dFile, (LEN(dFile)-7)) & fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            End If
        End If
        lCounter=lCounter + 1
        cPosition=cPosition + 1
Loop
objFileToWrite.Close
Set objFileToWrite = Nothing
objFileToRead.Close
Set objFileToRead = Nothing

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\ is an escape character in Python. \t gets interpreted as a tab. If you need \ character in a string, you have to use \\.

Your code should be:
test_file=open('c:\\Python27\\test.txt','r')

What is the difference between "INNER JOIN" and "OUTER JOIN"?

You use INNER JOIN to return all rows from both tables where there is a match. i.e. In the resulting table all the rows and columns will have values.

In OUTER JOIN the resulting table may have empty columns. Outer join may be either LEFT or RIGHT.

LEFT OUTER JOIN returns all the rows from the first table, even if there are no matches in the second table.

RIGHT OUTER JOIN returns all the rows from the second table, even if there are no matches in the first table.

How to convert a char to a String?

Use any of the following:

String str = String.valueOf('c');
String str = Character.toString('c');
String str = 'c' + "";

How to make Twitter bootstrap modal full screen

The following class will make a full-screen modal in Bootstrap:

.full-screen {
    width: 100%;
    height: 100%;
    margin: 0;
    top: 0;
    left: 0;
}

I'm not sure how the inner content of your modal is structured, this may have an effect on the overall height depending on the CSS that is associated with it.

How do I prevent DIV tag starting a new line?

use float:left on the div and the link, or use a span.

What's the Use of '\r' escape sequence?

The program is printing "Hey this is my first hello world ", then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

None of the above worked for me and i was trouble shooting using a support page(https://support.microsoft.com/en-us/help/942051/error-message-when-a-user-visits-a-website-that-is-hosted-on-a-server)then i compared the application host file with one of the working copy and seems like i was missing a bunch of handlers and when i added back those into application host its start working. I was missing all these,

<add name="xamlx-ISAPI-4.0_64bit" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" />
<add name="xamlx-ISAPI-4.0_32bit" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" />
<add name="xamlx-Integrated-4.0" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" type="System.Xaml.Hosting.XamlHttpHandlerFactory, System.Xaml.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="rules-ISAPI-4.0_64bit" path="*.rules" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" />
<add name="rules-ISAPI-4.0_32bit" path="*.rules" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" />
<add name="rules-Integrated-4.0" path="*.rules" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="xoml-ISAPI-4.0_64bit" path="*.xoml" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" />
<add name="xoml-ISAPI-4.0_32bit" path="*.xoml" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" />
<add name="xoml-Integrated-4.0" path="*.xoml" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="svc-ISAPI-4.0_64bit" path="*.svc" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" />
<add name="svc-ISAPI-4.0_32bit" path="*.svc" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" />
<add name="svc-Integrated-4.0" path="*.svc" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="rules-64-ISAPI-2.0" path="*.rules" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" />
<add name="rules-ISAPI-2.0" path="*.rules" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness32" />
<add name="rules-Integrated" path="*.rules" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="integratedMode,runtimeVersionv2.0" />
<add name="xoml-64-ISAPI-2.0" path="*.xoml" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" />
<add name="xoml-ISAPI-2.0" path="*.xoml" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness32" />
<add name="xoml-Integrated" path="*.xoml" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="integratedMode,runtimeVersionv2.0" />
<add name="svc-ISAPI-2.0-64" path="*.svc" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" />
<add name="svc-ISAPI-2.0" path="*.svc" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness32" />
<add name="svc-Integrated" path="*.svc" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="integratedMode,runtimeVersionv2.0" />

How to set background image in Java?

Or try this ;)

try {
  this.setContentPane(
    new JLabel(new ImageIcon(ImageIO.read(new File("your_file.jpeg")))));
} catch (IOException e) {};

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

Get client IP address via third party web service

A more reliable REST endpoint would be http://freegeoip.net/json/

Returns the ip address along with the geo-location too. Also has cross-domain requests enabled (Access-Control-Allow-Origin: *) so you don't have to code around JSONP.

Change input value onclick button - pure javascript or jQuery

This will work fine for you

   <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script>
    function myfun(){
    $(document).ready(function(){

        $("#select").click(
        function(){
        var data=$("#select").val();
            $("#disp").val(data);
                            });
    });
    }
    </script>
    </head>
    <body>
    <p>id <input type="text" name="user" id="disp"></p>
    <select id="select" onclick="myfun()">
    <option name="1"value="one">1</option>
    <option name="2"value="two">2</option>
    <option name="3"value="three"></option>
    </select>
    </body>
    </html>

Using CSS :before and :after pseudo-elements with inline CSS?

You can use the data in inline

 <style>   
 td { text-align: justify; }
 td:after { content: attr(data-content); display: inline-block; width: 100%; }
</style>

<table><tr><td data-content="post"></td></tr></table>

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...

UPDATE:

Apparently this syntax is only available starting on SQL Server 2008.

"Faceted Project Problem (Java Version Mismatch)" error message

You have two options to fix the issue:

1- Manually make sure the two versions match.
2- Use the IDE's help as follows:
- Right mouse click on the error in the 'Problems' view
- Select the 'Quick Fix' menu item from the pop-up menu
- Select the right compiler level in the provided dialog and click 'Finish'.

Taken from Eclipse: Java compiler level and project facet mismatch

Also gives location of where you can access the Java compiler and facet version.

Understanding .get() method in Python

I see this is a fairly old question, but this looks like one of those times when something's been written without knowledge of a language feature. The collections library exists to fulfill these purposes.

from collections import Counter
letter_counter = Counter()
for letter in 'The quick brown fox jumps over the lazy dog':
    letter_counter[letter] += 1

>>> letter_counter
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 'T': 1, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})

In this example the spaces are being counted, obviously, but whether or not you want those filtered is up to you.

As for the dict.get(a_key, default_value), there have been several answers to this particular question -- this method returns the value of the key, or the default_value you supply. The first argument is the key you're looking for, the second argument is the default for when that key is not present.

Text overwrite in visual studio 2010

None of the solutions above were working for me. My workaround was to open the on-screen keyboard using the system settings (press Windows key and search for "keyboard" to find them). Once that's open you can click the Insert key on it.

What is jQuery Unobtrusive Validation?

jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

As the creator of ElasticSearch, maybe I can give you some reasoning on why I went ahead and created it in the first place :).

Using pure Lucene is challenging. There are many things that you need to take care for if you want it to really perform well, and also, its a library, so no distributed support, it's just an embedded Java library that you need to maintain.

In terms of Lucene usability, way back when (almost 6 years now), I created Compass. Its aim was to simplify using Lucene and make everyday Lucene simpler. What I came across time and time again is the requirement to be able to have Compass distributed. I started to work on it from within Compass, by integrating with data grid solutions like GigaSpaces, Coherence, and Terracotta, but it's not enough.

At its core, a distributed Lucene solution needs to be sharded. Also, with the advancement of HTTP and JSON as ubiquitous APIs, it means that a solution that many different systems with different languages can easily be used.

This is why I went ahead and created ElasticSearch. It has a very advanced distributed model, speaks JSON natively, and exposes many advanced search features, all seamlessly expressed through JSON DSL.

Solr is also a solution for exposing an indexing/search server over HTTP, but I would argue that ElasticSearch provides a much superior distributed model and ease of use (though currently lacking on some of the search features, but not for long, and in any case, the plan is to get all Compass features into ElasticSearch). Of course, I am biased, since I created ElasticSearch, so you might need to check for yourself.

As for Sphinx, I have not used it, so I can't comment. What I can refer you is to this thread at Sphinx forum which I think proves the superior distributed model of ElasticSearch.

Of course, ElasticSearch has many more features than just being distributed. It is actually built with a cloud in mind. You can check the feature list on the site.

Show MySQL host via SQL Command

show variables where Variable_name='hostname'; 

That could help you !!

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

Python - How to convert JSON File to Dataframe

There are 2 inputs you might have and you can also convert between them.

  1. input: listOfDictionaries --> use @VikashSingh solution

example: [{"":{"...

The pd.DataFrame() needs a listOfDictionaries as input.

  1. input: jsonStr --> use @JustinMalinchak solution

example: '{"":{"...

If you have jsonStr, you need an extra step to listOfDictionaries first. This is obvious as it is generated like:

jsonStr = json.dumps(listOfDictionaries)

Thus, switch back from jsonStr to listOfDictionaries first:

listOfDictionaries = json.loads(jsonStr)

How to Make Laravel Eloquent "IN" Query?

Here is how you do in Eloquent

$users = User::whereIn('id', array(1, 2, 3))->get();

And if you are using Query builder then :

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

How to create a drop shadow only on one side of an element?

I think this is what you're after?

_x000D_
_x000D_
.shadow {_x000D_
  -webkit-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
  -moz-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
  box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
}
_x000D_
<div class="shadow">wefwefwef</div>
_x000D_
_x000D_
_x000D_

What should I use to open a url instead of urlopen in urllib3

You should use urllib.reuqest, not urllib3.

import urllib.request   # not urllib - important!
urllib.request.urlopen('https://...')

Warning about SSL connection when connecting to MySQL database

Since I am currently in development mode I set useSSL to No not in tomcat but in mysql server configurations. Went to Manage Access Settings\Manage Server Connections from workbench -> Selected my connection. Inside connection tab went to SSL tab and disabled the settings. Worked for me.

get jquery `$(this)` id

Do you mean that for a select element with an id of "next" you need to perform some specific script?

$("#next").change(function(){
    //enter code here
});

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

How to check if a file exists before creating a new file

The easiest way to do this is using ios :: noreplace.

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

PHP/regex: How to get the string value of HTML tag?

$userinput = "http://www.example.vn/";
//$url = urlencode($userinput);
$input = @file_get_contents($userinput) or die("Could not access file: $userinput");
$regexp = "<tagname\s[^>]*>(.*)<\/tagname>";
//==Example:
//$regexp = "<div\s[^>]*>(.*)<\/div>";

if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) {
    foreach($matches as $match) {
        // $match[2] = link address 
        // $match[3] = link text
    }
}

How to copy files from host to Docker container?

Try docker cp.

Usage:

docker cp CONTAINER:PATH HOSTPATH

It copies files/folders from PATH to the HOSTPATH.

Horizontal list items

You could also use inline blocks to avoid floating elements

<ul>
    <li>
        <a href="#">some item</a>
    </li>
    <li>
        <a href="#">another item</a>
   </li>
</ul>

and then style as:

li{
    /* with fix for IE */
    display:inline;
    display:inline-block;
    zoom:1;
    /*
    additional styles to make it look nice
    */
 }

that way you wont need to float anything, eliminating the need for clearfixes

How do you make strings "XML safe"?

Since PHP 5.4 you can use:

htmlspecialchars($string, ENT_XML1);

You should specify the encoding, such as:

htmlspecialchars($string, ENT_XML1, 'UTF-8');

Update

Note that the above will only convert:

  • & to &amp;
  • < to &lt;
  • > to &gt;

If you want to escape text for use in an attribute enclosed in double quotes:

htmlspecialchars($string, ENT_XML1 | ENT_COMPAT, 'UTF-8');

will convert " to &quot; in addition to &, < and >.


And if your attributes are enclosed in single quotes:

htmlspecialchars($string, ENT_XML1 | ENT_QUOTES, 'UTF-8');

will convert ' to &apos; in addition to &, <, > and ".

(Of course you can use this even outside of attributes).


See the manual entry for htmlspecialchars.

When to use: Java 8+ interface default method, vs. abstract method

As mentioned in other answers, the ability to add implementation to an interface was added in order to provide backward compatibility in the Collections framework. I would argue that providing backward compatibility is potentially the only good reason for adding implementation to an interface.

Otherwise, if you add implementation to an interface, you are breaking the fundamental law for why interfaces were added in the first place. Java is a single inheritance language, unlike C++ which allows for multiple inheritance. Interfaces provide the typing benefits that come with a language that supports multiple inheritance without introducing the problems that come with multiple inheritance.

More specifically, Java only allows single inheritance of an implementation, but it does allow multiple inheritance of interfaces. For example, the following is valid Java code:

class MyObject extends String implements Runnable, Comparable { ... }

MyObject inherits only one implementation, but it inherits three contracts.

Java passed on multiple inheritance of implementation because multiple inheritance of implementation comes with a host of thorny problems, which are outside the scope of this answer. Interfaces were added to allow multiple inheritance of contracts (aka interfaces) without the problems of multiple inheritance of implementation.

To support my point, here is a quote from Ken Arnold and James Gosling from the book The Java Programming Language, 4th edition:

Single inheritance precludes some useful and correct designs. The problems of multiple inheritance arise from multiple inheritance of implementation, but in many cases multiple inheritance is used to inherit a number of abstract contracts and perhaps one concrete implementation. Providing a means to inherit an abstract contract without inheriting an implementation allows the typing benefits of multiple inheritance without the problems of multiple implementation inheritance. The inheritance of an abstract contract is termed interface inheritance. The Java programming language supports interface inheritance by allowing you to declare an interface type

Finish an activity from another activity

  1. Make your activity A in manifest file: launchMode = "singleInstance"

  2. When the user clicks new, do FirstActivity.fa.finish(); and call the new Intent.

  3. When the user clicks modify, call the new Intent or simply finish activity B.

FIRST WAY

In your first activity, declare one Activity object like this,

public static Activity fa;
onCreate()
{
    fa = this;
}

now use that object in another Activity to finish first-activity like this,

onCreate()
{
    FirstActivity.fa.finish();
}

SECOND WAY

While calling your activity FirstActivity which you want to finish as soon as you move on, You can add flag while calling FirstActivity

intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

But using this flag the activity will get finished evenif you want it not to. and sometime onBack if you want to show the FirstActivity you will have to call it using intent.

How to make <input type="file"/> accept only these types?

for powerpoint and pdf files:

<html>
<input type="file" placeholder="Do you have a .ppt?" name="pptfile" id="pptfile" accept="application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/vnd.openxmlformats-officedocument.presentationml.presentation"/>
</html>

How to convert byte[] to InputStream?

Check out java.io.ByteArrayInputStream

Adding system header search path to Xcode

We have two options.

  1. Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.

  2. Set HEADER_SEARCH_PATHS parameter in build settings on project info. I added "${SRCROOT}" here without recursion. This setting works well for most projects.

About 2nd option:

Xcode uses Clang which has GCC compatible command set. GCC has an option -Idir which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS in Xcode project build setting.

However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.

But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}".

Or just use . to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.

The ${SRCROOT} is predefined value by Xcode. This means source directory. You can find more values in Reference document.

PS. Actually you don't have to use braces {}. I get same result with $SRCROOT. If you know the difference, please let me know.

Import regular CSS file in SCSS file?

I figured out an elegant, Rails-like way to do it. First, rename your .scss file to .scss.erb, then use syntax like this (example for highlight_js-rails4 gem CSS asset):

@import "<%= asset_path("highlight_js/github") %>";

Why you can't host the file directly via SCSS:

Doing an @import in SCSS works fine for CSS files as long as you explicitly use the full path one way or another. In development mode, rails s serves assets without compiling them, so a path like this works...

@import "highlight_js/github.css";

...because the hosted path is literally /assets/highlight_js/github.css. If you right-click on the page and "view source", then click on the link for the stylesheet with the above @import, you'll see a line in there that looks like:

@import url(highlight_js/github.css);

The SCSS engine translates "highlight_js/github.css" to url(highlight_js/github.css). This will work swimmingly until you decide to try running it in production where assets are precompiled have a hash injected into the file name. The SCSS file will still resolve to a static /assets/highlight_js/github.css that was not precompiled and doesn't exist in production.

How this solution works:

Firstly, by moving the .scss file to .scss.erb, we have effectively turned the SCSS into a template for Rails. Now, whenever we use <%= ... %> template tags, the Rails template processor will replace these snippets with the output of the code (just like any other template).

Stating asset_path("highlight_js/github") in the .scss.erb file does two things:

  1. Triggers the rake assets:precompile task to precompile the appropriate CSS file.
  2. Generates a URL that appropriately reflects the asset regardless of the Rails environment.

This also means that the SCSS engine isn't even parsing the CSS file; it's just hosting a link to it! So there's no hokey monkey patches or gross workarounds. We're serving a CSS asset via SCSS as intended, and using a URL to said CSS asset as Rails intended. Sweet!

How can I convert a comma-separated string to an array?

I had a similar issue, but more complex as I needed to transform a CSV file into an array of arrays (each line is one array element that inside has an array of items split by comma).

The easiest solution (and more secure I bet) was to use PapaParse which has a "no-header" option that transform the CSV file into an array of arrays, plus, it automatically detected the "," as my delimiter.

Plus, it is registered in Bower, so I only had to:

bower install papa-parse --save

And then use it in my code as follows:

var arrayOfArrays = Papa.parse(csvStringWithEnters), {header:false}).data;

I really liked it.

How to access pandas groupby dataframe by key

gb = df.groupby(['A'])

gb_groups = grouped_df.groups

If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..

gb_groups.keys()

key_list = [key1, key2, key3 and so on...]

for key, values in gb_groups.iteritems():
    if key in key_list:
        print df.ix[values], "\n"

Can you recommend a free light-weight MySQL GUI for Linux?

I really like the MySQL collection of of GUI Tools. They aren't too large or resource hungry.

There are quite a few options here as well. Of the applications presented on that page, I like SQL Buddy - it does require a web server, however.

How to detect if multiple keys are pressed at once using JavaScript?

Note: keyCode is now deprecated.

Multiple keystroke detection is easy if you understand the concept

The way I do it is like this:

var map = {}; // You could also use an array
onkeydown = onkeyup = function(e){
    e = e || event; // to deal with IE
    map[e.keyCode] = e.type == 'keydown';
    /* insert conditional here */
}

This code is very simple: Since the computer only passes one keystroke at a time, an array is created to keep track of multiple keys. The array can then be used to check for one or more keys at once.

Just to explain, let's say you press A and B, each fires a keydown event that sets map[e.keyCode] to the value of e.type == keydown, which evaluates to either true or false. Now both map[65] and map[66] are set to true. When you let go of A, the keyup event fires, causing the same logic to determine the opposite result for map[65] (A), which is now false, but since map[66] (B) is still "down" (it hasn't triggered a keyup event), it remains true.

The map array, through both events, looks like this:

// keydown A 
// keydown B
[
    65:true,
    66:true
]
// keyup A
// keydown B
[
    65:false,
    66:true
]

There are two things you can do now:

A) A Key logger (example) can be created as a reference for later when you want to quickly figure out one or more key codes. Assuming you have defined an html element and pointed to it with the variable element.

element.innerHTML = '';
var i, l = map.length;
for(i = 0; i < l; i ++){
    if(map[i]){
        element.innerHTML += '<hr>' + i;
    }
}

Note: You can easily grab an element by its id attribute.

<div id="element"></div>

This creates an html element that can be easily referenced in javascript with element

alert(element); // [Object HTMLDivElement]

You don't even have to use document.getElementById() or $() to grab it. But for the sake of compatibility, use of jQuery's $() is more widely recommended.

Just make sure the script tag comes after the body of the HTML. Optimization tip: Most big-name websites put the script tag after the body tag for optimization. This is because the script tag blocks further elements from loading until its script is finished downloading. Putting it ahead of the content allows the content to load beforehand.

B (which is where your interest lies) You can check for one or more keys at a time where /*insert conditional here*/ was, take this example:

if(map[17] && map[16] && map[65]){ // CTRL+SHIFT+A
    alert('Control Shift A');
}else if(map[17] && map[16] && map[66]){ // CTRL+SHIFT+B
    alert('Control Shift B');
}else if(map[17] && map[16] && map[67]){ // CTRL+SHIFT+C
    alert('Control Shift C');
}

Edit: That isn't the most readable snippet. Readability's important, so you could try something like this to make it easier on the eyes:

function test_key(selkey){
    var alias = {
        "ctrl":  17,
        "shift": 16,
        "A":     65,
        /* ... */
    };

    return key[selkey] || key[alias[selkey]];
}

function test_keys(){
    var keylist = arguments;

    for(var i = 0; i < keylist.length; i++)
        if(!test_key(keylist[i]))
            return false;

    return true;
}

Usage:

test_keys(13, 16, 65)
test_keys('ctrl', 'shift', 'A')
test_key(65)
test_key('A')

Is this better?

if(test_keys('ctrl', 'shift')){
    if(test_key('A')){
        alert('Control Shift A');
    } else if(test_key('B')){
        alert('Control Shift B');
    } else if(test_key('C')){
        alert('Control Shift C');
    }
}

(end of edit)


This example checks for CtrlShiftA, CtrlShiftB, and CtrlShiftC

It's just as simple as that :)

Notes

Keeping Track of KeyCodes

As a general rule, it is good practice to document code, especially things like Key codes (like // CTRL+ENTER) so you can remember what they were.

You should also put the key codes in the same order as the documentation (CTRL+ENTER => map[17] && map[13], NOT map[13] && map[17]). This way you won't ever get confused when you need to go back and edit the code.

A gotcha with if-else chains

If checking for combos of differing amounts (like CtrlShiftAltEnter and CtrlEnter), put smaller combos after larger combos, or else the smaller combos will override the larger combos if they are similar enough. Example:

// Correct:
if(map[17] && map[16] && map[13]){ // CTRL+SHIFT+ENTER
    alert('Whoa, mr. power user');
}else if(map[17] && map[13]){ // CTRL+ENTER
    alert('You found me');
}else if(map[13]){ // ENTER
    alert('You pressed Enter. You win the prize!')
}

// Incorrect:
if(map[17] && map[13]){ // CTRL+ENTER
    alert('You found me');
}else if(map[17] && map[16] && map[13]){ // CTRL+SHIFT+ENTER
    alert('Whoa, mr. power user');
}else if(map[13]){ // ENTER
    alert('You pressed Enter. You win the prize!');
}
// What will go wrong: When trying to do CTRL+SHIFT+ENTER, it will
// detect CTRL+ENTER first, and override CTRL+SHIFT+ENTER.
// Removing the else's is not a proper solution, either
// as it will cause it to alert BOTH "Mr. Power user" AND "You Found Me"

Gotcha: "This key combo keeps activating even though I'm not pressing the keys"

When dealing with alerts or anything that takes focus from the main window, you might want to include map = [] to reset the array after the condition is done. This is because some things, like alert(), take the focus away from the main window and cause the 'keyup' event to not trigger. For example:

if(map[17] && map[13]){ // CTRL+ENTER
    alert('Oh noes, a bug!');
}
// When you Press any key after executing this, it will alert again, even though you 
// are clearly NOT pressing CTRL+ENTER
// The fix would look like this:

if(map[17] && map[13]){ // CTRL+ENTER
    alert('Take that, bug!');
    map = {};
}
// The bug no longer happens since the array is cleared

Gotcha: Browser Defaults

Here's an annoying thing I found, with the solution included:

Problem: Since the browser usually has default actions on key combos (like CtrlD activates the bookmark window, or CtrlShiftC activates skynote on maxthon), you might also want to add return false after map = [], so users of your site won't get frustrated when the "Duplicate File" function, being put on CtrlD, bookmarks the page instead.

if(map[17] && map[68]){ // CTRL+D
    alert('The bookmark window didn\'t pop up!');
    map = {};
    return false;
}

Without return false, the Bookmark window would pop up, to the dismay of the user.

The return statement (new)

Okay, so you don't always want to exit the function at that point. That's why the event.preventDefault() function is there. What it does is set an internal flag that tells the interpreter to not allow the browser to run its default action. After that, execution of the function continues (whereas return will immediately exit the function).

Understand this distinction before you decide whether to use return false or e.preventDefault()

event.keyCode is deprecated

User SeanVieira pointed out in the comments that event.keyCode is deprecated.

There, he gave an excellent alternative: event.key, which returns a string representation of the key being pressed, like "a" for A, or "Shift" for Shift.

I went ahead and cooked up a tool for examining said strings.

element.onevent vs element.addEventListener

Handlers registered with addEventListener can be stacked, and are called in the order of registration, while setting .onevent directly is rather aggressive and overrides anything you previously had.

document.body.onkeydown = function(ev){
    // do some stuff
    ev.preventDefault(); // cancels default actions
    return false; // cancels this function as well as default actions
}

document.body.addEventListener("keydown", function(ev){
    // do some stuff
    ev.preventDefault() // cancels default actions
    return false; // cancels this function only
});

The .onevent property seems to override everything and the behavior of ev.preventDefault() and return false; can be rather unpredictable.

In either case, handlers registered via addEventlistener seem to be easier to write and reason about.

There is also attachEvent("onevent", callback) from Internet Explorer's non-standard implementation, but this is beyond deprecated and doesn't even pertain to JavaScript (it pertains to an esoteric language called JScript). It would be in your best interest to avoid polyglot code as much as possible.

A helper class

To address confusion/complaints, I've written a "class" that does this abstraction (pastebin link):

function Input(el){
    var parent = el,
        map = {},
        intervals = {};
    
    function ev_kdown(ev)
    {
        map[ev.key] = true;
        ev.preventDefault();
        return;
    }
    
    function ev_kup(ev)
    {
        map[ev.key] = false;
        ev.preventDefault();
        return;
    }
    
    function key_down(key)
    {
        return map[key];
    }

    function keys_down_array(array)
    {
        for(var i = 0; i < array.length; i++)
            if(!key_down(array[i]))
                return false;

        return true;
    }
    
    function keys_down_arguments()
    {
        return keys_down_array(Array.from(arguments));
    }
    
    function clear()
    {
        map = {};
    }
    
    function watch_loop(keylist, callback)
    {
        return function(){
            if(keys_down_array(keylist))
                callback();
        }
    }

    function watch(name, callback)
    {
        var keylist = Array.from(arguments).splice(2);

        intervals[name] = setInterval(watch_loop(keylist, callback), 1000/24);
    }

    function unwatch(name)
    {
        clearInterval(intervals[name]);
        delete intervals[name];
    }

    function detach()
    {
        parent.removeEventListener("keydown", ev_kdown);
        parent.removeEventListener("keyup", ev_kup);
    }
    
    function attach()
    {
        parent.addEventListener("keydown", ev_kdown);
        parent.addEventListener("keyup", ev_kup);
    }
    
    function Input()
    {
        attach();

        return {
            key_down: key_down,
            keys_down: keys_down_arguments,
            watch: watch,
            unwatch: unwatch,
            clear: clear,
            detach: detach
        };
    }
    
    return Input();
}

This class doesn't do everything and it won't handle every conceivable use case. I'm not a library guy. But for general interactive use it should be fine.

To use this class, create an instance and point it to the element you want to associate keyboard input with:

var input_txt = Input(document.getElementById("txt"));

input_txt.watch("print_5", function(){
    txt.value += "FIVE ";
}, "Control", "5");

What this will do is attach a new input listener to the element with #txt (let's assume it's a textarea), and set a watchpoint for the key combo Ctrl+5. When both Ctrl and 5 are down, the callback function you passed in (in this case, a function that adds "FIVE " to the textarea) will be called. The callback is associated with the name print_5, so to remove it, you simply use:

input_txt.unwatch("print_5");

To detach input_txt from the txt element:

input_txt.detach();

This way, garbage collection can pick up the object (input_txt), should it be thrown away, and you won't have an old zombie event listener left over.

For thoroughness, here is a quick reference to the class's API, presented in C/Java style so you know what they return and what arguments they expect.

Boolean  key_down (String key);

Returns true if key is down, false otherwise.

Boolean  keys_down (String key1, String key2, ...);

Returns true if all keys key1 .. keyN are down, false otherwise.

void     watch (String name, Function callback, String key1, String key2, ...);

Creates a "watchpoint" such that pressing all of keyN will trigger the callback

void     unwatch (String name);

Removes said watchpoint via its name

void     clear (void);

Wipes the "keys down" cache. Equivalent to map = {} above

void     detach (void);

Detaches the ev_kdown and ev_kup listeners from the parent element, making it possible to safely get rid of the instance

Update 2017-12-02 In response to a request to publish this to github, I have created a gist.

Update 2018-07-21 I've been playing with declarative style programming for a while, and this way is now my personal favorite: fiddle, pastebin

Generally, it'll work with the cases you would realistically want (ctrl, alt, shift), but if you need to hit, say, a+w at the same time, it wouldn't be too difficult to "combine" the approaches into a multi-key-lookup.


I hope this thoroughly explained answer mini-blog was helpful :)

REACT - toggle class onclick

You can also do this with hooks.

function MyComponent (props) {
  const [isActive, setActive] = useState(false);

  const toggleClass = () => {
    setActive(!isActive);
  };

  return (
    <div 
      className={isActive ? 'your_className': null} 
      onClick={toggleClass} 
    >
      <p>{props.text}</p>
    </div>
   );
}  

How to connect to Mysql Server inside VirtualBox Vagrant?

Make sure MySQL binds to 0.0.0.0 and not 127.0.0.1 or it will not be accessible from outside the machine

You can ensure this by editing your my.conf file and looking for the bind-address item--you want it to look like bind-address = 0.0.0.0. Then save this and restart mysql:

sudo service mysql restart

If you are doing this on a production server, you want to be aware of the security implications, discussed here: https://serverfault.com/questions/257513/how-bad-is-setting-mysqls-bind-address-to-0-0-0-0

TypeError: unsupported operand type(s) for -: 'str' and 'int'

For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

@ variables in Ruby on Rails

@ variables are instance variables, without are local variables.

Read more at http://ruby.about.com/od/variables/a/Instance-Variables.htm

How to recover a dropped stash in Git?

Why do people ask this question? Because they don't yet know about or understand the reflog.

Most answers to this question give long commands with options almost nobody will remember. So people come into this question and copy paste whatever they think they need and forget it almost immediately after.

I would advise everyone with this question to just check the reflog (git reflog), not much more than that. Once you see that list of all commits there are a hundred ways to find out what commit you're looking for and to cherry-pick it or create a branch from it. In the process you'll have learned about the reflog and useful options to various basic git commands.

How to append rows in a pandas dataframe in a for loop?

Suppose your data looks like this:

import pandas as pd
import numpy as np

np.random.seed(2015)
df = pd.DataFrame([])
for i in range(5):
    data = dict(zip(np.random.choice(10, replace=False, size=5),
                    np.random.randint(10, size=5)))
    data = pd.DataFrame(data.items())
    data = data.transpose()
    data.columns = data.iloc[0]
    data = data.drop(data.index[[0]])
    df = df.append(data)
print('{}\n'.format(df))
# 0   0   1   2   3   4   5   6   7   8   9
# 1   6 NaN NaN   8   5 NaN NaN   7   0 NaN
# 1 NaN   9   6 NaN   2 NaN   1 NaN NaN   2
# 1 NaN   2   2   1   2 NaN   1 NaN NaN NaN
# 1   6 NaN   6 NaN   4   4   0 NaN NaN NaN
# 1 NaN   9 NaN   9 NaN   7   1   9 NaN NaN

Then it could be replaced with

np.random.seed(2015)
data = []
for i in range(5):
    data.append(dict(zip(np.random.choice(10, replace=False, size=5),
                         np.random.randint(10, size=5))))
df = pd.DataFrame(data)
print(df)

In other words, do not form a new DataFrame for each row. Instead, collect all the data in a list of dicts, and then call df = pd.DataFrame(data) once at the end, outside the loop.

Each call to df.append requires allocating space for a new DataFrame with one extra row, copying all the data from the original DataFrame into the new DataFrame, and then copying data into the new row. All that allocation and copying makes calling df.append in a loop very inefficient. The time cost of copying grows quadratically with the number of rows. Not only is the call-DataFrame-once code easier to write, it's performance will be much better -- the time cost of copying grows linearly with the number of rows.

inherit from two classes in C#

Use composition:

class ClassC
{
    public ClassA A { get; set; }
    public ClassB B { get; set; }   

    public C (ClassA  a, ClassB  b)
    {
        this.A = a;
        this.B = b;
    }
}

Then you can call C.A.DoA(). You also can change the properties to an interface or abstract class, like public InterfaceA A or public AbstractClassA A.

Nested JSON objects - do I have to use arrays for everything?

You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.

use each() wrap within another each() until the last array.

for result.data[0].stuff[0].onetype[0] in jQuery you could do the following:

`

$.each(data.result.data, function(index0, v) {
    $.each(v, function (index1, w) {
        $.each(w, function (index2, x) {
            alert(x.id);
        });
    });

});

`

Where is Android Studio layout preview?

If you want to see the live preview, in the right part of the screen you should have a button call Preview that show/hide the live preview.

If what you want is to use the WYSISYG editor mode, in the bottom of the editor there is a tab that switch between XML mode and WYSISYG mode.

This works in the same way both in IntelliJ and Android Studio.

How to exclude a directory in find . command

The -path -prune approach also works with wildcards in the path. Here is a find statement that will find the directories for a git server serving multiple git repositiories leaving out the git internal directories:

find . -type d \
   -not \( -path */objects -prune \) \
   -not \( -path */branches -prune \) \
   -not \( -path */refs -prune \) \
   -not \( -path */logs -prune \) \
   -not \( -path */.git -prune \) \
   -not \( -path */info -prune \) \
   -not \( -path */hooks -prune \)  

How to create a global variable?

From the official Swift programming guide:

Global variables are variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily.

You can define it in any file and can access it in current module anywhere. So you can define it somewhere in the file outside of any scope. There is no need for static and all global variables are computed lazily.

 var yourVariable = "someString"

You can access this from anywhere in the current module.

However you should avoid this as Global variables are not good for application state and mainly reason of bugs.

As shown in this answer, in Swift you can encapsulate them in struct and can access anywhere. You can define static variables or constant in Swift also. Encapsulate in struct

struct MyVariables {
    static var yourVariable = "someString"
}

You can use this variable in any class or anywhere

let string = MyVariables.yourVariable
println("Global variable:\(string)")

//Changing value of it
MyVariables.yourVariable = "anotherString"

Set selected item of spinner programmatically

If you have a list of contacts the you can go for this:

((Spinner) view.findViewById(R.id.mobile)).setSelection(spinnerContactPersonDesignationAdapter.getPosition(schoolContact.get(i).getCONT_DESIGNATION()));

Sending email with PHP from an SMTP server

<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "[email protected]");

$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = [email protected]";

$headers = "From: [email protected]";

mail("[email protected]", "Testing", $message, $headers);
echo "Check your email now....&lt;BR/>";
?>

or, for more details, read on.

How to connect to Oracle 11g database remotely

You will need to run the lsnrctl utility on server A to start the listener. You would then connect from computer B using the following syntax:

sqlplus username/password@hostA:1521 /XE

The port information is optional if the default of 1521 is used.

Listener configuration documentation here. Remote connection documentation here.

How to place the ~/.composer/vendor/bin directory in your PATH?

this is what I added in my .bashrc file and worked.

export PATH="$PATH:/home/myUsername/.composer/vendor/bin"

How to set default values in Rails?

You can also try change_column_default in your migrations (tested in Rails 3.2.8):

class SetDefault < ActiveRecord::Migration
  def up
    # Set default value
    change_column_default :people, :last_name, "Smith"
  end

  def down
    # Remove default
    change_column_default :people, :last_name, nil
  end
end

change_column_default Rails API docs

Multiple files upload (Array) with CodeIgniter 2.0

I finally managed to make it work with your help!

Here's my code:

 function do_upload()
{       
    $this->load->library('upload');

    $files = $_FILES;
    $cpt = count($_FILES['userfile']['name']);
    for($i=0; $i<$cpt; $i++)
    {           
        $_FILES['userfile']['name']= $files['userfile']['name'][$i];
        $_FILES['userfile']['type']= $files['userfile']['type'][$i];
        $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
        $_FILES['userfile']['error']= $files['userfile']['error'][$i];
        $_FILES['userfile']['size']= $files['userfile']['size'][$i];    

        $this->upload->initialize($this->set_upload_options());
        $this->upload->do_upload();
    }
}

private function set_upload_options()
{   
    //upload an image options
    $config = array();
    $config['upload_path'] = './Images/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size']      = '0';
    $config['overwrite']     = FALSE;

    return $config;
}

Thank you guys!

What is the best way to tell if a character is a letter or number in Java without using regexes?

As the answers indicate (if you examine them carefully!), your question is ambiguous. What do you mean by "an A-z letter" or a digit?

  • If you want to know if a character is a Unicode letter or digit, then use the Character.isLetter and Character.isDigit methods.

  • If you want to know if a character is an ASCII letter or digit, then the best thing to do is to test by comparing with the character ranges 'a' to 'z', 'A' to 'Z' and '0' to '9'.

Note that all ASCII letters / digits are Unicode letters / digits ... but there are many Unicode letters / digits characters that are not ASCII. For example, accented letters, cyrillic, sanskrit, ...


The general solution is to do this:

Character.UnicodeBlock block = Character.UnicodeBlock.of(someCodePoint);

and then test to see if the block is one of the ones that you are interested in. In some cases you will need to test for multiple blocks. For example, there are (at least) 4 code blocks for Cyrillic characters and 7 for Latin. The Character.UnicodeBlock class defines static constants for well-known blocks; see the javadocs.

Note that any code point will be in at most one block.

Python convert decimal to hex

I recently made this python program to convert Decimal to Hexadecimal, please check this out. This is my first Answer in stack overflow .

decimal = int(input("Enter the Decimal no that you want to convert to Hexadecimal : "))
intact = decimal
hexadecimal = ''
dictionary = {1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}

while(decimal!=0):
    c = decimal%16 
    hexadecimal =  dictionary[c] + hexadecimal 
    decimal = int(decimal/16)

print(f"{intact} is {hexadecimal} in Hexadecimal")

When you Execute this code this will give output as:

Enter the Decimal no that you want to convert to Hexadecimal : 2766

2766 is ACE in Hexadecimal

Accessing UI (Main) Thread safely in WPF

You can use

Dispatcher.Invoke(Delegate, object[])

on the Application's (or any UIElement's) dispatcher.

You can use it for example like this:

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

or

someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

UIAlertController custom font, size, color

For iOS 9.0 and above use this code in app delegate

[[UIView appearanceWhenContainedInInstancesOfClasses:@[[UIAlertController class]]] setTintColor:[UIColor redColor]];

JS - window.history - Delete a state

You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).

One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.

Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.

var myHistory = [];

function pageLoad() {
    window.history.pushState(myHistory, "<name>", "<url>");

    //Load page data.
}

Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.

function nav_to_details() {
    myHistory.push("page_im_on_now");
    window.history.replaceState(myHistory, "<name>", "<url>");

    //Load page data.
}

When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.

function on_popState() {
    // Note that some browsers fire popState on initial load,
    // so you should check your state object and handle things accordingly.
    // (I did not do that in these examples!)

    if (myHistory.length > 0) {
        var pg = myHistory.pop();
        window.history.pushState(myHistory, "<name>", "<url>");

        //Load page data for "pg".
    } else {
        //No "history" - let them exit or keep them in the app.
    }
}

The user will never be able to navigate forward using their browser buttons because they are always on the newest page.

From the browser's perspective, every time they go "back", they've immediately pushed forward again.

From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).

From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).

If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...

var myHistory = [];

function pageLoad() {
    // When the user first hits your page...
    // Check the state to see what's going on.

    if (window.history.state === null) {
        // If the state is null, this is a NEW navigation,
        //    the user has navigated to your page directly (not using back/forward).

        // First we establish a "back" page to catch backward navigation.
        window.history.replaceState(
            { isBackPage: true },
            "<back>",
            "<back>"
        );

        // Then push an "app" page on top of that - this is where the user will sit.
        // (As browsers vary, it might be safer to put this in a short setTimeout).
        window.history.pushState(
            { isBackPage: false },
            "<name>",
            "<url>"
        );

        // We also need to start our history tracking.
        myHistory.push("<whatever>");

        return;
    }

    // If the state is NOT null, then the user is returning to our app via history navigation.

    // (Load up the page based on the last entry of myHistory here)

    if (window.history.state.isBackPage) {
        // If the user came into our app via the back page,
        //     you can either push them forward one more step or just use pushState as above.

        window.history.go(1);
        // or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
    }

    setTimeout(function() {
        // Add our popstate event listener - doing it here should remove
        //     the issue of dealing with the browser firing it on initial page load.
        window.addEventListener("popstate", on_popstate);
    }, 100);
}

function on_popstate(e) {
    if (e.state === null) {
        // If there's no state at all, then the user must have navigated to a new hash.

        // <Look at what they've done, maybe by reading the hash from the URL>
        // <Change/load the new page and push it onto the myHistory stack>
        // <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>

        // Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
        window.history.go(-1);

        // Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
        // This would also prevent them from using the "forward" button to return to the new hash.
        window.history.replaceState(
            { isBackPage: false },
            "<new name>",
            "<new url>"
        );
    } else {
        if (e.state.isBackPage) {
            // If there is state and it's the 'back' page...

            if (myHistory.length > 0) {
                // Pull/load the page from our custom history...
                var pg = myHistory.pop();
                // <load/render/whatever>

                // And push them to our "app" page again
                window.history.pushState(
                    { isBackPage: false },
                    "<name>",
                    "<url>"
                );
            } else {
                // No more history - let them exit or keep them in the app.
            }
        }

        // Implied 'else' here - if there is state and it's NOT the 'back' page
        //     then we can ignore it since we're already on the page we want.
        //     (This is the case when we push the user back with window.history.go(-1) above)
    }
}

What happens to a declared, uninitialized variable in C? Does it have a value?

Static variables (file scope and function static) are initialized to zero:

int x; // zero
int y = 0; // also zero

void foo() {
    static int x; // also zero
}

Non-static variables (local variables) are indeterminate. Reading them prior to assigning a value results in undefined behavior.

void foo() {
    int x;
    printf("%d", x); // the compiler is free to crash here
}

In practice, they tend to just have some nonsensical value in there initially - some compilers may even put in specific, fixed values to make it obvious when looking in a debugger - but strictly speaking, the compiler is free to do anything from crashing to summoning demons through your nasal passages.

As for why it's undefined behavior instead of simply "undefined/arbitrary value", there are a number of CPU architectures that have additional flag bits in their representation for various types. A modern example would be the Itanium, which has a "Not a Thing" bit in its registers; of course, the C standard drafters were considering some older architectures.

Attempting to work with a value with these flag bits set can result in a CPU exception in an operation that really shouldn't fail (eg, integer addition, or assigning to another variable). And if you go and leave a variable uninitialized, the compiler might pick up some random garbage with these flag bits set - meaning touching that uninitialized variable may be deadly.

How can I add the new "Floating Action Button" between two widgets/layouts

Try this library (javadoc is here), min API level is 7:

dependencies {
    compile 'com.shamanland:fab:0.0.8'
}

It provides single widget with ability to customize it via Theme, xml or java-code.

light between

It's very simple to use. There are available normal and mini implementation according to Promoted Actions pattern.

<com.shamanland.fab.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_action_my"
    app:floatingActionButtonColor="@color/my_fab_color"
    app:floatingActionButtonSize="mini"
    />

Try to compile the demo app. There is exhaustive example: light and dark themes, using with ListView, align between two Views.

Python - TypeError: 'int' object is not iterable

If the case is:

n=int(input())

Instead of -> for i in n: -> gives error- 'int' object is not iterable

Use -> for i in range(0,n): -> works fine..!

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

How do I change the android actionbar title and icon

Go to manifest in which specific activity you want to change Action bar Title name and write android:label="Title name"

How to deep copy a list?

Regarding the list as a tree, the deep_copy in python can be most compactly written as

def deep_copy(x):
    if not isinstance(x, list): return x
    else: return map(deep_copy, x)

TypeError: 'str' does not support the buffer interface

>>> s = bytes("s","utf-8")
>>> print(s)
b's'
>>> s = s.decode("utf-8")
>>> print(s)
s

Well if useful for you in case removing annoying 'b' character.If anyone got better idea please suggest me or feel free to edit me anytime in here.I'm just newbie

Get difference between 2 dates in JavaScript?

A more correct solution

... since dates naturally have time-zone information, which can span regions with different day light savings adjustments

Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24, so the typical calculation will fail.

You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.

Now, the solution can be written as,

const _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// test it
const a = new Date("2017-01-01"),
    b = new Date("2017-07-25"),
    difference = dateDiffInDays(a, b);

This works because UTC time never observes DST. See Does UTC observe daylight saving time?

p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.

How to install cron

Do you have a Windows machine or a Linux machine?

Under Windows cron is called 'Scheduled Tasks'. It's located in the Control Panel. You can set several scripts to run at specified times in the control panel. Use the wizard to define the scheduled times. Be sure that PHP is callable in your PATH.

Under Linux you can create a crontab for your current user by typing:

crontab -e [username]

If this command fails, it's likely that cron is not installed. If you use a Debian based system (Debian, Ubuntu), try the following commands first:

sudo apt-get update
sudo apt-get install cron

If the command runs properly, a text editor will appear. Now you can add command lines to the crontab file. To run something every five minutes:

*/5 * * * *  /home/user/test.pl

The syntax is basically this:

.---------------- minute (0 - 59) 
|  .------------- hour (0 - 23)
|  |  .---------- day of month (1 - 31)
|  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ... 
|  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)  OR sun,mon,tue,wed,thu,fri,sat 
|  |  |  |  |
*  *  *  *  *  command to be executed

Read more about it on the following pages: Wikipedia: crontab

How to change Android version and code version number?

Go in the build.gradle and set the version code and name inside the defaultConfig element

defaultConfig {
    minSdkVersion 9
    targetSdkVersion 19
    versionCode 1
    versionName "1.0"
}

screenshot

pass **kwargs argument to another function with **kwargs

Expanding on @gecco 's answer, the following is an example that'll show you the difference:

def foo(**kwargs):
    for entry in kwargs.items():
        print("Key: {}, value: {}".format(entry[0], entry[1]))

# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})

# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")

Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails

Can I assume (bool)true == (int)1 for any C++ compiler?

Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...

Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as ints that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h> only require zero or non-zero, not necessarily zero or one.

If you cast that to bool, zero will convert to false, and non-zero to true (as you'd expect).

How can I use pointers in Java?

you can have pointers for literals as well. You have to implement them yourself. It is pretty basic for experts ;). Use an array of int/object/long/byte and voila you have the basics for implementing pointers. Now any int value can be a pointer to that array int[]. You can increment the pointer, you can decrement the pointer, you can multiply the pointer. You indeed have pointer arithmetics! That's the only way to implements 1000 int attributes classes and have a generic method that applies to all attributes. You can also use a byte[] array instead of an int[]

However I do wish Java would let you pass literal values by reference. Something along the lines

//(* telling you it is a pointer) public void myMethod(int* intValue);

How to create User/Database in script for Docker Postgres

You need to have the database running before you create the users. For this you need multiple processes. You can either start postgres in a subshell (&) in the shell script, or use a tool like supervisord to run postgres and then run any initialization scripts.

A guide to supervisord and docker https://docs.docker.com/articles/using_supervisord/

Eliminate space before \begin{itemize}

Try \vspace{-5mm} before the itemize.

How to apply a CSS filter to a background image

Please check the below code:-

_x000D_
_x000D_
.backgroundImageCVR{_x000D_
 position:relative;_x000D_
 padding:15px;_x000D_
}_x000D_
.background-image{_x000D_
 position:absolute;_x000D_
 left:0;_x000D_
 right:0;_x000D_
 top:0;_x000D_
 bottom:0;_x000D_
 background:url('http://www.planwallpaper.com/static/images/colorful-triangles-background_yB0qTG6.jpg');_x000D_
 background-size:cover;_x000D_
 z-index:1;_x000D_
 -webkit-filter: blur(10px);_x000D_
  -moz-filter: blur(10px);_x000D_
  -o-filter: blur(10px);_x000D_
  -ms-filter: blur(10px);_x000D_
  filter: blur(10px); _x000D_
}_x000D_
.content{_x000D_
 position:relative;_x000D_
 z-index:2;_x000D_
 color:#fff;_x000D_
}
_x000D_
<div class="backgroundImageCVR">_x000D_
    <div class="background-image"></div>_x000D_
    <div class="content">_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquam erat in ante malesuada, facilisis semper nulla semper. Phasellus sapien neque, faucibus in malesuada quis, lacinia et libero. Sed sed turpis tellus. Etiam ac aliquam tortor, eleifend rhoncus metus. Ut turpis massa, sollicitudin sit amet molestie a, posuere sit amet nisl. Mauris tincidunt cursus posuere. Nam commodo libero quis lacus sodales, nec feugiat ante posuere. Donec pulvinar auctor commodo. Donec egestas diam ut mi adipiscing, quis lacinia mauris condimentum. Quisque quis odio venenatis, venenatis nisi a, vehicula ipsum. Etiam at nisl eu felis vulputate porta.</p>_x000D_
      <p>Fusce ut placerat eros. Aliquam consequat in augue sed convallis. Donec orci urna, tincidunt vel dui at, elementum semper dolor. Donec tincidunt risus sed magna dictum, quis luctus metus volutpat. Donec accumsan et nunc vulputate accumsan. Vestibulum tempor, erat in mattis fringilla, elit urna ornare nunc, vel pretium elit sem quis orci. Vivamus condimentum dictum tempor. Nam at est ante. Sed lobortis et lorem in sagittis. In suscipit in est et vehicula.</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Spring Boot: Cannot access REST Controller on localhost (404)

You can add inside the POM.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <version>XXXXXXXXX</version>
</dependency>

Is quitting an application frowned upon?

There is a (relatively) simple design which will allow you to get around the "exit" conundrum. Make your app have a "base" state (activity) which is just a blank screen. On the first onCreate of the activity, you can launch another activity that your app's main functionality is in. The "exit" can then be accomplished by finish()ing this second activity and going back to the base of just a blank screen. The OS can keep this blank screen in memory for as long as it wants...

In essence, because you cannot exit out to OS, you simply transform into a self-created nothingness.

Is there a JavaScript function that can pad a string to get to a determined length?

Array manipulations are really slow compared to simple string concat. Of course, benchmark for your use case.

function(string, length, pad_char, append) {
    string = string.toString();
    length = parseInt(length) || 1;
    pad_char = pad_char || ' ';

    while (string.length < length) {
        string = append ? string+pad_char : pad_char+string;
    }
    return string;
};

hash keys / values as array

var a = {"apples": 3, "oranges": 4, "bananas": 42};    

var array_keys = new Array();
var array_values = new Array();

for (var key in a) {
    array_keys.push(key);
    array_values.push(a[key]);
}

alert(array_keys);
alert(array_values);

Accessing an SQLite Database in Swift

I've created an elegant SQLite library written completely in Swift called SwiftData.

Some of its feature are:

  • Bind objects conveniently to the string of SQL
  • Support for transactions and savepoints
  • Inline error handling
  • Completely thread safe by default

It provides an easy way to execute 'changes' (e.g. INSERT, UPDATE, DELETE, etc.):

if let err = SD.executeChange("INSERT INTO Cities (Name, Population, IsWarm, FoundedIn) VALUES ('Toronto', 2615060, 0, '1793-08-27')") {
    //there was an error during the insert, handle it here
} else {
    //no error, the row was inserted successfully
}

and 'queries' (e.g. SELECT):

let (resultSet, err) = SD.executeQuery("SELECT * FROM Cities")
if err != nil {
    //there was an error during the query, handle it here
} else {
    for row in resultSet {
        if let name = row["Name"].asString() {
            println("The City name is: \(name)")
        }
        if let population = row["Population"].asInt() {
            println("The population is: \(population)")
        }
        if let isWarm = row["IsWarm"].asBool() {
            if isWarm {
                println("The city is warm")
            } else {
                println("The city is cold")
            }
        }
        if let foundedIn = row["FoundedIn"].asDate() {
            println("The city was founded in: \(foundedIn)")
        }
    }
}

Along with many more features!

You can check it out here

Android camera android.hardware.Camera deprecated

Answers provided here as which camera api to use are wrong. Or better to say they are insufficient.

Some phones (for example Samsung Galaxy S6) could be above api level 21 but still may not support Camera2 api.

CameraCharacteristics mCameraCharacteristics = mCameraManager.getCameraCharacteristics(mCameraId);
Integer level = mCameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
if (level == null || level == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
    return false;
}

CameraManager class in Camera2Api has a method to read camera characteristics. You should check if hardware wise device is supporting Camera2 Api or not.

But there are more issues to handle if you really want to make it work for a serious application: Like, auto-flash option may not work for some devices or battery level of the phone might create a RuntimeException on Camera or phone could return an invalid camera id and etc.

So best approach is to have a fallback mechanism as for some reason Camera2 fails to start you can try Camera1 and if this fails as well you can make a call to Android to open default Camera for you.

How to sum the values of one column of a dataframe in spark/scala

If you want to sum all values of one column, it's more efficient to use DataFrame's internal RDD and reduce.

import sqlContext.implicits._
import org.apache.spark.sql.functions._

val df = sc.parallelize(Array(10,2,3,4)).toDF("steps")
df.select(col("steps")).rdd.map(_(0).asInstanceOf[Int]).reduce(_+_)

//res1 Int = 19

IOError: [Errno 13] Permission denied

I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt

Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....

Share Text on Facebook from Android App via ACTION_SEND

First you need query Intent to handler sharing option. Then use package name to filter Intent then we will have only one Intent that handler sharing option!

Share via Facebook

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Content to share");
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
    if ((app.activityInfo.name).contains("facebook")) {
        final ActivityInfo activity = app.activityInfo;
        final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
        shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        shareIntent.setComponent(name);
        v.getContext().startActivity(shareIntent);
        break;
   }
}

Bonus - Share via Twitter

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Content to share");
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
    if ("com.twitter.android.PostActivity".equals(app.activityInfo.name)) {
        final ActivityInfo activity = app.activityInfo;
        final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
        shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        shareIntent.setComponent(name);
        v.getContext().startActivity(shareIntent);
        break;
   }
}

And if you want to find how to share via another sharing application, find it there Tép Blog - Advance share via Android