Programs & Examples On #Wakelock

Refers to PowerManager.WakeLock, a class from the Android SDK belonging to package android.os. Its responsibility is requesting CPU resources in the context of power management. If no wake locks are taken, Android will shut down the CPU.

Disable Proximity Sensor during call

After trying a whole bunch of fixes including:

  • Phone app's menu option (my phone did not have a option to disable)
  • Proximity Screen Off Lite (did not work)
  • Xposed Framework with sensor disabler (works till phone is rebooted or app updates)
  • Macrodroid macro (Macrodroid does not run on my phone for some reason)
  • put some tin foil in front of it?(i don't know what i was thinking)

Here is My fix: I figured you cannot break it more so I opened up my phone and removed the proximity sensor all together from the motherboard. The sensor tester app now shows "no_value" where it use to give "Distance: 0" and my screen no longer goes black after dialing. Please note I can only confirm this working on a Samsung I8190 Galaxy S III mini with CM MOD 5.1.1. Here is a picture of the device i removed: prox sensor I have removed it using a SMD solder station's heat gun at 400 degrees, some tweezers and flux.But a sharp hobby knife might work too.

Android: How to turn screen on and off programmatically?

This is worked on Marshmallow

private final String TAG = "OnOffScreen";
private PowerManager _powerManager;
private PowerManager.WakeLock _screenOffWakeLock;

public void turnOnScreen() {
    if (_screenOffWakeLock != null) {
        _screenOffWakeLock.release();
    }
}

public void turnOffScreen() {
    try {
        _powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
        if (_powerManager != null) {
            _screenOffWakeLock = _powerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
            if (_screenOffWakeLock != null) {
                _screenOffWakeLock.acquire();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

adb server version doesn't match this client

Got a quick way to do it First

sudo rm /usr/bin/adb

Then

sudo ln -s /home/{{username}}/Android/Sdk/platform-tools/adb  /usr/bin/adb

Fastest way to fix the issue

How to get an Android WakeLock to work?

Do you have the required permission set in your Manifest?

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

What and where are the stack and heap?

I think many other people have given you mostly correct answers on this matter.

One detail that has been missed, however, is that the "heap" should in fact probably be called the "free store". The reason for this distinction is that the original free store was implemented with a data structure known as a "binomial heap." For that reason, allocating from early implementations of malloc()/free() was allocation from a heap. However, in this modern day, most free stores are implemented with very elaborate data structures that are not binomial heaps.

Easiest way to develop simple GUI in Python

Take your pick here.

Tkinter is in the Python stdlib.

How to calculate the sum of the datatable column in asp.net?

 this.LabelControl.Text = datatable.AsEnumerable()
    .Sum(x => x.Field<int>("Amount"))
    .ToString();

If you want to filter the results:

 this.LabelControl.Text = datatable.AsEnumerable()
    .Where(y => y.Field<string>("SomeCol") != "foo")
    .Sum(x => x.Field<int>("MyColumn") )
    .ToString();

Associating existing Eclipse project with existing SVN repository

Team->Share project is exactly what you need to do. Select SVN from the list, then click "Next". Subclipse will notice the presence of .svn directories that will ask you to confirm that the information is correct, and associate the project with subclipse.

Reading specific XML elements from XML file

You could use linq to xml.

    var xmlStr = File.ReadAllText("fileName.xml");


    var str = XElement.Parse(xmlStr);

    var result = str.Elements("word").
Where(x => x.Element("category").Value.Equals("verb")).ToList();

    Console.WriteLine(result);

Django error - matching query does not exist

your line raising the error is here:

comment = Comment.objects.get(pk=comment_id)

you try to access a non-existing comment.

from django.shortcuts import get_object_or_404

comment = get_object_or_404(Comment, pk=comment_id)

Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.

Ok up to here I suppose you are aware of this.

Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.

Other users go to addresses from their history, (same if data have been deleted since it may happens).

How to do SVN Update on my project using the command line

svn update /path/to/working/copy

If subversion is not in your PATH, then of course

/path/to/subversion/svn update /path/to/working/copy

or if you are in the current root directory of your svn repo (it contains a .svn subfolder), it's as simple as

svn update

SQL Server loop - how do I loop through a set of records

Just another approach if you are fine using temp tables.I have personally tested this and it will not cause any exception (even if temp table does not have any data.)

CREATE TABLE #TempTable
(
    ROWID int identity(1,1) primary key,
    HIERARCHY_ID_TO_UPDATE int,
)

--create some testing data
--INSERT INTO #TempTable VALUES(1)
--INSERT INTO #TempTable VALUES(2)
--INSERT INTO #TempTable VALUES(4)
--INSERT INTO #TempTable VALUES(6)
--INSERT INTO #TempTable VALUES(8)

DECLARE @MAXID INT, @Counter INT

SET @COUNTER = 1
SELECT @MAXID = COUNT(*) FROM #TempTable

WHILE (@COUNTER <= @MAXID)
BEGIN
    --DO THE PROCESSING HERE 
    SELECT @HIERARCHY_ID_TO_UPDATE = PT.HIERARCHY_ID_TO_UPDATE
    FROM #TempTable AS PT
    WHERE ROWID = @COUNTER

    SET @COUNTER = @COUNTER + 1
END


IF (OBJECT_ID('tempdb..#TempTable') IS NOT NULL)
BEGIN
    DROP TABLE #TempTable
END

Finding the index of an item in a list

There is a more functional answer to this.

list(filter(lambda x: x[1]=="bar",enumerate(["foo", "bar", "baz", "bar", "baz", "bar", "a", "b", "c"])))

More generic form:

def get_index_of(lst, element):
    return list(map(lambda x: x[0],\
       (list(filter(lambda x: x[1]==element, enumerate(lst))))))

Reload parent window from child window

parent.location.reload();

This should work.

Naming Conventions: What to name a boolean variable?

Two issues to think about

  1. What is the scope of the variable (in other words: are you speaking about a local variable or a field?) ? A local variable has a narrower scope compared to a field. In particular, if the variable is used inside a relatively short method I would not care so much about its name. When the scope is large naming is more important.

  2. I think there's an inherent conflict in the way you treat this variable. On the one hand you say "false when an object is the last in a list", where on the other hand you also want to call it "inFront". An object that is (not) last in the list does not strike me as (not) inFront. This I would go with isLast.

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

In the functional paradigm repeat is usually an infinite recursive function. To use it we need either lazy evaluation or continuation passing style.

Lazy evaluated function repetition

_x000D_
_x000D_
const repeat = f => x => [x, () => repeat(f) (f(x))];_x000D_
const take = n => ([x, f]) => n === 0 ? x : take(n - 1) (f());_x000D_
_x000D_
console.log(_x000D_
  take(8) (repeat(x => x * 2) (1)) // 256_x000D_
);
_x000D_
_x000D_
_x000D_

I use a thunk (a function without arguments) to achieve lazy evaluation in Javascript.

Function repetition with continuation passing style

_x000D_
_x000D_
const repeat = f => x => [x, k => k(repeat(f) (f(x)))];_x000D_
const take = n => ([x, k]) => n === 0 ? x : k(take(n - 1));_x000D_
_x000D_
console.log(_x000D_
  take(8) (repeat(x => x * 2) (1)) // 256_x000D_
);
_x000D_
_x000D_
_x000D_

CPS is a little scary at first. However, it always follows the same pattern: The last argument is the continuation (a function), which invokes its own body: k => k(...). Please note that CPS turns the application inside out, i.e. take(8) (repeat...) becomes k(take(8)) (...) where k is the partially applied repeat.

Conclusion

By separating the repetition (repeat) from the termination condition (take) we gain flexibility - separation of concerns up to its bitter end :D

Differences between MySQL and SQL Server

Lots of comments here sound more like religious arguments than real life statements. I've worked for years with both MySQL and MSSQL and both are good products. I would choose MySQL mainly based on the environment that you are working on. Most open source projects use MySQL, so if you go into that direction MySQL is your choice. If you develop something with .Net I would choose MSSQL, not because it's much better, but just cause that is what most people use. I'm actually currently on a Project that uses ASP.NET with MySQL and C#. It works perfectly fine.

Run function from the command line

Something like this: call_from_terminal.py

# call_from_terminal.py
# Ex to run from terminal
# ip='"hi"'
# python -c "import call_from_terminal as cft; cft.test_term_fun(${ip})"
# or
# fun_name='call_from_terminal'
# python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
def test_term_fun(ip):
    print ip

This works in bash.

$ ip='"hi"' ; fun_name='call_from_terminal' 
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi

Best way to make a shell script daemon?

Here is the minimal change to the original proposal to create a valid daemon in Bourne shell (or Bash):

#!/bin/sh
if [ "$1" != "__forked__" ]; then
    setsid "$0" __forked__ "$@" &
    exit
else
    shift
fi

trap 'siguser1=true' SIGUSR1
trap 'echo "Clean up and exit"; kill $sleep_pid; exit' SIGTERM
exec > outfile
exec 2> errfile
exec 0< /dev/null

while true; do
    (sleep 30000000 &>/dev/null) &
    sleep_pid=$!
    wait
    kill $sleep_pid &>/dev/null
    if [ -n "$siguser1" ]; then
        siguser1=''
        echo "Wait was interrupted by SIGUSR1, do things here."
    fi
done

Explanation:

  • Line 2-7: A daemon must be forked so it doesn't have a parent. Using an artificial argument to prevent endless forking. "setsid" detaches from starting process and terminal.
  • Line 9: Our desired signal needs to be differentiated from other signals.
  • Line 10: Cleanup is required to get rid of dangling "sleep" processes.
  • Line 11-13: Redirect stdout, stderr and stdin of the script.
  • Line 16: sleep in the background
  • Line 18: wait waits for end of sleep, but gets interrupted by (some) signals.
  • Line 19: Kill sleep process, because that is still running when signal is caught.
  • Line 22: Do the work if SIGUSR1 has been caught.

Guess it does not get any simpler than that.

Why is HttpClient BaseAddress not working?

Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.

If base URI contains non-empty path, merge procedure discards it's last part (after last /). Relevant section:

5.2.3. Merge Paths

The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:

  • If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise

  • return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).

If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

If you already have all the required modules installed you probably need to import the setuptools module in your setup.py file. So just add the following line at the leading of setup.py file.

import setuptools
from distutils.core import setup
# other imports and setups

This is also mentioned in wheel's documentation. https://wheel.readthedocs.io/en/stable/#usage

Scatter plot with error bars

Using ggplot and a little dplyr for data manipulation:

set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

library(ggplot2)
library(dplyr)

df.summary <- df %>% group_by(x) %>%
    summarize(ymin = min(y),
              ymax = max(y),
              ymean = mean(y))

ggplot(df.summary, aes(x = x, y = ymean)) +
    geom_point(size = 2) +
    geom_errorbar(aes(ymin = ymin, ymax = ymax))

If there's an additional grouping column (OP's example plot has two errorbars per x value, saying the data is sourced from two files), then you should get all the data in one data frame at the start, add the grouping variable to the dplyr::group_by call (e.g., group_by(x, file) if file is the name of the column) and add it as a "group" aesthetic in the ggplot, e.g., aes(x = x, y = ymean, group = file).

Get selected value from combo box in C# WPF

It depends what you bound to your ComboBox. If you have bound an object called MyObject, and have, let's say, a property called Name do the following:

MyObject mo = myListBox.SelectedItem as MyObject;
return mo.Name;

Checking if a file is a directory or just a file

Use the S_ISDIRmacro:

int isDirectory(const char *path) {
   struct stat statbuf;
   if (stat(path, &statbuf) != 0)
       return 0;
   return S_ISDIR(statbuf.st_mode);
}

Is an anchor tag without the href attribute safe?

The <a> tag without the "href" can be handy when using multi-level menus and you need to expand the next level but don't want that menu label to be an active link. I have never had any issues using it that way.

How to call getClass() from a static method in Java?

I had the same problem ! but to solve it just modify your code as following.

public static void startMusic() {
URL songPath = YouClassName.class.getClassLoader().getResource("background.midi");
}

this worked fine with me hope it will also work fine with you.

Javascript find json value

First convert this structure to a "dictionary" object:

dict = {}
json.forEach(function(x) {
    dict[x.code] = x.name
})

and then simply

countryName = dict[countryCode]

For a list of countries this doesn't matter much, but for larger lists this method guarantees the instant lookup, while the naive searching will depend on the list size.

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

Why can't I change my input value in React even with the onChange listener

In react, state will not change until you do it by using this.setState({});. That is why your console message showing old values.

Reading data from a website using C#

Regarding the suggestion So I would suggest that you use WebClient and investigate the causes of the 30 second delay.

From the answers for the question System.Net.WebClient unreasonably slow

Try setting Proxy = null;

WebClient wc = new WebClient(); wc.Proxy = null;

Credit to Alex Burtsev

How to get an object's properties in JavaScript / jQuery?

Scanning object for first intance of a determinated prop:

var obj = {a:'Saludos',
            b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
           d:'Hasta luego'
            }
function scan (element,list){
    var res;
    if (typeof(list) != 'undefined'){
        if (typeof(list) == 'object'){
            for(key in list){
               if (typeof(res) == 'undefined'){
                res = (key == element)?list[key]:scan(element,list[key]);
               }
            });
        }
    }
    return res;
}
console.log(scan('a',obj));

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

Windows does not natively include a touch command.

You can use any of the available public versions or you can use your own version. Save this code as touch.cmd and place it somewhere in your path

@echo off
    setlocal enableextensions disabledelayedexpansion

    (for %%a in (%*) do if exist "%%~a" (
        pushd "%%~dpa" && ( copy /b "%%~nxa"+,, & popd )
    ) else (
        type nul > "%%~fa"
    )) >nul 2>&1

It will iterate over it argument list, and for each element if it exists, update the file timestamp, else, create it.

No Main class found in NetBeans

You need to add }} to the end of your code.

"R cannot be resolved to a variable"?

1) see if the xml files in the Package Explorer tree have an error-icon if they do, fix errors and R-class will be generated.

example hint: FILL_PARENT was renamed MATCH_PARENT in API Level 8; so if you're targeting platform 2.1 (api 7), change all occurences back to "fill_parent"

2) if you added "import android.R;" trying to do a quick-fix, remove that line

How to download a file using a Java REST service and a data stream

Refer this:

@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {

// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();

// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");

// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}

Details at: https://twilblog.github.io/java/spring/rest/file/stream/2015/08/14/return-a-file-stream-from-spring-rest.html

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

How to load a model from an HDF5 file in Keras?

According to official documentation https://keras.io/getting-started/faq/#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras

you can do :

first test if you have h5py installed by running the

import h5py

if you dont have errors while importing h5py you are good to save:

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

If you need to install h5py http://docs.h5py.org/en/latest/build.html

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

svn : how to create a branch from certain revision of trunk

append the revision using an "@" character:

svn copy http://src@REV http://dev

Or, use the -r [--revision] command line argument.

Insert HTML with React Variable Statements (JSX)

If anyone else still lands here. With ES6 you can create your html variable like so:

render(){
    var thisIsMyCopy = (
        <p>copy copy copy <strong>strong copy</strong></p>
    );
    return(
        <div>
            {thisIsMyCopy}
        </div>
    )
}

Double Iteration in List Comprehension

Order of iterators may seem counter-intuitive.

Take for example: [str(x) for i in range(3) for x in foo(i)]

Let's decompose it:

def foo(i):
    return i, i + 0.5

[str(x)
    for i in range(3)
        for x in foo(i)
]

# is same as
for i in range(3):
    for x in foo(i):
        yield str(x)

Failed to build gem native extension — Rails install

The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.

sudo apt-get install ruby-all-dev

worked for me.

get everything between <tag> and </tag> with php

$regex = '#<code>(.*?)</code>#';

Using # as the delimiter instead of / because then we don't need to escape the / in </code>

As Phoenix posted below, .*? is used to make the .* ("anything") match as few characters as possible before it comes across a </code> (known as a "non-greedy quantifier"). That way, if your string is

<code>hello</code> something <code>again</code>

you'll match hello and again instead of just matching hello</code> something <code>again.

Detect whether a Python string is a number or a letter

Check if string is positive digit (integer) and alphabet

You may use str.isdigit() and str.isalpha() to check whether given string is positive integer and alphabet respectively.

Sample Results:

# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True

# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False

Check for strings as positive/negative - integer/float

str.isdigit() returns False if the string is a negative number or a float number. For example:

# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False

If you want to also check for the negative integers and float, then you may write a custom function to check for it as:

def is_number(n):
    try:
        float(n)   # Type-casting the string to `float`.
                   # If string is not a valid `float`, 
                   # it'll raise `ValueError` exception
    except ValueError:
        return False
    return True

Sample Run:

>>> is_number('123')    # positive integer number
True

>>> is_number('123.4')  # positive float number
True
 
>>> is_number('-123')   # negative integer number
True

>>> is_number('-123.4') # negative `float` number
True

>>> is_number('abc')    # `False` for "some random" string
False

Discard "NaN" (not a number) strings while checking for number

The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:

>>> is_number('NaN')
True

In order to check whether the number is "NaN", you may use math.isnan() as:

>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)
True

Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:

# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False

Hence, above function is_number can be updated to return False for "NaN" as:

def is_number(n):
    is_number = True
    try:
        num = float(n)
        # check for "nan" floats
        is_number = num == num   # or use `math.isnan(num)`
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('Nan')   # not a number "Nan" string
False

>>> is_number('nan')   # not a number string "nan" with all lower cased
False

>>> is_number('123')   # positive integer
True

>>> is_number('-123')  # negative integer
True

>>> is_number('-1.12') # negative `float`
True

>>> is_number('abc')   # "some random" string
False

Allow Complex Number like "1+2j" to be treated as valid number

The above function will still return you False for the complex numbers. If you want your is_number function to treat complex numbers as valid number, then you need to type cast your passed string to complex() instead of float(). Then your is_number function will look like:

def is_number(n):
    is_number = True
    try:
        #      v type-casting the number here as `complex`, instead of `float`
        num = complex(n)
        is_number = num == num
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('1+2j')    # Valid 
True                     #      : complex number 

>>> is_number('1+ 2j')   # Invalid 
False                    #      : string with space in complex number represetantion
                         #        is treated as invalid complex number

>>> is_number('123')     # Valid
True                     #      : positive integer

>>> is_number('-123')    # Valid 
True                     #      : negative integer

>>> is_number('abc')     # Invalid 
False                    #      : some random string, not a valid number

>>> is_number('nan')     # Invalid
False                    #      : not a number "nan" string

PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.

Eclipse projects not showing up after placing project files in workspace/projects

I had the same problem over and over again the solution that a have found works for now

  1. Close Eclipse.
  2. go to workspace.metadata.plugins
  3. remove org.eclipse.core.resources
  4. Start Eclipse
  5. Do File->Import
  6. General->Existing Projects into Workspace and import all the project from the workspace

SSIS how to set connection string dynamically from a config file

Goto Package properties->Configurations->Enable Package Configurations->Add->xml configuration file->Specify dtsconfig file->click next->In OLEDB Properties tick the connection string->connection string value will be displayed->click next and finish package is hence configured.

You can add Environment variable also in this process

Why is list initialization (using curly braces) better than the alternatives?

There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:

  • If the object I'm creating conceptually holds the values I'm passing in the constructor (e.g. containers, POD structs, atomics, smart pointers etc.), then I'm using the braces.
  • If the constructor resembles a normal function call (it performs some more or less complex operations that are parametrized by the arguments) then I'm using the normal function call syntax.
  • For default initialization I always use curly braces.
    For one, that way I'm always sure that the object gets initialized irrespective of whether it e.g. is a "real" class with a default constructor that would get called anyway or a builtin / POD type. Second it is - in most cases - consistent with the first rule, as a default initialized object often represents an "empty" object.

In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).

It e.g. fits nicely with standard library-types like std::vector:

vector<int> a{10,20};   //Curly braces -> fills the vector with the arguments

vector<int> b(10,20);   //Parentheses -> uses arguments to parametrize some functionality,                          
vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.

vector<int> d{};      //empty braces -> default constructs vector, which is equivalent
                      //to a vector that is filled with zero elements

Windows Explorer "Command Prompt Here"

Hold Shift while Right-Clicking a blank space in the desired folder to bring up a more verbose context menu. One of the options is Open Command Window Here. This works in Windows Vista, 7, 8, and 10. Since Windows 10 Creators Update, the option has been replaced with Open PowerShell Here. However, there are ways to enable Open Command Window Here again.

Is there a way to remove the separator line from a UITableView?

In your viewDidLoad:

self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
{
    [self.tableView setSeparatorInset:UIEdgeInsetsZero];
}

Creating InetAddress object in Java

You should be able to use getByName or getByAddress.

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address

InetAddress addr = InetAddress.getByName("127.0.0.1");

The method that takes a byte array can be used like this:

byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Code for Greatest Common Divisor in Python

using recursion,

def gcd(a,b):
    return a if not b else gcd(b, a%b)

using while,

def gcd(a,b):
  while b:
    a,b = b, a%b
  return a

using lambda,

gcd = lambda a,b : a if not b else gcd(b, a%b)

>>> gcd(10,20)
>>> 10

Running two projects at once in Visual Studio

Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.

Solution properties dialog

How can I find the version of php that is running on a distinct domain name?

There is a possibility to find the PHP version of other domain by checking "X-Powered-By" response header in the browser through developer tools as other already mentioned it. If it is not exposed through the php.ini configuration there is no way you can get it unless you have access to the server.

How can we print line numbers to the log in java

Below code is tested code for logging line no class name and method name from where logging method is called

public class Utils {
/*
 * debug variable enables/disables all log messages to logcat
 * Useful to disable prior to app store submission
 */
public static final boolean debug = true;

/*
 * l method used to log passed string and returns the
 * calling file as the tag, method and line number prior
 * to the string's message
 */
public static void l(String s) {
    if (debug) {
        String[] msg = trace(Thread.currentThread().getStackTrace(), 3);
        Log.i(msg[0], msg[1] + s);
    } else {
        return;
    }
}

/*
 * l (tag, string)
 * used to pass logging messages as normal but can be disabled
 * when debug == false
 */
public static void l(String t, String s) {
    if (debug) {
        Log.i(t, s);
    } else {
        return;
    }
}

/*
 * trace
 * Gathers the calling file, method, and line from the stack
 * returns a string array with element 0 as file name and 
 * element 1 as method[line]
 */
public static String[] trace(final StackTraceElement e[], final int level) {
    if (e != null && e.length >= level) {
        final StackTraceElement s = e[level];
        if (s != null) { return new String[] {
                e[level].getFileName(), e[level].getMethodName() + "[" + e[level].getLineNumber() + "]"
        };}
    }
    return null;
}
}

What is size_t in C?

Since nobody has yet mentioned it, the primary linguistic significance of size_t is that the sizeof operator returns a value of that type. Likewise, the primary significance of ptrdiff_t is that subtracting one pointer from another will yield a value of that type. Library functions that accept it do so because it will allow such functions to work with objects whose size exceeds UINT_MAX on systems where such objects could exist, without forcing callers to waste code passing a value larger than "unsigned int" on systems where the larger type would suffice for all possible objects.

How can I make PHP display the error instead of giving me 500 Internal Server Error

Enabling error displaying from PHP code doesn't work out for me. In my case, using NGINX and PHP-FMP, I track the log file using grep. For instance, I know the file name mycode.php causes the error 500, but don't know which line. From the console, I use this:

/var/log/php-fpm# cat www-error.log | grep mycode.php

And I have the output:

[04-Apr-2016 06:58:27] PHP Parse error:  syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458

This helps me find the line where I have the typo.

What are the differences between Pandas and NumPy+SciPy in Python?

pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.

embedding image in html email

I know this is an old post, but the current answers dont address the fact that outlook and many other email providers dont support inline images or CID images. The most effective way to place images in emails is to host it online and place a link to it in the email. For small email lists a public dropbox works fine. This also keeps the email size down.

jQuery get the image src

This is what you need

 $('img').context.currentSrc

SUM OVER PARTITION BY

remove partition by and add group by clause,

SELECT BrandId
      ,SUM(ICount) totalSum
  FROM Table 
WHERE DateId  = 20130618
GROUP BY BrandId

Where to find extensions installed folder for Google Chrome on Mac?

For Mac EI caption/Mac Sierra, Chrome extension folders were located at

/Users/$USER/Library/Application\ Support/Google/Chrome/Profile*/Extensions/

WCF on IIS8; *.svc handler mapping doesn't work

I had to enable HTTP Activation in .NET Framework 4.5 Advanced Services > WCF Services

Enable HTTP Activation

Disable a link in Bootstrap

I just created my own version using CSS. As I need to disabled, then when document is ready use jQuery to make active. So that way a user cannot click on a button until after the document is ready. So i can substitute with AJAX instead. The way I came up with, was to add a class to the anchor tag itself and remove the class when document is ready. Could re-purpose this for your needs.

CSS:

a.disabled{
    pointer-events: none;
    cursor: default;
}

HTML:

<a class="btn btn-info disabled">Link Text</a>

JS:

$(function(){
    $('a.disabled').on('click',function(event){
        event.preventDefault();
    }).removeClass('disabled');
});

How to iterate over a JSONObject?

Most of the answers here are for flat JSON structures, in case you have a JSON which might have nested JSONArrays or Nested JSONObjects, the real complexity arises. The following code snippet takes care of such a business requirement. It takes a hash map, and hierarchical JSON with both nested JSONArrays and JSONObjects and updates the JSON with the data in the hash map

public void updateData(JSONObject fullResponse, HashMap<String, String> mapToUpdate) {

    fullResponse.keySet().forEach(keyStr -> {
        Object keyvalue = fullResponse.get(keyStr);

        if (keyvalue instanceof JSONArray) {
            updateData(((JSONArray) keyvalue).getJSONObject(0), mapToUpdate);
        } else if (keyvalue instanceof JSONObject) {
            updateData((JSONObject) keyvalue, mapToUpdate);
        } else {
            // System.out.println("key: " + keyStr + " value: " + keyvalue);
            if (mapToUpdate.containsKey(keyStr)) {
                fullResponse.put(keyStr, mapToUpdate.get(keyStr));
            }
        }
    });

}

You have to notice here that the return type of this is void, but sice objects are passed as refernce this change is refelected to the caller.

How to empty a list in C#?

You can use the clear method

List<string> test = new List<string>();
test.Clear();

Typescript Type 'string' is not assignable to type

All the above answers are valid, however, there are some cases that the String Literal Type is part of another complex type. Consider the following example:

  // in foo.ts
  export type ToolbarTheme = {
    size: 'large' | 'small',
  };

  // in bar.ts
  import { ToolbarTheme } from './foo.ts';
  function useToolbarTheme(theme: ToolbarTheme) {/* ... */}

  // Here you will get the following error: 
  // Type 'string' is not assignable to type '"small" | "large"'.ts(2322)
  ['large', 'small'].forEach(size => (
    useToolbarTheme({ size })
  ));

You have multiple solutions to fix this. Each solution is valid and has its own use cases.

1) The first solution is to define a type for the size and export it from the foo.ts. This is good if when you need to work with the size parameter by its own. For example, you have a function that accepts or returns a parameter of type size and you want to type it.

  // in foo.ts
  export type ToolbarThemeSize = 'large' | 'small';
  export type ToolbarTheme = {
    size: ToolbarThemeSize
  };

  // in bar.ts
  import { ToolbarTheme, ToolbarThemeSize } from './foo.ts';
  function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
  function getToolbarSize(): ToolbarThemeSize  {/* ... */}

  ['large', 'small'].forEach(size => (
    useToolbarTheme({ size: size as ToolbarThemeSize })
  ));

2) The second option is to just cast it to the type ToolbarTheme. In this case, you don't need to expose the internal of ToolbarTheme if you don't need.

  // in foo.ts
  export type ToolbarTheme = {
    size: 'large' | 'small'
  };

  // in bar.ts
  import { ToolbarTheme } from './foo.ts';
  function useToolbarTheme(theme: ToolbarTheme) {/* ... */}

  ['large', 'small'].forEach(size => (
    useToolbarTheme({ size } as ToolbarTheme)
  ));

Why is a ConcurrentModificationException thrown and how to debug it

This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.

Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
   Entry item = it.next();
   map.remove(item.getKey());
}

This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.

The correct approach would be

   Iterator it = map.entrySet().iterator();
   while (it.hasNext())
   {
      Entry item = it.next();
      it.remove();
   }

Assuming this iterator supports the remove() operation.

How to add a line to a multiline TextBox?

You have to use the AppendText method of the textbox directly. If you try to use the Text property, the textbox will not scroll down as new line are appended.

textBox1.AppendText("Hello" + Environment.NewLine);

How to increase heap size of an android application?

This can be done by two ways according to your Android OS.

  1. You can use android:largeHeap="true" in application tag of Android manifest to request a larger heap size, but this will not work on any pre Honeycomb devices.
  2. On pre 2.3 devices, you can use the VMRuntime class, but this will not work on Gingerbread and above See below how to do it.
VMRuntime.getRuntime().setMinimumHeapSize(BIGGER_SIZE);

Before Setting HeapSize make sure that you have entered the appropriate size which will not affect other application or OS functionality. Before settings just check how much size your app takes & then set the size just to fulfill your job. Dont use so much of memory otherwise other apps might affect.

Reference: http://dwij.co.in/increase-heap-size-of-android-application

How to Empty Caches and Clean All Targets Xcode 4 and later

Command-Option-Shift-K should do it. Alternatively, go to product menu, press the option key, now the option "Clean" will change to "Clean Build Folder ..." select that option.

Creating a search form in PHP to search a database?

You're getting errors 'table liam does not exist' because the table's name is Liam which is not the same as liam. MySQL table names are case sensitive.

Querying Datatable with where condition

something like this ? :

DataTable dt = ...
DataView dv = new DataView(dt);
dv.RowFilter = "(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)"

Is it what you are searching for?

How to concat string + i?

according to this it looks like you have to set "N" before trying to use it and it looks like it needs to be an int not string? Don't know much bout MatLab but just what i gathered from that site..hope it helps :)

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

in android

Replace: String webServiceUrl = "http://localhost:8080/Service1.asmx"

With : String webServiceUrl = "http://10.0.2.2:8080/Service1.asmx"

Good luck!

Failure during conversion to COFF: file invalid or corrupt

If you have installed VS2012 as well, the old cvtres file will no longer work.

Try removing the file (I simply renamed):
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\BIN\cvtres.exe

You can also debug using the /VERBOSE linker option in order to get more information regarding the linker error. There you should see an error message that the invoke to cvtres fails.

Convert RGB values to Integer

To get individual colour values you can use Color like following for pixel(x,y).

import java.awt.Color;
import java.awt.image.BufferedImage;

Color c = new Color(buffOriginalImage.getRGB(x,y));
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();

The above will give you the integer values of Red, Green and Blue in range of 0 to 255.

To set the values from RGB you can do so by:

Color myColour = new Color(red, green, blue);
int rgb = myColour.getRGB();

//Change the pixel at (x,y) ti rgb value
image.setRGB(x, y, rgb);

Please be advised that the above changes the value of a single pixel. So if you need to change the value entire image you may need to iterate over the image using two for loops.

How to maintain aspect ratio using HTML IMG tag

Use object-fit: contain in css of html element img.

ex:

img {
    ...
    object-fit: contain
    ...
}

Does Python have a package/module management system?

Poetry is what you're looking for. It takes care of dependency management, virtual environments, running.

html5 input for money/currency

More easy and beautiful if you has vue.js v-money-spinner :)

enter image description here

How to scale a UIImageView proportionally?

Set your ImageView by selecting Mode to Aspect Fill and check the Clip Subviews box.

enter image description here

How to detect installed version of MS-Office?

namespace Software_Info_v1._0
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop;

public class MS_Office
{
    public string GetOfficeVersion()
    {
        string sVersion = string.Empty;
        Microsoft.Office.Interop.Word.Application appVersion = new Microsoft.Office.Interop.Word.Application();
        appVersion.Visible = false;
        switch (appVersion.Version.ToString())
        {
            case "7.0":
                sVersion = "95";
                break;
            case "8.0":
                sVersion = "97";
                break;
            case "9.0":
                sVersion = "2000";
                break;
            case "10.0":
                sVersion = "2002";
                break;
            case "11.0":
                sVersion = "2003";
                break;
            case "12.0":
                sVersion = "2007";
                break;
            case "14.0":
                sVersion = "2010";
                break;
            default:
                sVersion = "Too Old!";
                break;
        }
        Console.WriteLine("MS office version: " + sVersion);
        return null;
    }



}
}

How is TeamViewer so fast?

The most fundamental thing here probably is that you don't want to transmit static images but only changes to the images, which essentially is analogous to video stream.

My best guess is some very efficient (and heavily specialized and optimized) motion compensation algorithm, because most of the actual change in generic desktop usage is linear movement of elements (scrolling text, moving windows, etc. opposed to transformation of elements).

The DirectX 3D performance of 1 FPS seems to confirm my guess to some extent.

PHP CSV string to array

Do this:

$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}
print_r($array);

It will give you an output like this:

Array
(
    [0] => Array
        (
            [0] => 12345
            [1] => Computers
            [2] => Acer
            [3] => 4
            [4] => Varta
            [5] => 5.93
            [6] => 1
            [7] => 0.04
            [8] => 27-05-2013
        )

    [1] => Array
        (
            [0] => 12346
            [1] => Computers
            [2] => Acer
            [3] => 5
            [4] => Decra
            [5] => 5.94
            [6] => 1
            [7] => 0.04
            [8] => 27-05-2013
        )

)

I hope this can be of some help.

How do you make websites with Java?

I'd suggest OOWeb to act as an HTTP server and a templating engine like Velocity to generate HTML. I also second Esko's suggestion of Wicket. Both solutions are considerably simpler than the average setup.

How to change TIMEZONE for a java.util.Calendar/Date

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

Another possible solution would be to utilise the static fields of the Calendar class:

//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.

How can I remove a key from a Python dictionary?

Using the "del" keyword:

del dict[key]

How to equalize the scales of x-axis and y-axis in Python matplotlib?

You need to dig a bit deeper into the api to do this:

from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()

doc for set_aspect

Navigation Drawer (Google+ vs. YouTube)

Personally I like the navigationDrawer in Google Drive official app. It just works and works great. I agree that the navigation drawer shouldn't move the action bar because is the key point to open and close the navigation drawer.

If you are still trying to get that behavior I recently create a project Called SherlockNavigationDrawer and as you may expect is the implementation of the Navigation Drawer with ActionBarSherlock and works for pre Honeycomb devices. Check it:

SherlockNavigationDrawer github

How to use MySQL dump from a remote machine

No one mentions anything about the --single-transaction option. People should use it by default for InnoDB tables to ensure data consistency. In this case:

mysqldump --single-transaction -h [remoteserver.com] -u [username] -p [password] [yourdatabase] > [dump_file.sql]

This makes sure the dump is run in a single transaction that's isolated from the others, preventing backup of a partial transaction.

For instance, consider you have a game server where people can purchase gears with their account credits. There are essentially 2 operations against the database:

  1. Deduct the amount from their credits
  2. Add the gear to their arsenal

Now if the dump happens in between these operations, the next time you restore the backup would result in the user losing the purchased item, because the second operation isn't dumped in the SQL dump file.

While it's just an option, there are basically not much of a reason why you don't use this option with mysqldump.

How do I change column default value in PostgreSQL?

'SET' is forgotten

ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';

Update multiple rows in same query using PostgreSQL

Let's say you have an array of IDs and equivalent array of statuses - here is an example how to do this with a static SQL (a sql query that doesn't change due to different values) of the arrays :

drop table if exists results_dummy;
create table results_dummy (id int, status text, created_at timestamp default now(), updated_at timestamp default now());
-- populate table with dummy rows
insert into results_dummy
(id, status)
select unnest(array[1,2,3,4,5]::int[]) as id, unnest(array['a','b','c','d','e']::text[]) as status;

select * from results_dummy;

-- THE update of multiple rows with/by different values
update results_dummy as rd
set    status=new.status, updated_at=now()
from (select unnest(array[1,2,5]::int[]) as id,unnest(array['a`','b`','e`']::text[]) as status) as new
where rd.id=new.id;

select * from results_dummy;

-- in code using **IDs** as first bind variable and **statuses** as the second bind variable:
update results_dummy as rd
set    status=new.status, updated_at=now()
from (select unnest(:1::int[]) as id,unnest(:2::text[]) as status) as new
where rd.id=new.id;

What is the behavior of integer division?

Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.

-5 / 2 = -2
 5 / 2 =  2

For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).

Making macOS Installer Packages which are Developer ID ready

FYI for those that are trying to create a package installer for a bundle or plugin, it's easy:

pkgbuild --component "Color Lists.colorPicker" --install-location ~/Library/ColorPickers ColorLists.pkg

How can a file be copied?

You could use os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')

or as I did it,

os.system('cp '+ rawfile + ' rawdata.dat')

where rawfile is the name that I had generated inside the program.

This is a Linux only solution

Making text bold using attributed string in swift

Just use code something like this:

 let font = UIFont(name: "Your-Font-Name", size: 10.0)!

        let attributedText = NSMutableAttributedString(attributedString: noteLabel.attributedText!)
        let boldedRange = NSRange(attributedText.string.range(of: "Note:")!, in: attributedText.string)
        attributedText.addAttributes([NSAttributedString.Key.font : font], range: boldedRange)
        noteLabel.attributedText = attributedText

How to lay out Views in RelativeLayout programmatically?

Just spent 4 hours with this problem. Finally realized that you must not use zero as view id. You would think that it is allowed as NO_ID == -1, but things tend to go haywire if you give it to your view...

"id cannot be resolved or is not a field" error?

Some times eclipse may confuse with other projects in the same directory.

Just change package name (don't forget to change in Android manifest file also), ensure the package name is not used already in the directory. It may work.

@Cacheable key on multiple method arguments

After some limited testing with Spring 3.2, it seems one can use a SpEL list: {..., ..., ...}. This can also include null values. Spring passes the list as the key to the actual cache implementation. When using Ehcache, such will at some point invoke List#hashCode(), which takes all its items into account. (I am not sure if Ehcache only relies on the hash code.)

I use this for a shared cache, in which I include the method name in the key as well, which the Spring default key generator does not include. This way I can easily wipe the (single) cache, without (too much...) risking matching keys for different methods. Like:

@Cacheable(value="bookCache", 
  key="{ #root.methodName, #isbn?.id, #checkWarehouse }")
public Book findBook(ISBN isbn, boolean checkWarehouse) 
...

@Cacheable(value="bookCache", 
  key="{ #root.methodName, #asin, #checkWarehouse }")
public Book findBookByAmazonId(String asin, boolean checkWarehouse)
...

Of course, if many methods need this and you're always using all parameters for your key, then one can also define a custom key generator that includes the class and method name:

<cache:annotation-driven mode="..." key-generator="cacheKeyGenerator" />
<bean id="cacheKeyGenerator" class="net.example.cache.CacheKeyGenerator" />

...with:

public class CacheKeyGenerator 
  implements org.springframework.cache.interceptor.KeyGenerator {

    @Override
    public Object generate(final Object target, final Method method, 
      final Object... params) {

        final List<Object> key = new ArrayList<>();
        key.add(method.getDeclaringClass().getName());
        key.add(method.getName());

        for (final Object o : params) {
            key.add(o);
        }
        return key;
    }
}

Boolean operators && and ||

The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.

When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.

> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3

The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.

Understanding the Gemfile.lock file

It seems no clear document talking on the Gemfile.lock format. Maybe it's because Gemfile.lock is just used by bundle internally.

However, since Gemfile.lock is a snapshot of Gemfile, which means all its information should come from Gemfile (or from default value if not specified in Gemfile).

For GEM, it lists all the dependencies you introduce directly or indirectly in the Gemfile. remote under GEM tells where to get the gems, which is specified by source in Gemfile.

If a gem is not fetch from remote, PATH tells the location to find it. PATH's info comes from path in Gemfile when you declare a dependency.

And PLATFORM is from here.

For DEPENDENCIES, it's the snapshot of dependencies resolved by bundle.

jQuery same click event for multiple elements

We can code like following also, I have used blur event here.

$("#proprice, #proqty").blur(function(){
      var price=$("#proprice").val();
      var qty=$("#proqty").val();
      if(price != '' || qty != '')
      {
          $("#totalprice").val(qty*price);
      }
  });

How to print float to n decimal places including trailing 0s?

Floating point numbers lack precision to accurately represent "1.6" out to that many decimal places. The rounding errors are real. Your number is not actually 1.6.

Check out: http://docs.python.org/library/decimal.html

commons httpclient - Adding query string parameters to GET/POST request

The HttpParams interface isn't there for specifying query string parameters, it's for specifying runtime behaviour of the HttpClient object.

If you want to pass query string parameters, you need to assemble them on the URL yourself, e.g.

new HttpGet(url + "key1=" + value1 + ...);

Remember to encode the values first (using URLEncoder).

How do I create an iCal-type .ics file that can be downloaded by other users?

That will work just fine. You can export an entire calendar with File > Export…, or individual events by dragging them to the Finder.

iCalendar (.ics) files are human-readable, so you can always pop it open in a text editor to make sure no private events made it in there. They consist of nested sections with start with BEGIN: and end with END:. You'll mostly find VEVENT sections (each of which represents an event) and VTIMEZONE sections, each of which represents a time zone that's referenced from one or more events.

How to connect to local instance of SQL Server 2008 Express

Haha, oh boy, I figured it out. Somehow, someway, I did not install the Database Engine when I installed SQL Server 2008. I have no idea how I missed that, but that's what happened.

Less than or equal to

There is no => for if.
Use if %energy% GEQ %m2enc%

See if /? for some other details.

how to add or embed CKEditor in php page

If you have downloaded the latest Version 4.3.4 then just follow these steps.

  • Download the package, unzip and place in your web directory or root folder.
  • Provide the read write permissions to that folder (preferably Ubuntu machines )
  • Create view page test.php
  • Paste the below mentioned code it should work fine.

Load the mentioned js file

<script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
<textarea class="ckeditor" name="editor"></textarea>

Remove an item from a dictionary when its key is unknown

y={'username':'admin','machine':['a','b','c']}
if 'c' in y['machine'] : del y['machine'][y['machine'].index('c')]

How to force IE to reload javascript?

When you work with web page or javascript file you want it to be reloaded every time you change it. You can change settings in IE 8 so the browser will never cache.

Follow this simple steps.

  1. Select Tools-> Internet Options.
  2. In General tab click on Settings button in Browsing history section.
  3. Click on "Every time I visit the webpage" radio button.
  4. Click OK button.

How to get the mobile number of current sim card in real device?

Sometimes you can retreive the phonenumber with a USSD request to your operator. For example I can get my phonenumber by dialing *116# This can probably be done within an app, I guess, if the USSD responce somehow could be catched. Offcourse this is not a method I would recommend to use within an app that is to be distributed, the code may even differ between operators.

How can you encode a string to Base64 in JavaScript?

Internet Explorer 10+

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

Cross-Browser

// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

jsFiddle


with Node.js

Here is how you encode normal text to base64 in Node.js:

//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter. 
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = new Buffer('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');

And here is how you decode base64 encoded strings:

var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();

with Dojo.js

To encode an array of bytes using dojox.encoding.base64:

var str = dojox.encoding.base64.encode(myByteArray);

To decode a base64-encoded string:

var bytes = dojox.encoding.base64.decode(str)

bower install angular-base64

<script src="bower_components/angular-base64/angular-base64.js"></script>

angular
    .module('myApp', ['base64'])
    .controller('myController', [

    '$base64', '$scope', 
    function($base64, $scope) {

        $scope.encoded = $base64.encode('a string');
        $scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);

Rounded corner for textview in android

Since your top level view already has android:background property set, you can use a <layer-list> (link) to create a new XML drawable that combines both your old background and your new rounded corners background.

Each <item> element in the list is drawn over the next, so the last item in the list is the one that ends up on top.

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/mydialogbox" />
    </item>
    <item>
        <shape>
            <stroke
                android:width="1dp"
                android:color="@color/common_border_color" />

            <solid android:color="#ffffff" />

            <padding
                    android:left="1dp"
                    android:right="1dp"
                    android:top="1dp" />

            <corners android:radius="5dp" />
        </shape>
    </item>
</layer-list>

How to upgrade Git to latest version on macOS?

if using homebrew you can update sim links using

brew link --overwrite git

Regular expression for first and last name

I'm working on the app that validates International Passports (ICAO). We support only english characters. While most foreign national characters can be represented by a character in the Latin alphabet e.g. è by e, there are several national characters that require an extra letter to represent them such as the German umlaut which requires an ‘e’ to be added to the letter e.g. ä by ae.

This is the JavaScript Regex for the first and last names we use:

/^[a-zA-Z '.-]*$/

The max number of characters on the international passport is up to 31. We use maxlength="31" to better word error messages instead of including it in the regex.

Here is a snippet from our code in AngularJS 1.6 with form and error handling:

_x000D_
_x000D_
class PassportController {_x000D_
  constructor() {_x000D_
    this.details = {};_x000D_
    // English letters, spaces and the following symbols ' - . are allowed_x000D_
    // Max length determined by ng-maxlength for better error messaging_x000D_
    this.nameRegex = /^[a-zA-Z '.-]*$/;_x000D_
  }_x000D_
}_x000D_
_x000D_
angular.module('akyc', ['ngMessages'])_x000D_
  .controller('PassportController', PassportController);
_x000D_
 _x000D_
.has-error p[ng-message] {_x000D_
  color: #bc111e;_x000D_
}_x000D_
_x000D_
.tip {_x000D_
  color: #535f67;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>_x000D_
<script src="https://code.angularjs.org/1.6.6/angular-messages.min.js"></script>_x000D_
_x000D_
<main ng-app="akyc" ng-controller="PassportController as $ctrl">_x000D_
  <form name="$ctrl.form">_x000D_
_x000D_
    <div name="lastName" ng-class="{ 'has-error': $ctrl.form.lastName.$invalid} ">_x000D_
        <label for="pp-last-name">Surname</label>_x000D_
        <div class="tip">Exactly as it appears on your passport</div>_x000D_
        <div ng-messages="$ctrl.form.lastName.$error" ng-if="$ctrl.form.$submitted" id="last-name-error">_x000D_
          <p ng-message="required">Please enter your last name</p>_x000D_
          <p ng-message="maxlength">This field can be at most 31 characters long</p>_x000D_
          <p ng-message="pattern">Only English letters, spaces and the following symbols ' - . are allowed</p>_x000D_
        </div>_x000D_
        _x000D_
        <input type="text" id="pp-last-name" ng-model="$ctrl.details.lastName" name="lastName"_x000D_
               class="form-control" required ng-pattern="$ctrl.nameRegex" ng-maxlength="31" aria-describedby="last-name-error" />_x000D_
      </div>_x000D_
_x000D_
      <button type="submit" class="btn btn-primary">Test</button>_x000D_
_x000D_
  </form>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Creating a singleton in Python

  • If one wants to have multiple number of instances of the same class, but only if the args or kwargs are different, one can use the third-party python package Handy Decorators (package decorators).
  • Ex.
    1. If you have a class handling serial communication, and to create an instance you want to send the serial port as an argument, then with traditional approach won't work
    2. Using the above mentioned decorators, one can create multiple instances of the class if the args are different.
    3. For same args, the decorator will return the same instance which is already been created.
>>> from decorators import singleton
>>>
>>> @singleton
... class A:
...     def __init__(self, *args, **kwargs):
...         pass
...
>>>
>>> a = A(name='Siddhesh')
>>> b = A(name='Siddhesh', lname='Sathe')
>>> c = A(name='Siddhesh', lname='Sathe')
>>> a is b  # has to be different
False
>>> b is c  # has to be same
True
>>>

CSS content generation before or after 'input' elements

Use tags label and our method for =, is bound to input. If follow the rules of the form, and avoid confusion with tags, use the following:

<style type="text/css">
    label.lab:before { content: 'input: '; }
</style>

or compare (short code):

<style type="text/css">
    div label { content: 'input: '; color: red; }
</style>

form....

<label class="lab" for="single"></label><input name="n" id="single" ...><label for="single"> - simle</label>

or compare (short code):

<div><label></label><input name="n" ...></div>

Are these methods thread safe?

The only problem with threads is accessing the same object from different threads without synchronization.

If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.

What to use now Google News API is deprecated?

I'm running into the same issue with one of my own apps. So far I've found the only non-deprecated way to access Google News data is through their RSS feeds. They have a feed for each section and also a useful search function. However, these are only for noncommercial use.

As for viable alternatives I'll be trying out these two services: Feedzilla, Daylife

struct in class

Your E class doesn't have a member of type struct X, you've just defined a nested struct X in there (i.e. you've defined a new type).

Try:

#include <iostream>

class E
{
    public: 
    struct X { int v; };
    X x; // an instance of `struct X`
};

int main(){

    E object;
    object.x.v = 1;

    return 0;
}

Unknown SSL protocol error in connection

In many cases it is linked to proxy problems. If so just config your git proxy

git config --global http.proxy HOST:PORT

AppSettings get value from .config file

This works for me:

string value = System.Configuration.ConfigurationManager.AppSettings[key];

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

I'd create a cte and do an inner join. It's not efficient but it's convenient

with table as (
SELECT DATE, STATUS, TITLE, ROW_NUMBER() 
OVER (PARTITION BY DATE, STATUS,  TITLE ORDER BY QUANTITY ASC) AS Row_Num
 FROM TABLE)

select *

from table t
join select(
max(Row_Num) as Row_Num
,DATE
,STATUS
,TITLE
from table 
group by date, status, title) t2  
on t2.Row_Num = t.Row_Num and t2
and t2.date = t.date
and t2.title = t.title

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Try to remove any trace of cocoapods pods using pod deintegrate then Run pod install

How do I format XML in Notepad++?

OK, here is how I did it in Notepad++:

  • Plugins
  • Plugin manager
  • Show plugin manager
  • Check XML tools
  • Install
  • Restart Notepad++
  • Open XML file
  • Plugins
  • XML tools
  • Pretty print (XML only -- with line breaks)

How to read a file line-by-line into a list?

If you want to are faced with a very large / huge file and want to read faster (imagine you are in a Topcoder/Hackerrank coding competition), you might read a considerably bigger chunk of lines into a memory buffer at one time, rather than just iterate line by line at file level.

buffersize = 2**16
with open(path) as f: 
    while True:
        lines_buffer = f.readlines(buffersize)
        if not lines_buffer:
            break
        for line in lines_buffer:
            process(line)

Bootstrap 3 dropdown select

We just switched our site to bootstrap 3 and we have a bunch of forms...wasn't fun but once you get the hang it's not too bad.

Is this what you are looking for? Demo Here

<div class="form-group">
  <label class="control-label col-sm-offset-2 col-sm-2" for="company">Company</label>
  <div class="col-sm-6 col-md-4">
    <select id="company" class="form-control">
      <option>small</option>
      <option>medium</option>
      <option>large</option>
    </select> 
  </div>
</div>

jQuery Multiple ID selectors

You can use multiple id's the way you wrote:

$('#upload_link, #upload_link2, #upload_link3')

However, that doesn't mean that those ids exist within the DOM when you've executed your code. It also doesn't mean that upload is a legitimate function. It also doesn't mean that upload has been built in a way that allows for multiple elements in a selection.

upload is a custom jQuery plugin, so you'll have to show what's going on with upload for us to be able to help you.

Avoiding NullPointerException in Java

I'm a fan of "fail fast" code. Ask yourself - are you doing something useful in the case where the parameter is null? If you don't have a clear answer for what your code should do in that case... I.e. it should never be null in the first place, then ignore it and allow a NullPointerException to be thrown. The calling code will make just as much sense of an NPE as it would an IllegalArgumentException, but it'll be easier for the developer to debug and understand what went wrong if an NPE is thrown rather than your code attempting to execute some other unexpected contingency logic - which ultimately results in the application failing anyway.

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

The same thing was when I've created a new Configuration and Build Scheme.

So the solution for me was to run

pod install

for this newly created Configuration.

Laravel 5.4 redirection to custom url after login

If you look in the AuthenticatesUsers trait you will see that in the sendLoginResponse method that there is a call made to $this->redirectPath(). If you look at this method then you will discover that the redirectTo can either be a method or a variable.

This is what I now have in my auth controller.

public function redirectTo() {
    $user = Auth::user();
    switch(true) {
        case $user->isInstructor():
            return '/instructor';
        case $user->isAdmin():
        case $user->isSuperAdmin():
            return '/admin';
        default:
            return '/account';
    }
}

How can I provide multiple conditions for data trigger in WPF?

@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)

but if you have values other than boolean try using type converters:

<MultiDataTrigger.Conditions>
    <Condition Value="True">
        <Condition.Binding>
            <MultiBinding Converter="{StaticResource conditionConverter}">
                <Binding Path="Name" />
                <Binding Path="State" />
            </MultiBinding>
        </Condition.Binding>
        <Setter Property="Background" Value="Cyan" />
    </Condition>
</MultiDataTrigger.Conditions>

you can use the values in Convert method any way you like to produce a condition which suits you.

PHP mySQL - Insert new record into table with auto-increment on primary key

You can also use blank single quotes for the auto_increment column. something like this. It worked for me.

$query = "INSERT INTO myTable VALUES ('','Fname', 'Lname', 'Website')";

T-SQL string replace in Update

The syntax for REPLACE:

REPLACE (string_expression,string_pattern,string_replacement)

So that the SQL you need should be:

UPDATE [DataTable] SET [ColumnValue] = REPLACE([ColumnValue], 'domain2', 'domain1')

Angular 2 Date Input not binding to date value

Angular 2 completely ignores type=date. If you change type to text you'll see that your input has two-way binding.

<input type='text' #myDate [(ngModel)]='demoUser.date'/><br>

Here is pretty bad advise with better one to follow:

My project originally used jQuery. So, I'm using jQuery datepicker for now, hoping that angular team will fix the original issue. Also it's a better replacement because it has cross-browser support. FYI, input=date doesn't work in Firefox.

Good advise: There are few pretty good Angular2 datepickers:

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

How do I print out the contents of a vector?

How about for_each + lambda expression:

#include <vector>
#include <algorithm>
// ...
std::vector<char> vec;
// ...
std::for_each(
              vec.cbegin(),
              vec.cend(),
              [] (const char c) {std::cout << c << " ";} 
              );
// ...

Of course, a range-based for is the most elegant solution for this concrete task, but this one gives many other possibilities as well.

Explanation

The for_each algorithm takes an input range and a callable object, calling this object on every element of the range. An input range is defined by two iterators. A callable object can be a function, a pointer to function, an object of a class which overloads () operator or as in this case, a lambda expression. The parameter for this expression matches the type of the elements from vector.

The beauty of this implementation is the power you get from lambda expressions - you can use this approach for a lot more things than just printing the vector.

How to initialize private static members in C++?

With a Microsoft compiler[1], static variables that are not int-like can also be defined in a header file, but outside of the class declaration, using the Microsoft specific __declspec(selectany).

class A
{
    static B b;
}

__declspec(selectany) A::b;

Note that I'm not saying this is good, I just say it can be done.

[1] These days, more compilers than MSC support __declspec(selectany) - at least gcc and clang. Maybe even more.

How can I quickly delete a line in VIM starting at the cursor position?

This is a very old question, but as VIM is still relevant something should be clarified.

Every answer and comment here as of October 2018 has referred to what would commonly be known as a "cut" action, thus using any of them will replace whatever is currently in VIM's unnamed register. This register tends to be treated like a default copy/paste clipboard, so none of these answers will work as desired if you are deleting the rest of a line to paste something in the same place afterward, as whatever was just deleted will be subsequently pasted in place of whatever was yanked before.

The true delete command in the OP's context is "_D (or "_C if insert mode is desired) This sends the deleted content into the black hole register, designated by "_, where it will bother no one ever again (although you can still undo this action using u).

That being said, whatever was last yanked is stored in the 0 register, and even if it gets replaced in the unnamed register, it can still be pasted using "0p.

Learn more about the black hole register and registers in general for extra VIM fun!

How to get a single value from FormGroup

Another option:

this.form.value['nameOfControl']

Combine two columns of text in pandas dataframe

Using zip could be even quicker:

df["period"] = [''.join(i) for i in zip(df["Year"].map(str),df["quarter"])]

Graph:

enter image description here

import pandas as pd
import numpy as np
import timeit
import matplotlib.pyplot as plt
from collections import defaultdict

df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})

myfuncs = {
"df['Year'].astype(str) + df['quarter']":
    lambda: df['Year'].astype(str) + df['quarter'],
"df['Year'].map(str) + df['quarter']":
    lambda: df['Year'].map(str) + df['quarter'],
"df.Year.str.cat(df.quarter)":
    lambda: df.Year.str.cat(df.quarter),
"df.loc[:, ['Year','quarter']].astype(str).sum(axis=1)":
    lambda: df.loc[:, ['Year','quarter']].astype(str).sum(axis=1),
"df[['Year','quarter']].astype(str).sum(axis=1)":
    lambda: df[['Year','quarter']].astype(str).sum(axis=1),
    "df[['Year','quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)":
    lambda: df[['Year','quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1),
    "[''.join(i) for i in zip(dataframe['Year'].map(str),dataframe['quarter'])]":
    lambda: [''.join(i) for i in zip(df["Year"].map(str),df["quarter"])]
}

d = defaultdict(dict)
step = 10
cont = True
while cont:
    lendf = len(df); print(lendf)
    for k,v in myfuncs.items():
        iters = 1
        t = 0
        while t < 0.2:
            ts = timeit.repeat(v, number=iters, repeat=3)
            t = min(ts)
            iters *= 10
        d[k][lendf] = t/iters
        if t > 2: cont = False
    df = pd.concat([df]*step)

pd.DataFrame(d).plot().legend(loc='upper center', bbox_to_anchor=(0.5, -0.15))
plt.yscale('log'); plt.xscale('log'); plt.ylabel('seconds'); plt.xlabel('df rows')
plt.show()

Select first empty cell in column F starting from row 1. (without using offset )

I just wrote this one-liner to select the first empty cell found in a column based on a selected cell. Only works on first column of selected cells. Modify as necessary

Selection.End(xlDown).Range("A2").Select

How to detect a textbox's content has changed

do you consider using change event ?

$("#myTextBox").change(function() { alert("content changed"); });

How to convert any date format to yyyy-MM-dd

This is your primary problem:

The source date could be anything like dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.

If you're given 01/02/2013, is it Jan 2 or Feb 1? You should solve this problem first and parsing the input will be much easier.

I suggest you take a step back and explore what you are trying to solve in more detail.

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

If you want to fill NaN for a specific column you can use loc:

d1 = {"Col1" : ['A', 'B', 'C'],
     "fruits": ['Avocado', 'Banana', 'NaN']}
d1= pd.DataFrame(d1)

output:

Col1    fruits
0   A   Avocado
1   B   Banana
2   C   NaN


d1.loc[ d1.Col1=='C', 'fruits' ] =  'Carrot'


output:

Col1    fruits
0   A   Avocado
1   B   Banana
2   C   Carrot

How can I force input to uppercase in an ASP.NET textbox?

  <telerik:RadTextBox ID="txtCityName" runat="server" MaxLength="50" Width="200px"
                            Style="text-transform: uppercase;">

Close popup window

Your web_window variable must have gone out of scope when you tried to close the window. Add this line into your _openpageview function to test:

setTimeout(function(){web_window.close();},1000);

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

As it turns out, my suspicions were right. The audience aud claim in a JWT is meant to refer to the Resource Servers that should accept the token.

As this post simply puts it:

The audience of a token is the intended recipient of the token.

The audience value is a string -- typically, the base address of the resource being accessed, such as https://contoso.com.

The client_id in OAuth refers to the client application that will be requesting resources from the Resource Server.

The Client app (e.g. your iOS app) will request a JWT from your Authentication Server. In doing so, it passes it's client_id and client_secret along with any user credentials that may be required. The Authorization Server validates the client using the client_id and client_secret and returns a JWT.

The JWT will contain an aud claim that specifies which Resource Servers the JWT is valid for. If the aud contains www.myfunwebapp.com, but the client app tries to use the JWT on www.supersecretwebapp.com, then access will be denied because that Resource Server will see that the JWT was not meant for it.

Get img src with PHP

There could be two easy solutions:

  1. HTML it self is an xml so you can use any XML parsing method if u load the tag as XML and get its attribute tottally dynamically even dom data attribute (like data-time or anything).....
  2. Use any html parser for php like http://mbe.ro/2009/06/21/php-html-to-array-working-one/ or php parse html to array Google this

MySQL combine two columns into one column

I have used this way and Its a best forever. In this code null also handled

SELECT Title,
FirstName,
lastName, 
ISNULL(Title,'') + ' ' + ISNULL(FirstName,'') + ' ' + ISNULL(LastName,'') as FullName 
FROM Customer

Try this...

Drawing an image from a data URL to a canvas

Given a data URL, you can create an image (either on the page or purely in JS) by setting the src of the image to your data URL. For example:

var img = new Image;
img.src = strDataURI;

The drawImage() method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.

You might use it like so:

var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
  ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;

Edit: I previously suggested in this space that it might not be necessary to use the onload handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload to use the new image, and then set the src—is necessary for some browsers to surely use the results.

How to find a hash key containing a matching value

You could use hashname.key(valuename)

Or, an inversion may be in order. new_hash = hashname.invert will give you a new_hash that lets you do things more traditionally.

How to convert InputStream to FileInputStream

Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.

URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...

If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.

Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

Regular expression to match a dot

to escape non-alphanumeric characters of string variables, including dots, you could use re.escape:

import re

expression = 'whatever.v1.dfc'
escaped_expression = re.escape(expression)
print(escaped_expression)

output:

whatever\.v1\.dfc

you can use the escaped expression to find/match the string literally.

Parsing arguments to a Java command line program

You could use the refcodes-console artifact at refcodes-console on REFCODES.ORG:

Option<String> r     = new StringOptionImpl( "-r", null, "opt1", "..." );
Option<String> s     = new StringOptionImpl( "-S", null, "opt2", "..." );
Operand<String> arg1 = new StringOperandImpl( "arg1", "..." );
Operand<String> arg2 = new StringOperandImpl( "arg2", "..." );
Operand<String> arg3 = new StringOperandImpl( "arg3", "..." );
Operand<String> arg4 = new StringOperandImpl( "arg4", "..." );
Switch test          = new SwitchImpl( null, "--test", "..." );
Option<String> a     = new StringOptionImpl( "-A", null, "opt3", "..." );
Condition theRoot    = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4,
    test );

Create your arguments parser ArgsParserImpl with your root condition:

ArgsParser theArgsParser = new ArgsParserImpl( theRoot );
theArgsParser.setName( "MyProgramm" );
theArgsParser.setSyntaxNotation( SyntaxNotation.GNU_POSIX );

Above you define your syntax, below you invoke the parser:

theArgsParser.printUsage();
theArgsParser.printSeparatorLn();
theArgsParser.printOptions();
theArgsParser.evalArgs( new String[] {
    "-r", "RRRRR", "-S", "SSSSS", "11111", "22222", "33333", "44444", 
    "--test", "-A", "AAAAA"
} );

In case you provided some good descriptions, theArgsParser.printUsage() will even show you the pretty printed usage:

Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 --test

In the above example all defined arguments must be passed by the user, else the parser will detect a wrong usage. In case the --test switch is to be optional (or any other argument), assign theRoot as follows:

theRoot = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4, new OptionalImpl( test ) );

Then your syntax looks as follows:

Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 [--test]

The full example for your case you find in the StackOverFlowExamle. You can use AND, OR, XOR conditions and any kind of nesting ... hope this helps.

Evaluate the parsed arguments as follows: r.getValue() ); or if (test.getValue() == true) ...:

LOGGER.info( "r    :=" + r.getValue() );
LOGGER.info( "S    :=" + s.getValue() );
LOGGER.info( "arg1 :=" + arg1.getValue() );
LOGGER.info( "arg2 :=" + arg2.getValue() );
LOGGER.info( "arg3 :=" + arg3.getValue() );
LOGGER.info( "arg4 :=" + arg4.getValue() );
LOGGER.info( "test :=" + test.getValue() + "" );
LOGGER.info( "A    :=" + a.getValue() );

Retaining file permissions with Git

Git is Version Control System, created for software development, so from the whole set of modes and permissions it stores only executable bit (for ordinary files) and symlink bit. If you want to store full permissions, you need third party tool, like git-cache-meta (mentioned by VonC), or Metastore (used by etckeeper). Or you can use IsiSetup, which IIRC uses git as backend.

See Interfaces, frontends, and tools page on Git Wiki.

Finding the direction of scrolling in a UIScrollView?

Alternatively, it is possible to observe key path "contentOffset". This is useful when it's not possible for you to set/change the delegate of the scroll view.

[yourScrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

After adding the observer, you could now:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    CGFloat newOffset = [[change objectForKey:@"new"] CGPointValue].y;
    CGFloat oldOffset = [[change objectForKey:@"old"] CGPointValue].y;
    CGFloat diff = newOffset - oldOffset;
    if (diff < 0 ) { //scrolling down
        // do something
    }
}

Do remember to remove the observer when needed. e.g. you could add the observer in viewWillAppear and remove it in viewWillDisappear

How to get current relative directory of your Makefile?

If you are using GNU make, $(CURDIR) is actually a built-in variable. It is the location where the Makefile resides the current working directory, which is probably where the Makefile is, but not always.

OUTPUT_PATH = /project1/bin/$(notdir $(CURDIR))

See Appendix A Quick Reference in http://www.gnu.org/software/make/manual/make.html

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

As of Android N, in order to work around this issue, you need to use the FileProvider API

There are 3 main steps here as mentioned below

Step 1: Manifest Entry

<manifest ...>
    <application ...>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
</manifest>

Step 2: Create XML file res/xml/provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Step 3: Code changes

File file = ...;
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
// Old Approach
    install.setDataAndType(Uri.fromFile(file), mimeType);
// End Old approach
// New Approach
    Uri apkURI = FileProvider.getUriForFile(
                             context, 
                             context.getApplicationContext()
                             .getPackageName() + ".provider", file);
    install.setDataAndType(apkURI, mimeType);
    install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// End New Approach
    context.startActivity(install);

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Please try this code

new_column=df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).count()
df['count_it']=new_column
df

I think that code will add a column called 'count it' which count of each group

How to handle checkboxes in ASP.NET MVC forms?

Same as nautic20's answer, just simply use MVC default model binding checkbox list with same name as a collection property of string/int/enum in ViewModel. That is it.

But one issue need to point out. In each checkbox component, you should not put "Id" in it which will affect MVC model binding.

Following code will work for model binding:

 <% foreach (var item in Model.SampleObjectList)
       { %>
        <tr>
            <td><input type="checkbox" name="SelectedObjectIds" value="<%= item.Id%>" /></td>
            <td><%= Html.Encode(item.Name)%></td>
        </tr>
 <% } %>

Following codes will not binding to model (difference here is it assigned id for each checkbox)

<% foreach (var item in Model.SampleObjectList)
       { %>
        <tr>
            <td><input type="checkbox" name="SelectedObjectIds" id="[some unique key]" value="<%= item.Id%>" /></td>
            <td><%= Html.Encode(item.Name)%></td>
        </tr>
<% } %>

Align DIV's to bottom or baseline

You would probably would have to set the child div to have position: absolute.

Update your child style to

#parentDiv .childDiv
{
  height:100px;
  width:30px;
  background-color:#999;
  position:absolute;
  top:207px;
}

JavaScript getElementByID() not working

Because when the script executes the browser has not yet parsed the <body>, so it does not know that there is an element with the specified id.

Try this instead:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = (function () {
            var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('Dhoor shala!');
            };
        });
    </script>
    </head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
</form>
</body>
</html>

Note that you may as well use addEventListener instead of window.onload = ... to make that function only execute after the whole document has been parsed.

Call child component method from parent class - Angular

user6779899's answer is neat and more generic However, based on the request by Imad El Hitti, a light weight solution is proposed here. This can be used when a child component is tightly connected to one parent only.

Parent.component.ts

export class Notifier {
    valueChanged: (data: number) => void = (d: number) => { };
}

export class Parent {
    notifyObj = new Notifier();
    tellChild(newValue: number) {
        this.notifyObj.valueChanged(newValue); // inform child
    }
}

Parent.component.html

<my-child-comp [notify]="notifyObj"></my-child-comp>

Child.component.ts

export class ChildComp implements OnInit{
    @Input() notify = new Notifier(); // create object to satisfy typescript
    ngOnInit(){
      this.notify.valueChanged = (d: number) => {
            console.log(`Parent has notified changes to ${d}`);
            // do something with the new value 
        };
    }
 }

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I faced this issue when I integrated spring boot with spring mvc. I solved it by just adding these dependencies.

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

convert string array to string

Aggregate can also be used for same.

string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string joinedString = test.Aggregate((prev, current) => prev + " " + current);

Error :The remote server returned an error: (401) Unauthorized

The answers did help, but I think a full implementation of this will help a lot of people.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Dom
{
    class Dom
    {
        public static string make_Sting_From_Dom(string reportname)
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                // Retrieve resource as a stream               
                Stream data = client.OpenRead(new Uri(reportname.Trim()));
                // Retrieve the text
                StreamReader reader = new StreamReader(data);
                string htmlContent = reader.ReadToEnd();
                string mtch = "TILDE";
                bool b = htmlContent.Contains(mtch);

                if (b)
                {
                    int index = htmlContent.IndexOf(mtch);
                    if (index >= 0)
                        Console.WriteLine("'{0} begins at character position {1}",
                        mtch, index + 1);
                }
                // Cleanup
                data.Close();
                reader.Close();
                return htmlContent;
            }
            catch (Exception)
            {
                throw;
            }
        }

        static void Main(string[] args)
        {
            make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
        }
    }
}

How to manually set an authenticated user in Spring Security / SpringMVC

The new filtering feature in Servlet 2.4 basically alleviates the restriction that filters can only operate in the request flow before and after the actual request processing by the application server. Instead, Servlet 2.4 filters can now interact with the request dispatcher at every dispatch point. This means that when a Web resource forwards a request to another resource (for instance, a servlet forwarding the request to a JSP page in the same application), a filter can be operating before the request is handled by the targeted resource. It also means that should a Web resource include the output or function from other Web resources (for instance, a JSP page including the output from multiple other JSP pages), Servlet 2.4 filters can work before and after each of the included resources. .

To turn on that feature you need:

web.xml

<filter>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter>  
<filter-mapping>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <url-pattern>/<strike>*</strike></url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

RegistrationController

return "forward:/login?j_username=" + registrationModel.getUserEmail()
        + "&j_password=" + registrationModel.getPassword();

Convert Rtf to HTML

You can try to upload it to google docs, and download it as HTML.

How to convert enum value to int?

I prefer this:

public enum Color {

   White,

   Green,

   Blue,

   Purple,

   Orange,

   Red
}

then:

//cast enum to int
int color = Color.Blue.ordinal();

Create a string and append text to it

Another way to do this is to add the new characters to the string as follows:

Dim str As String

str = ""

To append text to your string this way:

str = str & "and this is more text"

Simulating ENTER keypress in bash script

Here is sample usage using expect:

#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }

Check: man expect for further information.

Sending HTTP Post request with SOAP action using org.apache.http

It was giving 415 Http response Code as error,

So I added

httppost.addHeader("Content-Type", "text/xml; charset=utf-8");

Everything alright now, Http: 200

how to use a like with a join in sql?

Using INSTR:

SELECT *
  FROM TABLE a
  JOIN TABLE b ON INSTR(b.column, a.column) > 0

Using LIKE:

SELECT *
  FROM TABLE a
  JOIN TABLE b ON b.column LIKE '%'+ a.column +'%'

Using LIKE, with CONCAT:

SELECT *
  FROM TABLE a
  JOIN TABLE b ON b.column LIKE CONCAT('%', a.column ,'%')

Mind that in all options, you'll probably want to drive the column values to uppercase BEFORE comparing to ensure you are getting matches without concern for case sensitivity:

SELECT *
  FROM (SELECT UPPER(a.column) 'ua'
         TABLE a) a
  JOIN (SELECT UPPER(b.column) 'ub'
         TABLE b) b ON INSTR(b.ub, a.ua) > 0

The most efficient will depend ultimately on the EXPLAIN plan output.

JOIN clauses are identical to writing WHERE clauses. The JOIN syntax is also referred to as ANSI JOINs because they were standardized. Non-ANSI JOINs look like:

SELECT *
  FROM TABLE a,
       TABLE b
 WHERE INSTR(b.column, a.column) > 0

I'm not going to bother with a Non-ANSI LEFT JOIN example. The benefit of the ANSI JOIN syntax is that it separates what is joining tables together from what is actually happening in the WHERE clause.

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

read word by word from file in C++

First of all, don't loop while (!eof()), it will not work as you expect it to because the eofbit will not be set until after a failed read due to end of file.

Secondly, the normal input operator >> separates on whitespace and so can be used to read "words":

std::string word;
while (file >> word)
{
    ...
}

Passing Arrays to Function in C++

The syntaxes

int[]

and

int[X] // Where X is a compile-time positive integer

are exactly the same as

int*

when in a function parameter list (I left out the optional names).

Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3] and int secondarray[5] decay to int*s.

It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]) yield an lvalue to the same element when you use the same index.

These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

jQuery callback for multiple ajax calls

I came across this problem today, and this was my naive attempt before watching the accepted answer.

<script>
    function main() {
        var a, b, c
        var one = function() {
            if ( a != undefined  && b != undefined && c != undefined ) {
                alert("Ok")
            } else {
                alert( "¬¬ ")
            }
        }

        fakeAjaxCall( function() {
            a = "two"
            one()
        } )
        fakeAjaxCall( function() {
            b = "three"
            one()
        } )
        fakeAjaxCall( function() {
            c = "four"
            one()
        } )
    }
    function fakeAjaxCall( a ) {
        a()
    }
    main()
</script>

How to drop column with constraint?

Here's another way to drop a default constraint with an unknown name without having to first run a separate query to get the constraint name:

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'__ColumnName__'
                        AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)

What's the difference between Apache's Mesos and Google's Kubernetes

"I understand both are server cluster management software."

This statement isn't entirely true. Kubernetes doesn't manage server clusters, it orchestrates containers such that they work together with minimal hassle and exposure. Kubernetes allows you to define parts of your application as "pods" (one or more containers) that are delivered by "deployments" or "daemon sets" (and a few others) and exposed to the outside world via services. However, Kubernetes doesn't manage the cluster itself (there are tools that can provision, configure and scale clusters for you, but those are not part of Kubernetes itself).

Mesos on the other hand comes closer to "cluster management" in that it can control what's running where, but not just in terms of scheduling containers. Mesos also manages standalone software running on the cluster servers. Even though it's mostly used as an alternative to Kubernetes, Mesos can easily work with Kubernetes as while the functionality overlaps in many areas, Mesos can do more (but on the overlapping parts Kubernetes tends to be better).

How can I sort a List alphabetically?

Solution with Collections.sort

If you are forced to use that List, or if your program has a structure like

  • Create List
  • Add some country names
  • sort them once
  • never change that list again

then Thilos answer will be the best way to do it. If you combine it with the advice from Tom Hawtin - tackline, you get:

java.util.Collections.sort(listOfCountryNames, Collator.getInstance());

Solution with a TreeSet

If you are free to decide, and if your application might get more complex, then you might change your code to use a TreeSet instead. This kind of collection sorts your entries just when they are inserted. No need to call sort().

Collection<String> countryNames = 
    new TreeSet<String>(Collator.getInstance());
countryNames.add("UK");
countryNames.add("Germany");
countryNames.add("Australia");
// Tada... sorted.

Side note on why I prefer the TreeSet

This has some subtle, but important advantages:

  • It's simply shorter. Only one line shorter, though.
  • Never worry about is this list really sorted right now becaude a TreeSet is always sorted, no matter what you do.
  • You cannot have duplicate entries. Depending on your situation this may be a pro or a con. If you need duplicates, stick to your List.
  • An experienced programmer looks at TreeSet<String> countyNames and instantly knows: this is a sorted collection of Strings without duplicates, and I can be sure that this is true at every moment. So much information in a short declaration.
  • Real performance win in some cases. If you use a List, and insert values very often, and the list may be read between those insertions, then you have to sort the list after every insertion. The set does the same, but does it much faster.

Using the right collection for the right task is a key to write short and bug free code. It's not as demonstrative in this case, because you just save one line. But I've stopped counting how often I see someone using a List when they want to ensure there are no duplictes, and then build that functionality themselves. Or even worse, using two Lists when you really need a Map.

Don't get me wrong: Using Collections.sort is not an error or a flaw. But there are many cases when the TreeSet is much cleaner.

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

Conditional replacement of values in a data.frame

Try data.table's := operator :

DT = as.data.table(df)
DT[b==0, est := (a-5)/2.533]

It's fast and short. See these linked questions for more information on := :

Why has data.table defined :=

When should I use the := operator in data.table

How do you remove columns from a data.frame

R self reference

Reference an Element in a List of Tuples

Here's a quick example:

termList = []
termList.append(('term1', [1,2,3,4]))
termList.append(('term2', [5,6,7,8]))
termList.append(('term3', [9,10,11,12]))

result = [x[1] for x in termList if x[0] == 'term3']

print(result)

Use Awk to extract substring

You just want to set the field separator as . using the -F option and print the first field:

$ echo aaa0.bbb.ccc | awk -F'.' '{print $1}'
aaa0

Same thing but using cut:

$ echo aaa0.bbb.ccc | cut -d'.' -f1
aaa0

Or with sed:

$ echo aaa0.bbb.ccc | sed 's/[.].*//'
aaa0

Even grep:

$ echo aaa0.bbb.ccc | grep -o '^[^.]*'
aaa0

Check if key exists in JSON object using jQuery

Use JavaScript's hasOwnProperty() function:

if (json_object.hasOwnProperty('name')) {
    //do struff
}

How do you get a string from a MemoryStream?

This sample shows how to read and write a string to a MemoryStream.


Imports System.IO

Module Module1
  Sub Main()
    ' We don't need to dispose any of the MemoryStream 
    ' because it is a managed object. However, just for 
    ' good practice, we'll close the MemoryStream.
    Using ms As New MemoryStream
      Dim sw As New StreamWriter(ms)
      sw.WriteLine("Hello World")
      ' The string is currently stored in the 
      ' StreamWriters buffer. Flushing the stream will 
      ' force the string into the MemoryStream.
      sw.Flush()
      ' If we dispose the StreamWriter now, it will close 
      ' the BaseStream (which is our MemoryStream) which 
      ' will prevent us from reading from our MemoryStream
      'sw.Dispose()

      ' The StreamReader will read from the current 
      ' position of the MemoryStream which is currently 
      ' set at the end of the string we just wrote to it. 
      ' We need to set the position to 0 in order to read 
      ' from the beginning.
      ms.Position = 0
      Dim sr As New StreamReader(ms)
      Dim myStr = sr.ReadToEnd()
      Console.WriteLine(myStr)

      ' We can dispose our StreamWriter and StreamReader 
      ' now, though this isn't necessary (they don't hold 
      ' any resources open on their own).
      sw.Dispose()
      sr.Dispose()
    End Using

    Console.WriteLine("Press any key to continue.")
    Console.ReadKey()
  End Sub
End Module

MySQL SELECT only not null values

You can filter out rows that contain a NULL value in a specific column:

SELECT col1, col2, ..., coln
FROM yourtable
WHERE somecolumn IS NOT NULL

If you want to filter out rows that contain a null in any column then try this:

SELECT col1, col2, ..., coln
FROM yourtable
WHERE col1 IS NOT NULL
AND col2 IS NOT NULL
-- ...
AND coln IS NOT NULL

Update: Based on your comments, perhaps you want this?

SELECT * FROM
(
    SELECT col1 AS col FROM yourtable
    UNION
    SELECT col2 AS col FROM yourtable
    UNION
    -- ...
    UNION
    SELECT coln AS col FROM yourtable
) T1
WHERE col IS NOT NULL

And I agre with Martin that if you need to do this then you should probably change your database design.

React-Native: Application has not been registered error

Please check your app.json file in project. if there has not line appKey then you must add it

{
  "expo": {
    "sdkVersion": "27.0.0",
    "appKey": "mydojo"
  },
  "name": "mydojo",
  "displayName": "mydojo"
}

Pointer-to-pointer dynamic two-dimensional array

What you describe for the second method only gives you a 1D array:

int *board = new int[10];

This just allocates an array with 10 elements. Perhaps you meant something like this:

int **board = new int*[4];
for (int i = 0; i < 4; i++) {
  board[i] = new int[10];
}

In this case, we allocate 4 int*s and then make each of those point to a dynamically allocated array of 10 ints.

So now we're comparing that with int* board[4];. The major difference is that when you use an array like this, the number of "rows" must be known at compile-time. That's because arrays must have compile-time fixed sizes. You may also have a problem if you want to perhaps return this array of int*s, as the array will be destroyed at the end of its scope.

The method where both the rows and columns are dynamically allocated does require more complicated measures to avoid memory leaks. You must deallocate the memory like so:

for (int i = 0; i < 4; i++) {
  delete[] board[i];
}
delete[] board;

I must recommend using a standard container instead. You might like to use a std::array<int, std::array<int, 10> 4> or perhaps a std::vector<std::vector<int>> which you initialise to the appropriate size.

convert iso date to milliseconds in javascript

Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.

var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);

See the fiddle for more details.

How to implement private method in ES6 class with Traceur

I hope this can be helpful. :)

I. Declaring vars, functions inside IIFE(Immediately-invoked function expression), those can be used only in the anonymous function. (It can be good to use "let, const" keywords without using 'var' when you need to change code for ES6.)

let Name = (function() {
  const _privateHello = function() {
  }
  class Name {
    constructor() {
    }
    publicMethod() {
      _privateHello()
    }
  }
  return Name;
})();

II. WeakMap object can be good for memoryleak trouble.

Stored variables in the WeakMap will be removed when the instance will be removed. Check this article. (Managing the private data of ES6 classes)

let Name = (function() {
  const _privateName = new WeakMap();
})();

III. Let's put all together.

let Name = (function() {
  const _privateName = new WeakMap();
  const _privateHello = function(fullName) {
    console.log("Hello, " + fullName);
  }

  class Name {
    constructor(firstName, lastName) {
      _privateName.set(this, {firstName: firstName, lastName: lastName});
    }
    static printName(name) {
      let privateName = _privateName.get(name);
      let _fullname = privateName.firstName + " " + privateName.lastName;
      _privateHello(_fullname);
    }
    printName() {
      let privateName = _privateName.get(this);
      let _fullname = privateName.firstName + " " + privateName.lastName;
      _privateHello(_fullname);
    }
  }

  return Name;
})();

var aMan = new Name("JH", "Son");
aMan.printName(); // "Hello, JH Son"
Name.printName(aMan); // "Hello, JH Son"

How to know which is running in Jupyter notebook?

import sys
print(sys.executable)
print(sys.version)
print(sys.version_info)

Seen below :- output when i run JupyterNotebook outside a CONDA venv

/home/dhankar/anaconda2/bin/python
2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jul  2 2016, 17:42:40) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)
 

Seen below when i run same JupyterNoteBook within a CONDA Venv created with command --

conda create -n py35 python=3.5 ## Here - py35 , is name of my VENV

in my Jupyter Notebook it prints :-

/home/dhankar/anaconda2/envs/py35/bin/python
3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:53:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)

also if you already have various VENV's created with different versions of Python you switch to the desired Kernel by choosing KERNEL >> CHANGE KERNEL from within the JupyterNotebook menu... JupyterNotebookScreencapture

Also to install ipykernel within an existing CONDA Virtual Environment -

http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernels-for-different-environments

Source --- https://github.com/jupyter/notebook/issues/1524

 $ /path/to/python -m  ipykernel install --help
 usage: ipython-kernel-install [-h] [--user] [--name NAME]
                          [--display-name DISPLAY_NAME]
                          [--profile PROFILE] [--prefix PREFIX]
                          [--sys-prefix]

Install the IPython kernel spec.

optional arguments: -h, --help show this help message and exit --user Install for the current user instead of system-wide --name NAME Specify a name for the kernelspec. This is needed to have multiple IPython kernels at the same time. --display-name DISPLAY_NAME Specify the display name for the kernelspec. This is helpful when you have multiple IPython kernels. --profile PROFILE Specify an IPython profile to load. This can be used to create custom versions of the kernel. --prefix PREFIX Specify an install prefix for the kernelspec. This is needed to install into a non-default location, such as a conda/virtual-env. --sys-prefix Install to Python's sys.prefix. Shorthand for --prefix='/Users/bussonniermatthias/anaconda'. For use in conda/virtual-envs.

DateTime "null" value

Just be warned - When using a Nullable its obviously no longer a 'pure' datetime object, as such you cannot access the DateTime members directly. I'll try and explain.

By using Nullable<> you're basically wrapping DateTime in a container (thank you generics) of which is nullable - obviously its purpose. This container has its own properties which you can call that will provide access to the aforementioned DateTime object; after using the correct property - in this case Nullable.Value - you then have access to the standard DateTime members, properties etc.

So - now the issue comes to mind as to the best way to access the DateTime object. There are a few ways, number 1 is by FAR the best and 2 is "dude why".

  1. Using the Nullable.Value property,

    DateTime date = myNullableObject.Value.ToUniversalTime(); //Works

    DateTime date = myNullableObject.ToUniversalTime(); //Not a datetime object, fails

  2. Converting the nullable object to datetime using Convert.ToDateTime(),

    DateTime date = Convert.ToDateTime(myNullableObject).ToUniversalTime(); //works but why...

Although the answer is well documented at this point, I believe the usage of Nullable was probably worth posting about. Sorry if you disagree.

edit: Removed a third option as it was a bit overly specific and case dependent.

ASP.Net MVC: Calling a method from a view

You can implement a static formatting method or an HTML helper, then use this syntaxe :

@using class_of_method_namespace
...
// HTML page here
@className.MethodName()

or in case of HTML Helper

@Html.MehtodName()

How do I analyze a .hprof file?

You can also use HeapWalker from the Netbeans Profiler or the Visual VM stand-alone tool. Visual VM is a good alternative to JHAT as it is stand alone, but is much easier to use than JHAT.

You need Java 6+ to fully use Visual VM.

How do I code my submit button go to an email address

You might use Form tag with action attribute to submit the mailto.

Here is an example:

<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" /> 
</form>

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.

EXEC sp_addrolemember 'db_ddladmin', 'username_here';

did the trick

How to convert CSV to JSON in Node.js

I have a very simple solution to just print json from csv on console using csvtojson module.

// require csvtojson
var csv = require("csvtojson");

const csvFilePath='customer-data.csv' //file path of csv
csv()
.fromFile(csvFilePath)``
.then((jsonObj)=>{
    console.log(jsonObj);
})