Programs & Examples On #Pickle

Pickle is an object serialization module for Python. Use this tag together with the Python tag for questions related to storing or loading objects with Pickle.

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

Pickle uses different protocols to convert your data to a binary stream.

You must specify in python 3 a protocol lower than 3 in order to be able to load the data in python 2. You can specify the protocol parameter when invoking pickle.dump.

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

for root, dirs, files in os.walk(directory):
    for file in files:
        floc = file
        im = Image.open(str(directory) + '\\' + floc)
        pix = np.array(im.getdata())
        pixels.append(pix)
        labels.append(1)   # append(i)???

So far ok. But you want to leave pixels as a list until you are done with the iteration.

pixels = np.array(pixels)
labels = np.array(labels)

You had this indention right in your other question. What happened? previous

Iterating, collecting values in a list, and then at the end joining things into a bigger array is the right way. To make things clear I often prefer to use notation like:

alist = []
for ..
    alist.append(...)
arr = np.array(alist)

If names indicate something about the nature of the object I'm less likely to get errors like yours.

I don't understand what you are trying to do with traindata. I doubt if you need to build it during the loop. pixels and labels have the basic information.

That

traindata = np.array([traindata[i][i],traindata[1]], dtype=object)

comes from the previous question. I'm not sure you understand that answer.

traindata = []
traindata.append(pixels)
traindata.append(labels)

if done outside the loop is just

traindata = [pixels, labels]

labels is a 1d array, a bunch of 1s (or [0,1,2,3...] if my guess is right). pixels is a higher dimension array. What is its shape?

Stop right there. There's no point in turning that list into an array. You can save the list with pickle.

You are copying code from an earlier question, and getting the formatting wrong. cPickle very large amount of data

How to save a list to a file and read it as a list type?

I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing. Therefore, I did this:

score = [1,2,3,4,5]

with open("file.txt", "w") as f:
    for s in score:
        f.write(str(s) +"\n")
score = []
with open("file.txt", "r") as f:
  for line in f:
    score.append(int(line.strip()))

So the items in the file are read as integers, despite being stored to the file as strings.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I had a similar error but with different context when I uploaded a *.p file to Google Drive. I tried to use it later in a Google Colab session, and got this error:

    1 with open("/tmp/train.p", mode='rb') as training_data:
----> 2     train = pickle.load(training_data)
UnpicklingError: invalid load key, '<'.

I solved it by compressing the file, upload it and then unzip on the session. It looks like the pickle file is not saved correctly when you upload/download it so it gets corrupted.

Saving an Object (Data persistence)

You can use anycache to do the job for you. It considers all the details:

  • It uses dill as backend, which extends the python pickle module to handle lambda and all the nice python features.
  • It stores different objects to different files and reloads them properly.
  • Limits cache size
  • Allows cache clearing
  • Allows sharing of objects between multiple runs
  • Allows respect of input files which influence the result

Assuming you have a function myfunc which creates the instance:

from anycache import anycache

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

@anycache(cachedir='/path/to/your/cache')    
def myfunc(name, value)
    return Company(name, value)

Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the function name and its arguments) as filename. On any consecutive run, the pickled object is loaded. If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

For any further details see the documentation

Python multiprocessing PicklingError: Can't pickle <type 'function'>

This solution requires only the installation of dill and no other libraries as pathos

def apply_packed_function_for_map((dumped_function, item, args, kwargs),):
    """
    Unpack dumped function as target function and call it with arguments.

    :param (dumped_function, item, args, kwargs):
        a tuple of dumped function and its arguments
    :return:
        result of target function
    """
    target_function = dill.loads(dumped_function)
    res = target_function(item, *args, **kwargs)
    return res


def pack_function_for_map(target_function, items, *args, **kwargs):
    """
    Pack function and arguments to object that can be sent from one
    multiprocessing.Process to another. The main problem is:
        «multiprocessing.Pool.map*» or «apply*»
        cannot use class methods or closures.
    It solves this problem with «dill».
    It works with target function as argument, dumps it («with dill»)
    and returns dumped function with arguments of target function.
    For more performance we dump only target function itself
    and don't dump its arguments.
    How to use (pseudo-code):

        ~>>> import multiprocessing
        ~>>> images = [...]
        ~>>> pool = multiprocessing.Pool(100500)
        ~>>> features = pool.map(
        ~...     *pack_function_for_map(
        ~...         super(Extractor, self).extract_features,
        ~...         images,
        ~...         type='png'
        ~...         **options,
        ~...     )
        ~... )
        ~>>>

    :param target_function:
        function, that you want to execute like  target_function(item, *args, **kwargs).
    :param items:
        list of items for map
    :param args:
        positional arguments for target_function(item, *args, **kwargs)
    :param kwargs:
        named arguments for target_function(item, *args, **kwargs)
    :return: tuple(function_wrapper, dumped_items)
        It returs a tuple with
            * function wrapper, that unpack and call target function;
            * list of packed target function and its' arguments.
    """
    dumped_function = dill.dumps(target_function)
    dumped_items = [(dumped_function, item, args, kwargs) for item in items]
    return apply_packed_function_for_map, dumped_items

It also works for numpy arrays.

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Most of the answers here have dealt with how to mange EOFError exceptions, which is really handy if you're unsure about whether the pickled object is empty or not.

However, if you're surprised that the pickle file is empty, it could be because you opened the filename through 'wb' or some other mode that could have over-written the file.

for example:

filename = 'cd.pkl'
with open(filename, 'wb') as f:
    classification_dict = pickle.load(f)

This will over-write the pickled file. You might have done this by mistake before using:

...
open(filename, 'rb') as f:

And then got the EOFError because the previous block of code over-wrote the cd.pkl file.

When working in Jupyter, or in the console (Spyder) I usually write a wrapper over the reading/writing code, and call the wrapper subsequently. This avoids common read-write mistakes, and saves a bit of time if you're going to be reading the same file multiple times through your travails

Using pickle.dump - TypeError: must be str, not bytes

Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

Not able to pip install pickle in python 3.6

import pickle

intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()

Test your pickle quickly. pickle is a part of standard python library and available by default.

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

Why not to use separate func?

def func(*args, **kwargs):
    return inst.method(args, kwargs)

print pool.map(func, arr)

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

Multiprocessing: How to use Pool.map on a function defined in a class?

I'm not sure if this approach has been taken but a work around i'm using is:

from multiprocessing import Pool

t = None

def run(n):
    return t.f(n)

class Test(object):
    def __init__(self, number):
        self.number = number

    def f(self, x):
        print x * self.number

    def pool(self):
        pool = Pool(2)
        pool.map(run, range(10))

if __name__ == '__main__':
    t = Test(9)
    t.pool()
    pool = Pool(2)
    pool.map(run, range(10))

Output should be:

0
9
18
27
36
45
54
63
72
81
0
9
18
27
36
45
54
63
72
81

How to read pickle file?

The following is an example of how you might write and read a pickle file. Note that if you keep appending pickle data to the file, you will need to continue reading from the file until you find what you want or an exception is generated by reaching the end of the file. That is what the last function does.

import os
import pickle


PICKLE_FILE = 'pickle.dat'


def main():
    # append data to the pickle file
    add_to_pickle(PICKLE_FILE, 123)
    add_to_pickle(PICKLE_FILE, 'Hello')
    add_to_pickle(PICKLE_FILE, None)
    add_to_pickle(PICKLE_FILE, b'World')
    add_to_pickle(PICKLE_FILE, 456.789)
    # load & show all stored objects
    for item in read_from_pickle(PICKLE_FILE):
        print(repr(item))
    os.remove(PICKLE_FILE)


def add_to_pickle(path, item):
    with open(path, 'ab') as file:
        pickle.dump(item, file, pickle.HIGHEST_PROTOCOL)


def read_from_pickle(path):
    with open(path, 'rb') as file:
        try:
            while True:
                yield pickle.load(file)
        except EOFError:
            pass


if __name__ == '__main__':
    main()

Storing Python dictionaries

Pickle save:

try:
    import cPickle as pickle
except ImportError:  # Python 3.x
    import pickle

with open('data.p', 'wb') as fp:
    pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)

See the pickle module documentation for additional information regarding the protocol argument.

Pickle load:

with open('data.p', 'rb') as fp:
    data = pickle.load(fp)

JSON save:

import json

with open('data.json', 'w') as fp:
    json.dump(data, fp)

Supply extra arguments, like sort_keys or indent, to get a pretty result. The argument sort_keys will sort the keys alphabetically and indent will indent your data structure with indent=N spaces.

json.dump(data, fp, sort_keys=True, indent=4)

JSON load:

with open('data.json', 'r') as fp:
    data = json.load(fp)

Saving and loading objects and using pickle

You can use anycache to do the job for you. Assuming you have a function myfunc which creates the instance:

from anycache import anycache

class Fruits:pass

@anycache(cachedir='/path/to/your/cache')    
def myfunc()
    banana = Fruits()
    banana.color = 'yellow'
    banana.value = 30
return banana

Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the the function name and the arguments) as filename. On any consecutive run, the pickled object is loaded.

If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

The function arguments are also taken into account. A refactored implementation works likewise:

from anycache import anycache

class Fruits:pass

@anycache(cachedir='/path/to/your/cache')    
def myfunc(color, value)
    fruit = Fruits()
    fruit.color = color
    fruit.value = value
return fruit

How can I use pickle to save a dict?

In general, pickling a dict will fail unless you have only simple objects in it, like strings and integers.

Python 2.7.9 (default, Dec 11 2014, 01:21:43) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy import *
>>> type(globals())     
<type 'dict'>
>>> import pickle
>>> pik = pickle.dumps(globals())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
    Pickler(file, protocol).dump(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 306, in save
    rv = reduce(self.proto)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle module objects
>>> 

Even a really simple dict will often fail. It just depends on the contents.

>>> d = {'x': lambda x:x}
>>> pik = pickle.dumps(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
    Pickler(file, protocol).dump(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 748, in save_global
    (obj, module, name))
pickle.PicklingError: Can't pickle <function <lambda> at 0x102178668>: it's not found as __main__.<lambda>

However, if you use a better serializer like dill or cloudpickle, then most dictionaries can be pickled:

>>> import dill
>>> pik = dill.dumps(d)

Or if you want to save your dict to a file...

>>> with open('save.pik', 'w') as f:
...   dill.dump(globals(), f)
... 

The latter example is identical to any of the other good answers posted here (which aside from neglecting the picklability of the contents of the dict are good).

best way to preserve numpy arrays on disk

I'm a big fan of hdf5 for storing large numpy arrays. There are two options for dealing with hdf5 in python:

http://www.pytables.org/

http://www.h5py.org/

Both are designed to work with numpy arrays efficiently.

What is the difference between rb and r+b modes in file objects

r opens for reading, whereas r+ opens for reading and writing. The b is for binary.

This is spelled out in the documentation:

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

Serializing class instance to JSON

Using jsonpickle

import jsonpickle

object = YourClass()
json_object = jsonpickle.encode(object)

How to unpack pkl file?

Generally

Your pkl file is, in fact, a serialized pickle file, which means it has been dumped using Python's pickle module.

To un-pickle the data you can:

import pickle


with open('serialized.pkl', 'rb') as f:
    data = pickle.load(f)

For the MNIST data set

Note gzip is only needed if the file is compressed:

import gzip
import pickle


with gzip.open('mnist.pkl.gz', 'rb') as f:
    train_set, valid_set, test_set = pickle.load(f)

Where each set can be further divided (i.e. for the training set):

train_x, train_y = train_set

Those would be the inputs (digits) and outputs (labels) of your sets.

If you want to display the digits:

import matplotlib.cm as cm
import matplotlib.pyplot as plt


plt.imshow(train_x[0].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()

mnist_digit

The other alternative would be to look at the original data:

http://yann.lecun.com/exdb/mnist/

But that will be harder, as you'll need to create a program to read the binary data in those files. So I recommend you to use Python, and load the data with pickle. As you've seen, it's very easy. ;-)

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

How to change options of <select> with jQuery?

For some odd reason this part

$el.empty(); // remove old options

from CMS solution didn't work for me, so instead of that I've simply used this

el.html(' ');

And it's works. So my working code now looks like that:

var newOptions = {
    "Option 1":"option-1",
    "Option 2":"option-2"
};

var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
    $el.append($("<option></option>")
    .attr("value", value).text(key));
});

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I found a way around this after 3-4 hours of googling. I have added the following

<startup selegacyv2runtimeactivationpolicy="true">
  <supportedruntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup>

If this doesn't solve your problem then--> In the Project References Right Click on DLL where you getting error --> Select Properties--> Check the Run-time Version --> If it is v2.0.50727 then we know the problem. The Problem is :- you are having 2.0 Version of respective DLL. Solution is:- You can delete the respective DLL from the Project references and then download the latest version of DLL's from the corresponding website and add the reference of the latest version DLL reference then it will work.

How does PHP 'foreach' actually work?

As per the documentation provided by PHP manual.

On each iteration, the value of the current element is assigned to $v and the internal
array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

So as per your first example:

$array = ['foo'=>1];
foreach($array as $k=>&$v)
{
   $array['bar']=2;
   echo($v);
}

$array have only single element, so as per the foreach execution, 1 assign to $v and it don't have any other element to move pointer

But in your second example:

$array = ['foo'=>1, 'bar'=>2];
foreach($array as $k=>&$v)
{
   $array['baz']=3;
   echo($v);
}

$array have two element, so now $array evaluate the zero indices and move the pointer by one. For first iteration of loop, added $array['baz']=3; as pass by reference.

How do I do a multi-line string in node.js?

What exactly are you looking for when you mean multiline strings.

Are you looking for something like:

var str = "Some \
    String \
    Here";

Which would print as "Some String Here"?

If so, keep in mind that the above is valid Javascript, but this isn't:

var str = "Some \ 
    String \
    Here";

What's the difference? A space after the \. Have fun debugging that.

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

How to press/click the button using Selenium if the button does not have the Id?

In Selenium IDE you can do:

Command   |   clickAndWait
Target    |   //input[@value='Next' and @title='next']

It should work fine.

Access host database from a docker container

From the 18.03 docs:

I want to connect from a container to a service on the host

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.

The gateway is also reachable as gateway.docker.internal.

EXAMPLE: Here's what I use for my MySQL connection string inside my container to access the MySQL instance on my host:

mysql://host.docker.internal:3306/my_awesome_database

Fastest way to convert an iterator to a list

@Robino was suggesting to add some tests which make sense, so here is a simple benchmark between 3 possible ways (maybe the most used ones) to convert an iterator to a list:

  1. by type constructor

list(my_iterator)

  1. by unpacking

[*my_iterator]

  1. using list comprehension

[e for e in my_iterator]

I have been using simple_bechmark library

from simple_benchmark import BenchmarkBuilder
from heapq import nsmallest

b = BenchmarkBuilder()

@b.add_function()
def convert_by_type_constructor(size):
    list(iter(range(size)))

@b.add_function()
def convert_by_list_comprehension(size):
    [e for e in iter(range(size))]

@b.add_function()
def convert_by_unpacking(size):
    [*iter(range(size))]


@b.add_arguments('Convert an iterator to a list')
def argument_provider():
    for exp in range(2, 22):
        size = 2**exp
        yield size, size

r = b.run()
r.plot()

enter image description here

As you can see there is very hard to make a difference between conversion by the constructor and conversion by unpacking, conversion by list comprehension is the “slowest” approach.


I have been testing also across different Python versions (3.6, 3.7, 3.8, 3.9) by using the following simple script:

import argparse
import timeit

parser = argparse.ArgumentParser(
    description='Test convert iterator to list')
parser.add_argument(
    '--size', help='The number of elements from iterator')

args = parser.parse_args()

size = int(args.size)
repeat_number = 10000

# do not wait too much if the size is too big
if size > 10000:
    repeat_number = 100


def test_convert_by_type_constructor():
    list(iter(range(size)))


def test_convert_by_list_comprehension():
    [e for e in iter(range(size))]


def test_convert_by_unpacking():
    [*iter(range(size))]


def get_avg_time_in_ms(func):
    avg_time = timeit.timeit(func, number=repeat_number) * 1000 / repeat_number
    return round(avg_time, 6)


funcs = [test_convert_by_type_constructor,
         test_convert_by_unpacking, test_convert_by_list_comprehension]

print(*map(get_avg_time_in_ms, funcs))

The script will be executed via a subprocess from a Jupyter Notebook (or a script), the size parameter will be passed through command-line arguments and the script results will be taken from standard output.

from subprocess import PIPE, run

import pandas

simple_data = {'constructor': [], 'unpacking': [], 'comprehension': [],
        'size': [], 'python version': []}


size_test = 100, 1000, 10_000, 100_000, 1_000_000
for version in ['3.6', '3.7', '3.8', '3.9']:
    print('test for python', version)
    for size in size_test:
        command = [f'python{version}', 'perf_test_convert_iterator.py', f'--size={size}']
        result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
        constructor, unpacking,  comprehension = result.stdout.split()
        
        simple_data['constructor'].append(float(constructor))
        simple_data['unpacking'].append(float(unpacking))
        simple_data['comprehension'].append(float(comprehension))
        simple_data['python version'].append(version)
        simple_data['size'].append(size)

df_ = pandas.DataFrame(simple_data)
df_

enter image description here

You can get my full notebook from here.

In most of the cases, in my tests, unpacking shows to be faster, but the difference is so small that the results may change from a run to the other. Again, the comprehension approach is the slowest, in fact, the other 2 methods are up to ~ 60% faster.

Find the greatest number in a list of numbers

    #Ask for number input
first = int(raw_input('Please type a number: '))
second = int(raw_input('Please type a number: '))
third = int(raw_input('Please type a number: '))
fourth = int(raw_input('Please type a number: '))
fifth = int(raw_input('Please type a number: '))
sixth = int(raw_input('Please type a number: '))
seventh = int(raw_input('Please type a number: '))
eighth = int(raw_input('Please type a number: '))
ninth = int(raw_input('Please type a number: '))
tenth = int(raw_input('Please type a number: '))

    #create a list for variables
sorted_list = [first, second, third, fourth, fifth, sixth, seventh, 
              eighth, ninth, tenth]
odd_numbers = []

    #filter list and add odd numbers to new list
for value in sorted_list:
    if value%2 != 0:
        odd_numbers.append(value)
print 'The greatest odd number you typed was:', max(odd_numbers)

How to make an Android device vibrate? with different frequency?

I use the following utils method:

public static final void vibratePhone(Context context, short vibrateMilliSeconds) {
    Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(vibrateMilliSeconds);
}

Add the following permission to the AndroidManifest file

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

You can use overloaded methods in case if you wish to use different types of vibrations (patterns / indefinite) as suggested above.

PDO Prepared Inserts multiple rows in single query

Although an old question all the contributions helped me a lot so here's my solution, which works within my own DbContext class. The $rows parameter is simply an array of associative arrays representing rows or models: field name => insert value.

If you use a pattern that uses models this fits in nicely when passed model data as an array, say from a ToRowArray method within the model class.

Note: It should go without saying but never allow the arguments passed to this method to be exposed to the user or reliant on any user input, other than the insert values, which have been validated and sanitised. The $tableName argument and the column names should be defined by the calling logic; for instance a User model could be mapped to the user table, which has its column list mapped to the model's member fields.

public function InsertRange($tableName, $rows)
{
    // Get column list
    $columnList = array_keys($rows[0]);
    $numColumns = count($columnList);
    $columnListString = implode(",", $columnList);

    // Generate pdo param placeholders
    $placeHolders = array();

    foreach($rows as $row)
    {
        $temp = array();

        for($i = 0; $i < count($row); $i++)
            $temp[] = "?";

        $placeHolders[] = "(" . implode(",", $temp) . ")";
    }

    $placeHolders = implode(",", $placeHolders);

    // Construct the query
    $sql = "insert into $tableName ($columnListString) values $placeHolders";
    $stmt = $this->pdo->prepare($sql);

    $j = 1;
    foreach($rows as $row)
    {
        for($i = 0; $i < $numColumns; $i++)
        {
            $stmt->bindParam($j, $row[$columnList[$i]]);
            $j++;
        }
    }

    $stmt->execute();
}

How can I time a code segment for testing performance with Pythons timeit?

Here is an example of how to time a function using timeit:

import timeit

def time_this(n):
    return [str(i) for i in range(n)]

timeit.timeit(lambda: time_this(n=5000), number=1000)

This will return the time in seconds it took to execute the time_this() function 1000 times.

How to send list of file in a folder to a txt file in Linux

you can just use

ls > filenames.txt

(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd to go to that folder first, or you can ls ~/docs > filenames.txt

Call a python function from jinja2

To import all the builtin functions you can use:

app.jinja_env.globals.update(__builtins__)

Add .__dict__ after __builtins__ if this doesn't work.

Based on John32323's answer.

How often should Oracle database statistics be run?

At my last job we ran statistics once a week. If I remember correctly, we scheduled them on a Thursday night, and on Friday the DBAs were very careful to monitor the longest running queries for anything unexpected. (Friday was picked because it was often just after a code release, and tended to be a fairly low traffic day.) When they saw a bad query they would find a better query plan and save that one so it wouldn't change again unexpectedly. (Oracle has tools to do this for you automatically, you tell it the query to optimize and it does.)

Many organizations avoid running statistics out of fear of bad query plans popping up unexpectedly. But this usually means that their query plans get worse and worse over time. And when they do run statistics then they encounter a number of problems. The resulting scramble to fix those issues confirms their fears about the dangers of running statistics. But if they ran statistics regularly, used the monitoring tools as they are supposed to, and fixed issues as they came up then they would have fewer headaches, and they wouldn't encounter them all at once.

how to count the spaces in a java string?

If you use Java 8, the following should work:

long count = "0 1 2 3 4.".chars().filter(Character::isWhitespace).count();

This will also work in Java 8 using Eclipse Collections:

int count = Strings.asChars("0 1 2 3 4.").count(Character::isWhitespace);

Note: I am a committer for Eclipse Collections.

How to add a char/int to an char array in C?

I think you've forgotten initialize your string "str": You need initialize the string before using strcat. And also you need that tmp were a string, not a single char. Try change this:

char str[1024]; // Only declares size
char tmp = '.';

for

char str[1024] = "Hello World";  //Now you have "Hello World" in str
char tmp[2] = ".";

How do I configure modprobe to find my module?

I think the key is to copy the module to the standard paths.

Once that is done, modprobe only accepts the module name, so leave off the path and ".ko" extension.

Unable to resolve host "<URL here>" No address associated with host name

Sometimes, although you add <uses-permission android:name="android.permission.INTERNET" /> in the AndroidManifest and you have a WiFi connection, this exception can be thrown. In my case, I have turned off WiFi and then turned it on again. This resolved the error. Weird solution, but sometimes it works.

How to debug Apache mod_rewrite

For basic URL resolution, use a command line fetcher like wget or curl to do the testing, rather than a manual browser. Then you don't have to clear any cache; just up arrow and Enter in a shell to re-run your test fetches.

How to delete an object by id with entity framework

If you dont want to query for it just create an entity, and then delete it.

Customer customer  = new Customer() {  Id = 1   } ; 
context.AttachTo("Customers", customer);
context.DeleteObject(customer);
context.Savechanges();

How can I put an icon inside a TextInput in React Native?

You can use combination of View, Icon and TextInput like so:

<View style={styles.searchSection}>
    <Icon style={styles.searchIcon} name="ios-search" size={20} color="#000"/>
    <TextInput
        style={styles.input}
        placeholder="User Nickname"
        onChangeText={(searchString) => {this.setState({searchString})}}
        underlineColorAndroid="transparent"
    />
</View>

and use flex-direction for styling

searchSection: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
},
searchIcon: {
    padding: 10,
},
input: {
    flex: 1,
    paddingTop: 10,
    paddingRight: 10,
    paddingBottom: 10,
    paddingLeft: 0,
    backgroundColor: '#fff',
    color: '#424242',
},

Icons were taken from "react-native-vector-icons"

Changing image size in Markdown

For IntelliJ IDEA users, please refer to Markdown Navigator plugin.

Preview renders images, badges, HTML, etc.

Android Studio Markdown Preview

Force add despite the .gitignore file

See man git-add:

   -f, --force
       Allow adding otherwise ignored files.

So run this

git add --force my/ignore/file.foo

How to make the 'cut' command treat same sequental delimiters as one?

Try:

tr -s ' ' <text.txt | cut -d ' ' -f4

From the tr man page:

-s, --squeeze-repeats   replace each input sequence of a repeated character
                        that is listed in SET1 with a single occurrence
                        of that character

Split string on the first white space occurrence

Whenever I need to get a class from a list of classes or a part of a class name or id, I always use split() then either get it specifically with the array index or, most often in my case, pop() to get the last element or shift() to get the first.

This example gets the div's classes "gallery_148 ui-sortable" and returns the gallery id 148.

var galleryClass = $(this).parent().prop("class"); // = gallery_148 ui-sortable
var galleryID = galleryClass.split(" ").shift(); // = gallery_148
galleryID = galleryID.split("_").pop(); // = 148
//or
galleryID = galleryID.substring(8); // = 148 also, but less versatile 

I'm sure it could be compacted into less lines but I left it expanded for readability.

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

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

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

Change 8080 to whichever you want

Why is there no Char.Empty like String.Empty?

There's no such thing as an empty character. It always contains something. Even '\0' is a character.

Comparing two files in linux terminal

Here is my solution for this :

mkdir temp
mkdir results
cp /usr/share/dict/american-english ~/temp/american-english-dictionary
cp /usr/share/dict/british-english ~/temp/british-english-dictionary
cat ~/temp/american-english-dictionary | wc -l > ~/results/count-american-english-dictionary
cat ~/temp/british-english-dictionary | wc -l > ~/results/count-british-english-dictionary
grep -Fxf ~/temp/american-english-dictionary ~/temp/british-english-dictionary > ~/results/common-english
grep -Fxvf ~/results/common-english ~/temp/american-english-dictionary > ~/results/unique-american-english
grep -Fxvf ~/results/common-english ~/temp/british-english-dictionary > ~/results/unique-british-english

Why can't static methods be abstract in Java?

Because "abstract" means: "Implements no functionality", and "static" means: "There is functionality even if you don't have an object instance". And that's a logical contradiction.

What is the difference between a candidate key and a primary key?

First you have to know what is a determinant? the determinant is an attribute that used to determine another attribute in the same table. SO the determinant must be a candidate key. And you can have more than one determinant. But primary key is used to determine the whole record and you can have only one primary key. Both primary and candidate key can consist of one or more attributes

HttpClient 4.0.1 - how to release connection?

If you want to re-use the connection then you must consume content stream completely after every use as follows :

EntityUtils.consume(response.getEntity())

Note : you need to consume the content stream even if the status code is not 200. Not doing so will raise the following on next use :

Exception in thread "main" java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated. Make sure to release the connection before allocating another one.

If it's a one time use, then simply closing the connection will release all the resources associated with it.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

When i faced this error( while making AJAX call from javascript ); the reason was the response from controller was erroneous; it was returning a JSON which was not of valid format.

WooCommerce return product object by id

Alright, I deserve to be throttled. definitely an RTM but not for WooCommerce, for Wordpress. Solution found due to a JOLT cola (all hail JOLT cola).

TASK: Field named 'related_product_ids' added to a custom post type. So when that post is displayed mini product displays can be displayed with it.

PROBLEM: Was having a problem getting the multiple ids returned via WP_Query.

SOLUTION:

$related_id_list          = get_post_custom_values('related_product_ids');
    // Get comma delimited list from current post
$related_product_ids      = explode(",", trim($related_id_list[0],','));
    // Return an array of the IDs ensure no empty array elements from extra commas
$related_product_post_ids = array( 'post_type' => 'product', 
                                   'post__in'  => $related_product_ids,
                                   'meta_query'=> array( 
                                        array( 'key'    => '_visibility',
                                               'value'  => array('catalog', 'visible'),'compare' => 'IN'
                                        )
                            ) 
);      
    // Query to get all product posts matching given IDs provided it is a published post
$loop = new WP_Query( $related_posts );
    // Execute query
while ( $loop->have_posts() ) : $loop->the_post(); $_product = get_product( $loop->post->ID );
    // Do stuff here to display your products 
endwhile;

Thank you for anyone who may have spent some time on this.

Tim

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

I sorted this problem as verifying the json from JSONLint.com and then, correcting it. And this is code for the same.

String jsonStr = "[{\r\n" + "\"name\":\"New York\",\r\n" + "\"number\": \"732921\",\r\n"+ "\"center\": {\r\n" + "\"latitude\": 38.895111,\r\n"  + " \"longitude\": -77.036667\r\n" + "}\r\n" + "},\r\n" + " {\r\n"+ "\"name\": \"San Francisco\",\r\n" +\"number\":\"298732\",\r\n"+ "\"center\": {\r\n" + "    \"latitude\": 37.783333,\r\n"+ "\"longitude\": -122.416667\r\n" + "}\r\n" + "}\r\n" + "]";

ObjectMapper mapper = new ObjectMapper();
MyPojo[] jsonObj = mapper.readValue(jsonStr, MyPojo[].class);

for (MyPojo itr : jsonObj) {
    System.out.println("Val of name is: " + itr.getName());
    System.out.println("Val of number is: " + itr.getNumber());
    System.out.println("Val of latitude is: " + 
        itr.getCenter().getLatitude());
    System.out.println("Val of longitude is: " + 
        itr.getCenter().getLongitude() + "\n");
}

Note: MyPojo[].class is the class having getter and setter of json properties.

Result:

Val of name is: New York
Val of number is: 732921
Val of latitude is: 38.895111
Val of longitude is: -77.036667
Val of name is: San Francisco
Val of number is: 298732
Val of latitude is: 37.783333
Val of longitude is: -122.416667

How to keep the local file or the remote file during merge using Git and the command line?

This approach seems more straightforward, avoiding the need to individually select each file:

# keep remote files
git merge --strategy-option theirs
# keep local files
git merge --strategy-option ours

or

# keep remote files
git pull -Xtheirs
# keep local files
git pull -Xours

Copied directly from: Resolve Git merge conflicts in favor of their changes during a pull

What does 'low in coupling and high in cohesion' mean

In software design high cohesion means that class should do one thing and one thing very well. High cohesion is closely related to Single responsibility principle.

Low coupling suggest that class should have least possible dependencies. Also, dependencies that must exist should be weak dependencies - prefer dependency on interface rather than dependency on concrete class, or prefer composition over inheritance .

High Cohesion and low coupling give us better designed code that is easier to maintain.

Where does mysql store data?

In version 5.6 at least, the Management tab in MySQL Workbench shows that it's in a hidden folder called ProgramData in the C:\ drive. My default data directory is

C:\ProgramData\MySQL\MySQL Server 5.6\data

. Each database has a folder and each table has a file here.

ORA-01031: insufficient privileges when selecting view

If the view is accessed via a stored procedure, the execute grant is insufficient to access the view. You must grant select explicitly.

simply type this

grant all on to public;

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

This is for Visual Studio 2019, After trying a lot of suggestions that failed to work (including changing the port number etc) I solved my problem by deleting a file that was generated on my project's root folder called "debug". As soon as this file was deleted everything started working.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

Android: Tabs at the BOTTOM

For all those of you that try to remove the separating line of the tabWidget, here is an example project (and its respective tutorial), that work great for customizing the tabs and thus removing problems when tabs are at bottom. Eclipse Project: android-custom-tabs ; Original explanation: blog; Hope this helped.

how to open *.sdf files?

It's a SQL Compact database. You need to define what you mean by "Open". You can open it via code with the SqlCeConnection so you can write your own tool/app to access it.

Visual Studio can also open the files directly if was created with the right version of SQL Compact.

There are also some third-party tools for manipulating them.

Using jquery to delete all elements with a given id

if you want to remove all elements with matching ID parts, for example:

<span id='myID_123'>
<span id='myID_456'>
<span id='myID_789'>

try this:

$("span[id*=myID]").remove();

don't forget the '*' - this will remove them all at once - cheers

Working Demo

Call ASP.NET function from JavaScript?

Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):

It is a little tricky though... :)

i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like

public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}

ii. This should add (using Tab-Tab) this function to your code file:

public void RaisePostBackEvent(string eventArgument) { }

iii. In your onclick event in JavaScript, write the following code:

var pageId = '<%=  Page.ClientID %>';
__doPostBack(pageId, argumentString);

This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.

P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!

CSS performance relative to translateZ(0)

CSS transformations create a new stacking context and containing block, as described in the spec. In plain English, this means that fixed position elements with a transformation applied to them will act more like absolutely positioned elements, and z-index values are likely to get screwed with.

If you take a look at this demo, you'll see what I mean. The second div has a transformation applied to it, meaning that it creates a new stacking context, and the pseudo elements are stacked on top rather than below.

So basically, don't do that. Apply a 3D transformation only when you need the optimization. -webkit-font-smoothing: antialiased; is another way to tap into 3D acceleration without creating these problems, but it only works in Safari.

How to select a value in dropdown javascript?

This may do it

document.forms['someform'].elements['someelement'].value

Upload files from Java client to a HTTP server

You'd normally use java.net.URLConnection to fire HTTP requests. You'd also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in RFC2388.

Here's a kickoff example:

String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (
    OutputStream output = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
    // Send normal param.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
    writer.append(CRLF).append(param).append(CRLF).flush();

    // Send text file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
    writer.append(CRLF).flush();
    Files.copy(textFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // Send binary file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    Files.copy(binaryFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // End of multipart/form-data.
    writer.append("--" + boundary + "--").append(CRLF).flush();
}

// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200

This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.

The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can't use and don't need it at the client side.

See also

save a pandas.Series histogram plot to file

You can use ax.figure.savefig():

import pandas as pd

s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

There is some news based on Mozilla Foundation, and sitepoint

Do not use this value (http-equiv=content-type) as it is obsolete. Prefer the charset attribute on the <meta> element. enter image description here

How to set min-font-size in CSS

Judging by your above comment, you're OK doing this with jQuery — here goes:

// for every element in the body tag
$("*", "body").each(function() {
  // parse out its computed font size, and see if it is less than 12
  if ( parseInt($(this).css("font-size"), 10) < 12 )
    // if so, then manually give it a CSS property of 12px
    $(this).css("font-size", "12px")
});

A cleaner way to do this might be to have a "min-font" class in your CSS that sets font-size: 12px, and just add the class instead:

$("*", "body").each(function() {
  if ( parseInt($(this).css("font-size"), 10) < 12 )
    $(this).addClass("min-font")
});

In Angular, how to pass JSON object/array into directive?

If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.


First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.

I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.

app.factory('locations', function($http) {
  var promise = null;

  return function() {
    if (promise) {
      // If we've already asked for this data once,
      // return the promise that already exists.
      return promise;
    } else {
      promise = $http.get('locations/locations.json');
      return promise;
    }
  };
});

As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations service into the directive, but this couples the directive to that service.

A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.

- The 80/20 Guide to Writing AngularJS Directives

In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.

app.controller('SomeController', function($scope, locations) {
  locations().success(function(data) {
    $scope.locations = data;
  });
});
<ul class="list">
   <li ng-repeat="location in locations">
      <a href="#">{{location.id}}. {{location.name}}</a>
   </li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div></div>',
    scope: {
      // creates a scope variable in your directive
      // called `locations` bound to whatever was passed
      // in via the `locations` attribute in the DOM
      locations: '=locations'
    },
    link: function(scope, element, attrs) {
      scope.$watch('locations', function(locations) {
        angular.forEach(locations, function(location, key) {
          // do something
        });
      });
    }
  };
});

In this way, the map directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.

Why rgb and not cmy?

the 3 additive colors are in fact red, green, and blue. printers use cmyk (cyan, magenta, yellow, and black).

and as http://en.wikipedia.org/wiki/Additive_color explains: if you use RYB as your primary colors, how do you make green? since yellow is made from equal amounts of red and green.

iOS 7 UIBarButton back button arrow color

In case you're making custom back button basing on UIButton with image of arrow, here is the subclass snippet. Using it you can either create button in code or just assign class in Interface Builder to any UIButton. Back Arrow Image will be added automatically and colored with text color.

@interface UIImage (TintColor)

- (UIImage *)imageWithOverlayColor:(UIColor *)color;

@end


@implementation UIImage (TintColor)

- (UIImage *)imageWithOverlayColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, self.size.width, self.size.height);

    if (UIGraphicsBeginImageContextWithOptions) {
        CGFloat imageScale = 1.0f;
        if ([self respondsToSelector:@selector(scale)])
            imageScale = self.scale;
        UIGraphicsBeginImageContextWithOptions(self.size, NO, imageScale);
    }
    else {
        UIGraphicsBeginImageContext(self.size);
    }

    [self drawInRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetBlendMode(context, kCGBlendModeSourceIn);

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

@end




#import "iOS7backButton.h"

@implementation iOS7BackButton

-(void)awakeFromNib
{
    [super awakeFromNib];

    BOOL is6=([[[UIDevice currentDevice] systemVersion] floatValue] <7);
    UIImage *backBtnImage = [[UIImage imageNamed:@"backArrow"] imageWithOverlayColor:self.titleLabel.textColor];
    [self setImage:backBtnImage forState:UIControlStateNormal];
    [self setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
    [self setImageEdgeInsets:UIEdgeInsetsMake(0, is6?0:-10, 0, 0)];


}


+ (UIButton*) buttonWithTitle:(NSString*)btnTitle andTintColor:(UIColor*)color {
    BOOL is6=([[[UIDevice currentDevice] systemVersion] floatValue] <7);
    UIButton *backBtn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    UIImage *backBtnImage = [[UIImage imageNamed:@"backArrow"] imageWithOverlayColor:color];
    [backBtn setImage:backBtnImage forState:UIControlStateNormal];
    [backBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, is6?5:-5, 0, 0)];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(0, is6?0:-10, 0, 0)];
    [backBtn setTitle:btnTitle forState:UIControlStateNormal];
    [backBtn setTitleColor:color /*#007aff*/ forState:UIControlStateNormal];

    return backBtn;
}

@end

back button image@2x

How do I turn off PHP Notices?

You can check if the constant's already defined using:

<?php
if (!defined('MYCONST'))
    define('MYCONST', 'Weeha!');
?>

Format SQL in SQL Server Management Studio

There is a special trick I discovered by accident.

  1. Select the query you wish to format.
  2. Ctrl+Shift+Q (This will open your query in the query designer)
  3. Then just go OK Voila! Query designer will format your query for you. Caveat is that you can only do this for statements and not procedural code, but its better than nothing.

How do I call a non-static method from a static method in C#?

Perhaps what you are looking for is the Singleton pattern?

public class Singleton
{
    private Singleton() {}

    public void DoWork()
    { 
        // do something
    }

    // You can call this static method which calls the singleton instance method.
    public static void DoSomeWork()
    { 
        Instance.DoWork();
    }

    public static Singleton Instance
    {
        get { return instance; } 
    }

    private static Singleton instance = new Singleton();
}

You still have to create an instance of the class but you ensure there is only one instance.

Why does Oracle not find oci.dll?

If you are using TOAD, you will need to download the 32-bit version of the Oracle Client Tools.

Since the Client Tools are different on a per-processor architecture basis, you probably need to install versions.

How to post a file from a form with Axios

Add the file to a formData object, and set the Content-Type header to multipart/form-data.

var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

concat scope variables into string in angular directive expression

I've created a working CodePen example demonstrating how to do this.

Relevant HTML:

<section ng-app="app" ng-controller="MainCtrl">
  <a href="#" ng-click="doSomething('#/path/{{obj.val1}}/{{obj.val2}}')">Click Me</a><br>
  debug: {{debug.val}}
</section>

Relevant javascript:

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

app.controller('MainCtrl', function($scope) {
  $scope.obj = {
    val1: 'hello',
    val2: 'world'
  };

  $scope.debug = {
    val: ''
  };

  $scope.doSomething = function(input) {
    $scope.debug.val = input;
  };
});

html cellpadding the left side of a cell

I use inline css all the time BECAUSE.... I want absolute control of the design and place different things aligned differently from cell to cell.

It is not hard to understand...

Anyway, I just put something like this inside my tag:

style='padding:5px 10px 5px 5px'

Where the order represents top, right, bottom and left.

Understanding The Modulus Operator %

Modulus operator gives you the result in 'reduced residue system'. For example for mod 5 there are 5 integers counted: 0,1,2,3,4. In fact 19=12=5=-2=-9 (mod 7). The main difference that the answer is given by programming languages by 'reduced residue system'.

How can I initialize an ArrayList with all zeroes in Java?

// apparently this is broken. Whoops for me!
java.util.Collections.fill(list,new Integer(0));

// this is better
Integer[] data = new Integer[60];
Arrays.fill(data,new Integer(0));
List<Integer> list = Arrays.asList(data);

Where is the user's Subversion config file stored on the major operating systems?

Not sure about Win but n *nix (OS X, Linux, etc.) its in ~/.subversion

How to do a newline in output

Use "\n" instead of '\n'

Math.random() explanation

To generate a number between 10 to 20 inclusive, you can use java.util.Random

int myNumber = new Random().nextInt(11) + 10

ng: command not found while creating new project using angular-cli

In my case, I was simply running the wrong node version.

I had just previously installed a new node version to play around with Angular (2). At work we use 6.x so that is my default in nvm. After restarting the laptop ng stopped working simply because I was running node 6.x again. So for me it was simply a matter of using the version with which I was installing the Angular CLI:

nvm use node // with the node alias pointing to the right version

or

nvm use v8.11.3 // if you happen to know the version

Check your installed versions and aliases with

nvm list 

prevent refresh of page when button inside form clicked

Return function is not working in all the cases. I tried this:

<button id="Reset" class="Button-class" onclick="return Reset()">Show result</button>

It didnt work for me.

I tried to return false inside the function and it worked for me.

function Reset()
{
    .
    .
    .
    return false;
}

refresh leaflet map: map container is already initialized

the best way

map.off();
map.remove();

You should add map.off(), it also works faster, and does not cause problems with the events

How to split() a delimited string to a List<String>

string.Split() returns an array - you can convert it to a list using ToList():

listStrLineElements = line.Split(',').ToList();

Note that you need to import System.Linq to access the .ToList() function.

Importing CSV with line breaks in Excel 2007

Short Answer

Remove the newline/linefeed characters (\n with Notepad++). Excel will still recognise the carriage return character (\r) to separate records.

Long Answer

As mentioned newline characters are supported inside CSV fields but Excel doesn't always handle them gracefully. I faced a similar issue with a third party CSV that possibly had encoding issues but didn't improve with encoding changes.

What worked for me was removing all newline characters (\n). This has the effect of collapsing fields to a single record assuming that your records are separated by the combination of a carriage return and a newline (CR/LF). Excel will then properly import the file and recognise new records by the carriage return.

Obviously a cleaner solution is to first replace the real newlines (\r\n) with a temporary character combination, replacing the newlines (\n) with your seperating character of choice (e.g. comma in a semicolon file) and then replacing the temporary characters with proper newlines again.

C# - How to get Program Files (x86) on Windows 64 bit

Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)

How to change working directory in Jupyter Notebook?

I have did it on windows machine. Detail mentioned below 1. From windows start menu open “Anaconda Prompt enter image description here 2. Find .jupyter folder file path . In command prompt just type enter image description here or enter image description here to find the .jupyter path

  1. After find the .jupyter folder, check there has “jupyter_notebook_config” file or not. If it is not there then run below command enter image description here After run the command it will create "jupyter_notebook_config.py"

if do not have administrator permission then Some time you could not find .jupyter folder . Still you can open config file from any of the text editor

  1. Open “jupyter_notebook_config.py” file from the the “.jypyter” folder.
  2. After open the file need to update the directory is use for notebooks and kernel. There are so many line in config file so find “#c.NotebookApp.notebook_dir” and update the path enter image description here After: enter image description here Save the file
  3. Now try to create or read some file from the location you set

HTML5 Audio stop function

Instead of stop() you could try with:

sound.pause();
sound.currentTime = 0;

This should have the desired effect.

Python Sets vs Lists

It depends on what you are intending to do with it.

Sets are significantly faster when it comes to determining if an object is present in the set (as in x in s), but are slower than lists when it comes to iterating over their contents.

You can use the timeit module to see which is faster for your situation.

Auto-increment on partial primary key with Entity Framework Core

First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:

make sure you have correclty set the keys

modelBuilder.Entity<Foo>()
            .HasKey(p => new { p.Name, p.Id });
modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

OR you can achieve it using data annotation as well

public class Foo
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key, Column(Order = 0)]
    public int Id { get; set; }

    [Key, Column(Order = 1)]
    public string Name{ get; set; }
}

Why and how to fix? IIS Express "The specified port is in use"

Open Task Manager and Just Close all processes of 'IIS Express System Tray' and 'IIS Express Worker Process' and Re-run the Project

Task Manager Process Details

Trying to embed newline in a variable in bash

sed solution:

echo "a b c" | sed 's/ \+/\n/g'

Result:

a
b
c

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

At the moment you're calling ToUniversalTime() - just get rid of that:

private long ConvertToTimestamp(DateTime value)
{
    long epoch = (value.Ticks - 621355968000000000) / 10000000;
    return epoch;
}

Alternatively, and rather more readably IMO:

private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
...

private static long ConvertToTimestamp(DateTime value)
{
    TimeSpan elapsedTime = value - Epoch;
    return (long) elapsedTime.TotalSeconds;
}

EDIT: As noted in the comments, the Kind of the DateTime you pass in isn't taken into account when you perform subtraction. You should really pass in a value with a Kind of Utc for this to work. Unfortunately, DateTime is a bit broken in this respect - see my blog post (a rant about DateTime) for more details.

You might want to use my Noda Time date/time API instead which makes everything rather clearer, IMO.

How can I make git show a list of the files that are being tracked?

The accepted answer only shows files in the current directory's tree. To show all of the tracked files that have been committed (on the current branch), use

git ls-tree --full-tree --name-only -r HEAD
  • --full-tree makes the command run as if you were in the repo's root directory.
  • -r recurses into subdirectories. Combined with --full-tree, this gives you all committed, tracked files.
  • --name-only removes SHA / permission info for when you just want the file paths.
  • HEAD specifies which branch you want the list of tracked, committed files for. You could change this to master or any other branch name, but HEAD is the commit you have checked out right now.

This is the method from the accepted answer to the ~duplicate question https://stackoverflow.com/a/8533413/4880003.

How to sort a list of lists by a specific index of the inner list?

Itemgetter lets you to sort by multiple criteria / columns:

sorted_list = sorted(list_to_sort, key=itemgetter(2,0,1))

How to remove elements/nodes from angular.js array

Here is filter with Underscore library might help you, we remove item with name "ted"

$scope.items = _.filter($scope.items, function(item) {
    return !(item.name == 'ted');
 });

How to know if two arrays have the same values

Sort the arrays and compare their values one by one.

function arrayCompare(_arr1, _arr2) {
    if (
      !Array.isArray(_arr1)
      || !Array.isArray(_arr2)
      || _arr1.length !== _arr2.length
      ) {
        return false;
      }
    
    // .concat() to not mutate arguments
    const arr1 = _arr1.concat().sort();
    const arr2 = _arr2.concat().sort();
    
    for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] !== arr2[i]) {
            return false;
         }
    }
    
    return true;
}

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

IE works with iframe like all the other browsers (at least for main functions). You just have to keep a set of rules:

  • before you load any javascript in the iframe (that part of js which needs to know about the iframe parent), ensure that the parent has document.domain changed.
  • when all iframe resources are loaded, change document.domain to be the same as the one defined in parent. (You need to do this later because setting domain will cause the iframe resource's request to fail)

  • now you can make a reference for parent window: var winn = window.parent

  • now you can make a reference to parent HTML, in order to manipulate it: var parentContent = $('html', winn.document)
  • at this point you should have access to IE parent window/document and you can change it as you wont

Cleanest way to build an SQL string in Java

I have been working on a Java servlet application that needs to construct very dynamic SQL statements for adhoc reporting purposes. The basic function of the app is to feed a bunch of named HTTP request parameters into a pre-coded query, and generate a nicely formatted table of output. I used Spring MVC and the dependency injection framework to store all of my SQL queries in XML files and load them into the reporting application, along with the table formatting information. Eventually, the reporting requirements became more complicated than the capabilities of the existing parameter mapping frameworks and I had to write my own. It was an interesting exercise in development and produced a framework for parameter mapping much more robust than anything else I could find.

The new parameter mappings looked as such:

select app.name as "App", 
       ${optional(" app.owner as "Owner", "):showOwner}
       sv.name as "Server", sum(act.trans_ct) as "Trans"
  from activity_records act, servers sv, applications app
 where act.server_id = sv.id
   and act.app_id = app.id
   and sv.id = ${integer(0,50):serverId}
   and app.id in ${integerList(50):appId}
 group by app.name, ${optional(" app.owner, "):showOwner} sv.name
 order by app.name, sv.name

The beauty of the resulting framework was that it could process HTTP request parameters directly into the query with proper type checking and limit checking. No extra mappings required for input validation. In the example query above, the parameter named serverId would be checked to make sure it could cast to an integer and was in the range of 0-50. The parameter appId would be processed as an array of integers, with a length limit of 50. If the field showOwner is present and set to "true", the bits of SQL in the quotes will be added to the generated query for the optional field mappings. field Several more parameter type mappings are available including optional segments of SQL with further parameter mappings. It allows for as complex of a query mapping as the developer can come up with. It even has controls in the report configuration to determine whether a given query will have the final mappings via a PreparedStatement or simply ran as a pre-built query.

For the sample Http request values:

showOwner: true
serverId: 20
appId: 1,2,3,5,7,11,13

It would produce the following SQL:

select app.name as "App", 
       app.owner as "Owner", 
       sv.name as "Server", sum(act.trans_ct) as "Trans"
  from activity_records act, servers sv, applications app
 where act.server_id = sv.id
   and act.app_id = app.id
   and sv.id = 20
   and app.id in (1,2,3,5,7,11,13)
 group by app.name,  app.owner,  sv.name
 order by app.name, sv.name

I really think that Spring or Hibernate or one of those frameworks should offer a more robust mapping mechanism that verifies types, allows for complex data types like arrays and other such features. I wrote my engine for only my purposes, it isn't quite read for general release. It only works with Oracle queries at the moment and all of the code belongs to a big corporation. Someday I may take my ideas and build a new open source framework, but I'm hoping one of the existing big players will take up the challenge.

Color text in terminal applications in UNIX

Use ANSI escape sequences. This article goes into some detail about them. You can use them with printf as well.

GUI-based or Web-based JSON editor that works like property explorer

Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.

Based on JSON Schema

Commercial (No endorsement intended or implied, may or may not meet requirement)

jQuery

YAML

See Also

Express.js - app.listen vs server.listen

I came with same question but after google, I found there is no big difference :)

From Github

If you wish to create both an HTTP and HTTPS server you may do so with the "http" and "https" modules as shown here.

/**
 * Listen for connections.
 *
 * A node `http.Server` is returned, with this
 * application (which is a `Function`) as its
 * callback. If you wish to create both an HTTP
 * and HTTPS server you may do so with the "http"
 * and "https" modules as shown here:
 *
 *    var http = require('http')
 *      , https = require('https')
 *      , express = require('express')
 *      , app = express();
 *
 *    http.createServer(app).listen(80);
 *    https.createServer({ ... }, app).listen(443);
 *
 * @return {http.Server}
 * @api public
 */

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Also if you want to work with socket.io see their example

See this

I prefer app.listen() :)

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

Move the session_start(); to top of the page always.

<?php
@ob_start();
session_start();
?>

Why are arrays of references illegal?

When you store something in an array , its size needs to be known (since array indexing relies on the size). Per the C++ standard It is unspecified whether or not a reference requires storage, as a result indexing an array of references would not be possible.

Angular cli generate a service and include the provider in one step

In Angular 5.12 and latest Angular CLI, do

ng generate service my-service -m app.module

SQL Server 2005 Setting a variable to the result of a select query

-- Sql Server 2005 Management studio


use Master
go
DECLARE @MyVar bigint
SET @myvar = (SELECT count(*) FROM spt_values);
SELECT @myvar

Result: 2346 (in my db)

-- Note: @myvar = @Myvar

How do I disable "missing docstring" warnings at a file-level in Pylint?

Edit file "C:\Users\Your User\AppData\Roaming\Code\User\settings.json" and add these python.linting.pylintArgs lines at the end as shown below:

{
    "team.showWelcomeMessage": false,
    "python.dataScience.sendSelectionToInteractiveWindow": true,
    "git.enableSmartCommit": true,
    "powershell.codeFormatting.useCorrectCasing": true,
    "files.autoSave": "onWindowChange",
    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django",
        "--errors-only"
    ],
}

replacing text in a file with Python

Faster way of writing it would be...

in = open('path/to/input/file').read()
out = open('path/to/input/file', 'w')
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
for i in replacements.keys():
    in = in.replace(i, replacements[i])
out.write(in)
out.close

This eliminated a lot of the iterations that the other answers suggest, and will speed up the process for longer files.

How to detect duplicate values in PHP array?

$count = 0;
$output ='';
$ischeckedvalueArray = array();
for ($i=0; $i < sizeof($array); $i++) {
    $eachArrayValue = $array[$i];
    if(! in_array($eachArrayValue, $ischeckedvalueArray)) {
        for( $j=$i; $j < sizeof($array); $j++) {
            if ($array[$j] === $eachArrayValue) {
                $count++;
            }
        }
        $ischeckedvalueArray[] = $eachArrayValue;
        $output .= $eachArrayValue. " Repated ". $count."<br/>";
        $count = 0;
    }

}

echo $output;

What is a simple C or C++ TCP server and client example?

I've used Beej's Guide to Network Programming in the past. It's in C, not C++, but the examples are good. Go directly to section 6 for the simple client and server example programs.

gradlew command not found?

For Ubuntu(linux) users: doing "bash ./gradlew build " works but "./gradlew build " doesnot work.

For me the issue was it was on NTFS file system, linux does not let execute a script from NTFS. Try moving the code from NTFS to a linux partition. then ./gradlew build should work

TimeSpan to DateTime conversion

A problem with all of the above is that the conversion returns the incorrect number of days as specified in the TimeSpan.
Using the above, the below returns 3 and not 2.

Ideas on how to preserve the 2 days in the TimeSpan arguments and return them as the DateTime day?

public void should_return_totaldays()
{
    _ts = new TimeSpan(2, 1, 30, 10);
    var format = "dd";
    var returnedVal = _ts.ToString(format);
    Assert.That(returnedVal, Is.EqualTo("2")); //returns 3 not 2
}

Setting up an MS-Access DB for multi-user access

I have found the SMB2 protocol introduced in Vista to lock the access databases. It can be disabled by the following regedit:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\LanmanServer\Parameters] "Smb2"=dword:00000000

How to Completely Uninstall Xcode and Clear All Settings

For complete removal old Xcode 7 you should remove

  1. /Applications/Xcode.app
  2. /Library/Preferences/com.apple.dt.Xcode.plist
  3. ~/Library/Preferences/com.apple.dt.Xcode.plist
  4. ~/Library/Caches/com.apple.dt.Xcode
  5. ~/Library/Application Support/Xcode
  6. ~/Library/Developer/Xcode
  7. ~/Library/Developer/CoreSimulator

Getting value of select (dropdown) before change

_x000D_
_x000D_
var last_value;
var current_value;
$(document).on("click","select",function(){
    last_value = $(this).val();
}).on("change","select",function(){
    current_value = $(this).val();

    console.log('last value - '+last_value);
    console.log('current value - '+current_value);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="test">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>
_x000D_
_x000D_
_x000D_

Format number to always show 2 decimal places

var quantity = 12;

var import1 = 12.55;

var total = quantity * import1;

var answer = parseFloat(total).toFixed(2);

document.write(answer);

Add php variable inside echo statement as href link address?

as simple as that: echo '<a href="'.$link_address.'">Link</a>';

Size-limited queue that holds last N elements in Java

    public class ArrayLimitedQueue<E> extends ArrayDeque<E> {

    private int limit;

    public ArrayLimitedQueue(int limit) {
        super(limit + 1);
        this.limit = limit;
    }

    @Override
    public boolean add(E o) {
        boolean added = super.add(o);
        while (added && size() > limit) {
            super.remove();
        }
        return added;
    }

    @Override
    public void addLast(E e) {
        super.addLast(e);
        while (size() > limit) {
            super.removeLast();
        }
    }

    @Override
    public boolean offerLast(E e) {
        boolean added = super.offerLast(e);
        while (added && size() > limit) {
            super.pollLast();
        }
        return added;
    }
}

What is the purpose of a question mark after a type (for example: int? myVariable)?

int? is shorthand for Nullable<int>. The two forms are interchangeable.

Nullable<T> is an operator that you can use with a value type T to make it accept null.

In case you don't know it: value types are types that accepts values as int, bool, char etc...

They can't accept references to values: they would generate a compile-time error if you assign them a null, as opposed to reference types, which can obviously accept it.

Why would you need that? Because sometimes your value type variables could receive null references returned by something that didn't work very well, like a missing or undefined variable returned from a database.

I suggest you to read the Microsoft Documentation because it covers the subject quite well.

Easy way to write contents of a Java InputStream to an OutputStream

Using Guava's ByteStreams.copy():

ByteStreams.copy(inputStream, outputStream);

How can I display a pdf document into a Webview?

Download source code from here (Open pdf in webview android)

activity_main.xml

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

    <WebView
        android:layout_width="match_parent"
        android:background="#ffffff"
        android:layout_height="match_parent"
        android:id="@+id/webview"></WebView>
</RelativeLayout>

MainActivity.java

package com.pdfwebview;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    WebView webview;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    init();
    listener();
    }

    private void init() {

        webview = (WebView) findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true);

        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setTitle("PDF");
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        webview.loadUrl("https://drive.google.com/file/d/0B534aayZ5j7Yc3RhcnRlcl9maWxl/view");

    }

    private void listener() {
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pDialog.show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pDialog.dismiss();
            }
        });
    }
}

How to preview selected image in input type="file" in popup using jQuery?

If your are using HTML5 then try following code snippet

<img id="uploadPreview" style="width: 100px; height: 100px;" />
<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />
<script type="text/javascript">

    function PreviewImage() {
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

        oFReader.onload = function (oFREvent) {
            document.getElementById("uploadPreview").src = oFREvent.target.result;
        };
    };

</script>

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

Here is a general answer for untab :-

In Python IDLE :- Ctrl + [

In elipse :- Shitft + Tab

In Visual Studio :- Shift+ Tab

Stash only one file out of multiple files that have changed with Git?

Use git stash push, like this:

git stash push [--] [<pathspec>...]

For example:

git stash push -- my/file.sh

This is available since Git 2.13, released in spring 2017.

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

Freemarker iterating over hashmap keys

For completeness, it's worth mentioning there's a decent handling of empty collections in Freemarker since recently.

So the most convenient way to iterate a map is:

<#list tags>
<ul class="posts">
    <#items as tagName, tagCount>
        <li>{$tagName} (${tagCount})</li>
    </#items>
</ul>
<#else>
    <p>No tags found.</p>
</#list>

No more <#if ...> wrappers.

How to get the current date and time

import org.joda.time.DateTime;

DateTime now = DateTime.now();

Linux bash: Multiple variable assignment

Sometimes you have to do something funky. Let's say you want to read from a command (the date example by SDGuero for example) but you want to avoid multiple forks.

read month day year << DATE_COMMAND
 $(date "+%m %d %Y")
DATE_COMMAND
echo $month $day $year

You could also pipe into the read command, but then you'd have to use the variables within a subshell:

day=n/a; month=n/a; year=n/a
date "+%d %m %Y" | { read day month year ; echo $day $month $year; }
echo $day $month $year

results in...

13 08 2013
n/a n/a n/a

What does MissingManifestResourceException mean and how to fix it?

I just came across this problem today, and I found this Microsoft Help and Support page that actually did work around the problem.

I had a couple delegates at the top of my file, in the global namespace, and all of a sudden I was getting a MissingManifestResourceException when running the program, on this line:

this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));

Then I moved the delegates into the namespace, got the same error. Finally I put the delegates in the only class in that file, and the error went away, but I didn't want the delegates in that class or namespace.

Then I came across that link above, which said

To resolve this problem, move all of the other class definitions so that they appear after the form's class definition.

I put the delegates (which I would not consider "class definitions") at the bottom of that file, outside of the local namespace, and the program didn't get the MissingManifestResourceException anymore. What an irritating error. But, that seems like a more robust solution than modifying the auto-generated code :)

How to change MySQL column definition?

This should do it:

ALTER TABLE test MODIFY locationExpert VARCHAR(120) 

How do I read / convert an InputStream into a String in Java?

If you were feeling adventurous, you could mix Scala and Java and end up with this:

scala.io.Source.fromInputStream(is).mkString("")

Mixing Java and Scala code and libraries has it's benefits.

See full description here: Idiomatic way to convert an InputStream to a String in Scala

jQuery UI autocomplete with item and id

I've tried above code displaying (value or ID) in text-box insted of Label text. After that I've tried event.preventDefault() it's working perfectly...

var e = [{"label":"PHP","value":"1"},{"label":"Java","value":"2"}]

$(".jquery-autocomplete").autocomplete({
    source: e,select: function( event, ui ) {
        event.preventDefault();
        $('.jquery-autocomplete').val(ui.item.label);
        console.log(ui.item.label);
        console.log(ui.item.value);
    }
});

Bootstrap Columns Not Working

Your Nesting DIV structure was missing, you must add another ".row" div when creating nested divs in bootstrap :

Here is the Code:

<div class="container">
   <div class="row">
            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-4"> <a href="">About</a>
    
                    </div>
                    <div class="col-md-4">
                        <img src="https://www.google.ca/images/srpr/logo11w.png" width="100px" />
                    </div>
                    <div class="col-md-4"> <a href="#myModal1" data-toggle="modal">SHARE</a>
    
                    </div>
                </div>
            </div>
        </div>
    </div>

Refer the Bootstrap example description for the same:

http://getbootstrap.com/css/

Nesting columns

To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or less (it is not required that you use all 12 available columns).


Here is the working Fiddle of your code: http://jsfiddle.net/52j6avkb/1/embedded/result/

In Spring MVC, how can I set the mime type header when using @ResponseBody

You may not be able to do it with @ResponseBody, but something like this should work:

package xxx;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class FooBar {
  @RequestMapping(value="foo/bar", method = RequestMethod.GET)
  public void fooBar(HttpServletResponse response) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(myService.getJson().getBytes());
    response.setContentType("application/json");
    response.setContentLength(out.size());
    response.getOutputStream().write(out.toByteArray());
    response.getOutputStream().flush();
  }
}

How to automatically crop and center an image

Try this: Set your image crop dimensions and use this line in your CSS:

object-fit: cover;

JQuery .each() backwards

I prefer creating a reverse plug-in eg

jQuery.fn.reverse = function(fn) {       
   var i = this.length;

   while(i--) {
       fn.call(this[i], i, this[i])
   }
};

Usage eg:

$('#product-panel > div').reverse(function(i, e) {
    alert(i);
    alert(e);
});

Removing elements with Array.map in JavaScript

Array Filter method

_x000D_
_x000D_
var arr = [1, 2, 3]_x000D_
_x000D_
// ES5 syntax_x000D_
arr = arr.filter(function(item){ return item != 3 })_x000D_
_x000D_
// ES2015 syntax_x000D_
arr = arr.filter(item => item != 3)_x000D_
_x000D_
console.log( arr )
_x000D_
_x000D_
_x000D_

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

It is a problem with Java InputStream. When the stream is read once the file offset position counter is moved to the end of file. On the subsequent read by using the same stream you'll get this error. So you have to close and reopen the stream again or call inputStream.reset() to reset the offset counter to its initial position.

What is the difference between %g and %f in C?

They are both examples of floating point input/output.

%g and %G are simplifiers of the scientific notation floats %e and %E.

%g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two.

The output of your print statement will depend on the value of sum.

How can I retrieve a table from stored procedure to a datatable?

Explaining if any one want to send some parameters while calling stored procedure as below,

using (SqlConnection con = new SqlConnection(connetionString))
            {
                using (var command = new SqlCommand(storedProcName, con))
                {
                    foreach (var item in sqlParams)
                    {
                        item.Direction = ParameterDirection.Input;
                        item.DbType = DbType.String;
                        command.Parameters.Add(item);
                    }
                    command.CommandType = CommandType.StoredProcedure;
                    using (var adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dt);
                    }
                }
            }

How to get the client IP address in PHP

One of these :

    $ip = $_SERVER['REMOTE_ADDR'];
    $ip = $_SERVER['HTTP_CLIENT_IP'];
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    $ip = $_SERVER['HTTP_X_FORWARDED'];
    $ip = $_SERVER['HTTP_FORWARDED_FOR'];
    $ip = $_SERVER['HTTP_FORWARDED'];

How can I return the current action in an ASP.NET MVC view?

I saw different answers and came up with a class helper:

using System;
using System.Web.Mvc;

namespace MyMvcApp.Helpers {
    public class LocationHelper {
        public static bool IsCurrentControllerAndAction(string controllerName, string actionName, ViewContext viewContext) {
            bool result = false;
            string normalizedControllerName = controllerName.EndsWith("Controller") ? controllerName : String.Format("{0}Controller", controllerName);

            if(viewContext == null) return false;
            if(String.IsNullOrEmpty(actionName)) return false;

            if (viewContext.Controller.GetType().Name.Equals(normalizedControllerName, StringComparison.InvariantCultureIgnoreCase) &&
                viewContext.Controller.ValueProvider.GetValue("action").AttemptedValue.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) {
                result = true;
            }

            return result;
        }
    }
}

So in View (or master/layout) you can use it like so (Razor syntax):

            <div id="menucontainer">

                <ul id="menu">
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home", "index", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("account","logon", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Logon", "Logon", "Account")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home","about", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("About", "About", "Home")</li>
                </ul>

            </div>

Hope it helps.

integrating barcode scanner into php application?

If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.

C++ auto keyword. Why is it magic?

It's not going anywhere ... it's a new standard C++ feature in the implementation of C++11. That being said, while it's a wonderful tool for simplifying object declarations as well as cleaning up the syntax for certain call-paradigms (i.e., range-based for-loops), don't over-use/abuse it :-)

Simple file write function in C++

This is a place in which C++ has a strange rule. Before being able to compile a call to a function the compiler must know the function name, return value and all parameters. This can be done by adding a "prototype". In your case this simply means adding before main the following line:

int writeFile();

this tells the compiler that there exist a function named writeFile that will be defined somewhere, that returns an int and that accepts no parameters.

Alternatively you can define first the function writeFile and then main because in this case when the compiler gets to main already knows your function.

Note that this requirement of knowing in advance the functions being called is not always applied. For example for class members defined inline it's not required...

struct Foo {
    void bar() {
        if (baz() != 99) {
            std::cout << "Hey!";
        }
    }

    int baz() {
        return 42;
    }
};

In this case the compiler has no problem analyzing the definition of bar even if it depends on a function baz that is declared later in the source code.

correct way to define class variables in Python

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

How to square or raise to a power (elementwise) a 2D numpy array?

>>> import numpy
>>> print numpy.power.__doc__

power(x1, x2[, out])

First array elements raised to powers from second array, element-wise.

Raise each base in `x1` to the positionally-corresponding power in
`x2`.  `x1` and `x2` must be broadcastable to the same shape.

Parameters
----------
x1 : array_like
    The bases.
x2 : array_like
    The exponents.

Returns
-------
y : ndarray
    The bases in `x1` raised to the exponents in `x2`.

Examples
--------
Cube each element in a list.

>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([  0,   1,   8,  27,  64, 125])

Raise the bases to different exponents.

>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([  0.,   1.,   8.,  27.,  16.,   5.])

The effect of broadcasting.

>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
       [1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0,  1,  8, 27, 16,  5],
       [ 0,  1,  8, 27, 16,  5]])
>>>

Precision

As per the discussed observation on numerical precision as per @GarethRees objection in comments:

>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027,  1.0,  1.0],
       [ 1.0,  1.0,  1.0],
       [ 1.0,  1.0,  1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484,  1.0,  1.0],
       [ 1.0,  1.0,  1.0],
       [ 1.0,  1.0,  1.0]], dtype=float96)

>>> a.dtype
dtype('float96')
>>> a[0,0]
0.46002700024131926
>>> b[0,0]
0.21162484095102677

>>> print b[0,0]
0.211624840951
>>> print a[0,0]
0.460027000241

Performance

>>> c    = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )

>>> import zmq
>>> aClk = zmq.Stopwatch()

>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L)                #   5 663 [usec]

>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L)                #   6 395 [usec]

>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L)                #   6 930 [usec]

>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L)                #   6 285 [usec]

>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L)             # 384 515 [usec]

JavaScript chop/slice/trim off last character in string

Here is an alternative that i don't think i've seen in the other answers, just for fun.

_x000D_
_x000D_
var strArr = "hello i'm a string".split("");_x000D_
strArr.pop();_x000D_
document.write(strArr.join(""));
_x000D_
_x000D_
_x000D_

Not as legible or simple as slice or substring but does allow you to play with the string using some nice array methods, so worth knowing.

Is there a vr (vertical rule) in html?

<div style="width:1px;background-color:red;height:30px;float:right;"></div>

Easily can be done using a div like this

mysql datatype for telephone number and address

i would use a varchar for telephone numbers. that way you can also store + and (), which is sometimes seen in tel numbers (as you mentioned yourself). and you don't have to worry about using up all bits in integers.

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

How to add local .jar file dependency to build.gradle file?

The following works for me:

compile fileTree(dir: 'libs', include: '*.jar')

Refer to the Gradle Documentation.

How to use WebRequest to POST some data and read response?

Here's an example of posting to a web service using the HttpWebRequest and HttpWebResponse objects.

StringBuilder sb = new StringBuilder();
    string query = "?q=" + latitude + "%2C" + longitude + "&format=xml&key=xxxxxxxxxxxxxxxxxxxxxxxx";
    string weatherservice = "http://api.worldweatheronline.com/free/v1/marine.ashx" + query;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(weatherservice);
    request.Referer = "http://www.yourdomain.com";
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);
    Char[] readBuffer = new Char[256];
    int count = reader.Read(readBuffer, 0, 256);

    while (count > 0)
    {
        String output = new String(readBuffer, 0, count);
        sb.Append(output);
        count = reader.Read(readBuffer, 0, 256);
    }
    string xml = sb.ToString();

SQL Statement with multiple SETs and WHEREs

No, you need to handle every statement separately..

UPDATE table1
 Statement1;
 UPDATE table 1
 Statement2;

And so on

Jquery Chosen plugin - dynamically populate list by Ajax

var object = $("#lstValue_chosen").find('.chosen-choices').find('input[type="text"]')[0];
var _KeyCode = event.which || event.keyCode;
if (_KeyCode != 37 && _KeyCode != 38 && _KeyCode != 39 && _KeyCode != 40) { 

    if (object.value != "") {
        var SelectedObjvalue = object.value;
        if (SelectedObjvalue.length > 0) {
            var obj = { value: SelectedObjvalue };
            var SelectedListValue = $('#lstValue').val();
            var Uniqueid = $('#uniqueid').val();

            $.ajax({
                url: '/Admin/GetUserListBox?SelectedValue=' + SelectedListValue + '&Uniqueid=' + Uniqueid,
                data: { value: SelectedObjvalue },
                type: 'GET',
                async: false,
                success: function (response) {
                    if (response.length > 0) {
                        $('#lstValue').html('');
                        var options = '';                            
                        $.each(response, function (i, obj) {
                            options += '<option value="' + obj.Value + '">' + obj.Text + '</option>';
                        });
                        $('#lstValue').append(options);
                        $('#lstValue').val(SelectedListValue);
                        $('#lstValue').trigger("chosen:updated");
                        object.value = SelectedObjvalue;
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    //jAlert("Error. Please, check the data.", " Deactivate User");
                    alert(error.StatusText);
                }
            });
        }
    }
}

how to delete default values in text field using selenium?

This worked for me:

driver.findElement(yourElement).clear();
driver.findElement(yourelement).sendKeys("");

Browse and display files in a git repo without cloning

GitHub is svn compatible so you can use svn ls

svn ls https://github.com/user/repository.git/branches/master/

BitBucket supports git archive so you can download tar archive and list archived files. It is not very efficient but works:

git archive [email protected]:repository HEAD directory | tar -t

Why a function checking if a string is empty always returns true?

You can simply cast to bool, dont forget to handle zero.

function isEmpty(string $string): bool {
    if($string === '0') {
        return false;
    }
    return !(bool)$string;
}

var_dump(isEmpty('')); // bool(true)
var_dump(isEmpty('foo')); // bool(false)
var_dump(isEmpty('0')); // bool(false)

How can I convert string to double in C++?

Must say I agree with that the most elegant solution to this is using boost::lexical_cast. You can then catch the bad_lexical_cast that might occure, and do something when it fails, instead of getting 0.0 which atof gives.

#include <boost/lexical_cast.hpp>
#include <string>

int main()
{
    std::string str = "3.14";
    double strVal;
    try {
        strVal = boost::lexical_cast<double>(str);
    } catch(bad_lexical_cast&) {
        //Do your errormagic
    }
    return 0;
}

How to check whether input value is integer or float?

Do this to distinguish that.

If for example your number is 3.1214 and stored in num but you don't know kind of num:

num = 3.1214
// cast num to int
int x = (int)num;
if(x == num)
{
  // num is a integer
} 
else
  // num is float
}

In this example we see that num is not integer.

Generator expressions vs. list comprehensions

When creating a generator from a mutable object (like a list) be aware that the generator will get evaluated on the state of the list at time of using the generator, not at time of the creation of the generator:

>>> mylist = ["a", "b", "c"]
>>> gen = (elem + "1" for elem in mylist)
>>> mylist.clear()
>>> for x in gen: print (x)
# nothing

If there is any chance of your list getting modified (or a mutable object inside that list) but you need the state at creation of the generator you need to use a list comprehension instead.

What does "for" attribute do in HTML <label> tag?

It labels whatever input is the parameter for the for attribute.

_x000D_
_x000D_
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
_x000D_
_x000D_

Address validation using Google Maps API

Google basis (free) does not provide address verification (Geocoding) as there is no UK postcode license.

This means postcode searches are very in-accurate. The proximity search is very poor, even for town searches, often not recognising locations.

This is why Google have a premier and a enterprise solution which still is more expensive and not as good as business mapping specialists like bIng and Via Michelin who also have API's.

As a free lance developer, so serious business would use Google as the system is weak and really provides a watered down solution.

IF a cell contains a string

You can use OR() to group expressions (as well as AND()):

=IF(OR(condition1, condition2), true, false)

=IF(AND(condition1, condition2), true, false)

So if you wanted to test for "cat" and "22":

=IF(AND(SEARCH("cat",a1),SEARCH("22",a1)),"cat and 22","none")

Is it possible to do a sparse checkout without checking out the whole repository first?

Steps to sparse checkout only specific folder:

1) git clone --no-checkout  <project clone url>  
2) cd <project folder>
3) git config core.sparsecheckout true   [You must do this]
4) echo "<path you want to sparce>/*" > .git/info/sparse-checkout
    [You must enter /* at the end of the path such that it will take all contents of that folder]
5) git checkout <branch name> [Ex: master]

How do I change screen orientation in the Android emulator?

You no longer need to remember the shortcuts. The latest Android AVD interface contains a sidebar with various functional shortcuts. I've circled in blue the buttons that rotate the screen clockwise and counter-clockwise.

enter image description here

jQuery click event on radio button doesn't get fired

put ur js code under the form html or use $(document).ready(function(){}) and try this.

$('#inline_content input[type="radio"]').click(function(){
                if($(this).val() == "walk_in"){
                    alert('ok');
                }
});

Open page in new window without popup blocking

As a general rule, pop up blockers target windows that launch without user interaction. Usually a click event can open a window without it being blocked. (unless it's a really bad popup blocker)

Try launching after a click event

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

I've had this happen on VS after I changed the file's line endings. Changing them back to Windows CR LF fixed the issue.

What column type/length should I use for storing a Bcrypt hashed password in a Database?

A Bcrypt hash can be stored in a BINARY(40) column.

BINARY(60), as the other answers suggest, is the easiest and most natural choice, but if you want to maximize storage efficiency, you can save 20 bytes by losslessly deconstructing the hash. I've documented this more thoroughly on GitHub: https://github.com/ademarre/binary-mcf

Bcrypt hashes follow a structure referred to as modular crypt format (MCF). Binary MCF (BMCF) decodes these textual hash representations to a more compact binary structure. In the case of Bcrypt, the resulting binary hash is 40 bytes.

Gumbo did a nice job of explaining the four components of a Bcrypt MCF hash:

$<id>$<cost>$<salt><digest>

Decoding to BMCF goes like this:

  1. $<id>$ can be represented in 3 bits.
  2. <cost>$, 04-31, can be represented in 5 bits. Put these together for 1 byte.
  3. The 22-character salt is a (non-standard) base-64 representation of 128 bits. Base-64 decoding yields 16 bytes.
  4. The 31-character hash digest can be base-64 decoded to 23 bytes.
  5. Put it all together for 40 bytes: 1 + 16 + 23

You can read more at the link above, or examine my PHP implementation, also on GitHub.

mysql Foreign key constraint is incorrectly formed error

thanks S Doerin:

"Just for completion. This error might be as well the case if you have a foreign key with VARCHAR(..) and the charset of the referenced table is different from the table referencing it. e.g. VARCHAR(50) in a Latin1 Table is different than the VARCHAR(50) in a UTF8 Table."

i solved this problem, changing the type of characters of the table. the creation have latin1 and the correct is utf8.

add the next line. DEFAULT CHARACTER SET = utf8;

Polling the keyboard (detect a keypress) in python


import sys
import select

def heardEnter():
    i,o,e = select.select([sys.stdin],[],[],0.0001)
    for s in i:
        if s == sys.stdin:
            input = sys.stdin.readline()
            return True
    return False

What is POCO in Entity Framework?

POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

  • Lazy loading
  • Change tracking

Here is a good start for this

POCO Entity framework

You can also generate POCOs so easily from your existing Entity framework project using Code generators.

EF 5.X DbContext code generator

Could not obtain information about Windows NT group user

Just solved this problem. In my case it was domain controller is not accessible, because both dns servers was google dns.

I just add to checklist for this problem:

  • check domain controller is accessible

What is the correct syntax of ng-include?

This worked for me:

ng-include src="'views/templates/drivingskills.html'"

complete div:

<div id="drivivgskills" ng-controller="DrivingSkillsCtrl" ng-view ng-include src="'views/templates/drivingskills.html'" ></div>

Unix's 'ls' sort by name

Check your .bashrc file for aliases.

gdb: "No symbol table is loaded"

I have the same problem and I followed this Post, it solved my problem.

Follow the following 2 steps:

  1. Make sure the optimization level is -O0
  2. Add -ggdb flag when compiling your program

Good luck!

How to make a .jar out from an Android Studio project

  • Open build.gradle for library project enter image description here

  • Write two tasks in build.gradle -- deleteJar and createJar and add rule createJar.dependsOn(deleteJar, build) enter image description here

The code from above:

task deleteJar(type: Delete) {
    delete 'libs/jars/logmanagementlib.jar'
}           

task createJar(type: Copy) {
    from('build/intermediates/bundles/release/')
    into('libs/jars/')
    include('classes.jar')
    rename('classes.jar', 'logmanagementlib.jar')
}

createJar.dependsOn(deleteJar, build)
  • Expand gradle panel from right and open all tasks under yourlibrary->others. You will see two new tasks there -- createJar and deleteJar enter image description here

  • Double click on createJar enter image description here

  • Once the task run successfully, get your generated jar from path mentioned in createJar task i.e. libs/xxxx.jar enter image description here

  • copy the newly generated jar into your required project's lib folder-->right click-->select "add as library"

Windows Batch Files: if else

if not %1 == "" (

must be

if not "%1" == "" (

If an argument isn't given, it's completely empty, not even "" (which represents an empty string in most programming languages). So we use the surrounding quotes to detect an empty argument.

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

CSS Grid Layout not working in IE11 even with prefixes

Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.

The repeat functionality is supported

You can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr), you have to write (1fr)[4]. That's it. See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/

Supporting grid-gap

Grid gaps are supported in all browsers except IE. So you can use the @supports at-rule to set the grid-gaps conditionally for all new browsers:

Example:

.grid {
  display: grid;
}
.item {
  margin-right: 1rem;
  margin-bottom: 1rem;
}
@supports (grid-gap: 1rem) {
  .grid {
    grid-gap: 1rem;
  }
  .item {
    margin-right: 0;
    margin-bottom: 0;
  }
}

It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.

Use Autoprefixer

I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.

Returning JSON from a PHP Script

According to the manual on json_encode the method can return a non-string (false):

Returns a JSON encoded string on success or FALSE on failure.

When this happens echo json_encode($data) will output the empty string, which is invalid JSON.

json_encode will for instance fail (and return false) if its argument contains a non UTF-8 string.

This error condition should be captured in PHP, for example like this:

<?php
header("Content-Type: application/json");

// Collect what you need in the $data variable.

$json = json_encode($data);
if ($json === false) {
    // Avoid echo of empty string (which is invalid JSON), and
    // JSONify the error message instead:
    $json = json_encode(["jsonError" => json_last_error_msg()]);
    if ($json === false) {
        // This should not happen, but we go all the way now:
        $json = '{"jsonError":"unknown"}';
    }
    // Set HTTP response status code to: 500 - Internal Server Error
    http_response_code(500);
}
echo $json;
?>

Then the receiving end should of course be aware that the presence of the jsonError property indicates an error condition, which it should treat accordingly.

In production mode it might be better to send only a generic error status to the client and log the more specific error messages for later investigation.

Read more about dealing with JSON errors in PHP's Documentation.

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

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

How do I write a bash script to restart a process if it dies?

I use this for my npm Process

#!/bin/bash
for (( ; ; ))
do
date +"%T"
echo Start Process
cd /toFolder
sudo process
date +"%T"
echo Crash
sleep 1
done

How to change app default theme to a different app theme?

If you are trying to reference an android style, you need to put "android:" in there

android:theme="@android:style/Theme.Black"

If that doesn't solve it, you may need to edit your question with the full manifest file, so we can see more details

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

There are changes in mongod.conf file in the latest MongoDB v 3.6.5 +

Here is how I fixed this issue on mac os High Sierra v 10.12.3

Note: I assume that you have installed/upgrade MongoDB using homebrew

mongo --version

MongoDB shell version v3.6.5 
git version: a20ecd3e3a174162052ff99913bc2ca9a839d618 
OpenSSL version: OpenSSL 1.0.2o  27 Mar 2018 
allocator: system modules: none build environment:
distarch: x86_64
target_arch: x86_64
  1. find mongod.conf file

     sudo find / -name mongod.conf` 
    

    /usr/local/etc/mongod.conf > first result .

  2. open mongod.conf file

    sudo vi /usr/local/etc/mongod.conf
    
  3. edit in the file for remote access under net: section

     port: 27017  
     bindIpAll: true 
     #bindIp: 127.0.0.1 // comment this out
    
  4. restart mongodb

    if you have installed using brew than

    brew services stop mongodb
    
    brew services start mongodb
    

otherwise, kill the process.

   sudo kill -9 <procssID>

Javascript-Setting background image of a DIV via a function and function parameter

If you are looking for a direct approach and using a local File in that case. Try

<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>

This is the case of JS with inline styling where Image is a local file that you must have imported with a path.

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

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

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

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

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

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

Conversion failed when converting the varchar value to data type int in sql

Your problem seams to be located here:

SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,LEN(Voucher_No)- LEN(@Prefix)) AS INT)) AS varchar(100)) FROM dbo.Journal_Entry;
SET @sCode=CAST(@maxCode AS INT)

As the error says, you're casting a string that contains a letter 'J' to an INT which for obvious reasons is not possible.

Either fix SUBSTRING or don't store the letter 'J' in the database and only prepend it when reading.

Dockerfile if else condition with external arguments

I had a similar issue for setting proxy server on a container.

The solution I'm using is an entrypoint script, and another script for environment variables configuration. Using RUN, you assure the configuration script runs on build, and ENTRYPOINT when you run the container.

--build-arg is used on command line to set proxy user and password.

As I need the same environment variables on container startup, I used a file to "persist" it from build to run.

The entrypoint script looks like:

#!/bin/bash
# Load the script of environment variables
. /root/configproxy.sh
# Run the main container command
exec "$@"

configproxy.sh

#!/bin/bash

function start_config {
read u p < /root/proxy_credentials

export HTTP_PROXY=http://$u:[email protected]:8080
export HTTPS_PROXY=https://$u:[email protected]:8080

/bin/cat <<EOF > /etc/apt/apt.conf 
Acquire::http::proxy "http://$u:[email protected]:8080";
Acquire::https::proxy "https://$u:[email protected]:8080";
EOF
}

if [ -s "/root/proxy_credentials" ]
then
start_config
fi

And in the Dockerfile, configure:

# Base Image
FROM ubuntu:18.04

ARG user
ARG pass

USER root

# -z the length of STRING is zero
# [] are an alias for test command
# if $user is not empty, write credentials file
RUN if [ ! -z "$user" ]; then echo "${user} ${pass}">/root/proxy_credentials ; fi

#copy bash scripts
COPY configproxy.sh /root
COPY startup.sh .

RUN ["/bin/bash", "-c", ". /root/configproxy.sh"]

# Install dependencies and tools
#RUN apt-get update -y && \
#    apt-get install -yqq --no-install-recommends \
#    vim iputils-ping

ENTRYPOINT ["./startup.sh"]
CMD ["sh", "-c", "bash"]

Build without proxy settings

docker build -t img01 -f Dockerfile . 

Build with proxy settings

docker build -t img01 --build-arg user=<USER> --build-arg pass=<PASS> -f Dockerfile . 

Take a look here.

How to get client's IP address using JavaScript?

Well, I am digressing from the question, but I had a similar need today and though I couldn't find the ID from the client using Javascript, I did the following.

On the server side: -

<div style="display:none;visibility:hidden" id="uip"><%= Request.UserHostAddress %></div>

Using Javascript

var ip = $get("uip").innerHTML;

I am using ASP.Net Ajax, but you can use getElementById instead of $get().

What's happening is, I've got a hidden div element on the page with the user's IP rendered from the server. Than in Javascript I just load that value.

This might be helpful to some people with a similar requirement like yours (like me while I hadn't figure this out).

Cheers!

Can I set enum start value in Java?

@scottf

An enum is like a Singleton. The JVM creates the instance.

If you would create it by yourself with classes it could be look like that

public static class MyEnum {

    final public static MyEnum ONE;
    final public static MyEnum TWO;

    static {
        ONE = new MyEnum("1");
        TWO = new MyEnum("2");
    }

    final String enumValue;

    private MyEnum(String value){
        enumValue = value;    
    }

    @Override
    public String toString(){
        return enumValue;
    }


}

And could be used like that:

public class HelloWorld{

   public static class MyEnum {

       final public static MyEnum ONE;
       final public static MyEnum TWO;

       static {
          ONE = new MyEnum("1");
          TWO = new MyEnum("2");
       }

       final String enumValue;

       private MyEnum(String value){
           enumValue = value;    
       }

       @Override
       public String toString(){
           return enumValue;
       }


   }

    public static void main(String []args){

       System.out.println(MyEnum.ONE);
       System.out.println(MyEnum.TWO);

       System.out.println(MyEnum.ONE == MyEnum.ONE);

       System.out.println("Hello World");
    }
}

Wait until ActiveWorkbook.RefreshAll finishes - VBA

DISCLAIMER: The code below reportedly casued some crashes! Use with care.

according to THIS answer in Excel 2010 and above CalculateUntilAsyncQueriesDone halts macros until refresh is done
ThisWorkbook.RefreshAll
Application.CalculateUntilAsyncQueriesDone

How to drop rows from pandas data frame that contains a particular string in a particular column?

If your string constraint is not just one string you can drop those corresponding rows with:

df = df[~df['your column'].isin(['list of strings'])]

The above will drop all rows containing elements of your list

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

In javascript,

You can use the list of all options of multiselect dropdown which will be an Array.Then loop through it to make Selected attributes as false in each Objects.

for(var i=0;i<list.length;i++)
{
   if(list[i].Selected==true)
    {
       list[i].Selected=false;
    }
}

Append data to a POST NSURLRequest

Any one looking for a swift solution

let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)

Using getline() with file input in C++

getline, as it name states, read a whole line, or at least till a delimiter that can be specified.

So the answer is "no", getlinedoes not match your need.

But you can do something like:

inFile >> first_name >> last_name >> age;
name = first_name + " " + last_name;

How to get detailed list of connections to database in sql server 2005?

sp_who2 will actually provide a list of connections for the database server, not a database. To view connections for a single database (YourDatabaseName in this example), you can use

DECLARE @AllConnections TABLE(
    SPID INT,
    Status VARCHAR(MAX),
    LOGIN VARCHAR(MAX),
    HostName VARCHAR(MAX),
    BlkBy VARCHAR(MAX),
    DBName VARCHAR(MAX),
    Command VARCHAR(MAX),
    CPUTime INT,
    DiskIO INT,
    LastBatch VARCHAR(MAX),
    ProgramName VARCHAR(MAX),
    SPID_1 INT,
    REQUESTID INT
)

INSERT INTO @AllConnections EXEC sp_who2

SELECT * FROM @AllConnections WHERE DBName = 'YourDatabaseName'

(Adapted from SQL Server: Filter output of sp_who2.)

Oracle date "Between" Query

Date Between Query

SELECT *
    FROM emp
    WHERE HIREDATE between to_date (to_char(sysdate, 'yyyy') ||'/09/01', 'yyyy/mm/dd')
    AND to_date (to_char(sysdate, 'yyyy') + 1|| '/08/31', 'yyyy/mm/dd');

Remove/ truncate leading zeros by javascript/jquery

I would use the Number() function:

var str = "00001";
str = Number(str).toString();
>> "1"

Or I would multiply my string by 1

var str = "00000000002346301625363";
str = (str * 1).toString();
>> "2346301625363"

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

Based on what @J. Calleja said, you have two choices

Method 1 - Random access

If you want to random access the element of Mat, just simply use

Mat.at<data_Type>(row_num, col_num) = value;

Method 2 - Continuous access

If you want to continuous access, OpenCV provides Mat iterator compatible with STL iterator and it's more C++ style

MatIterator_<double> it, end;
for( it = I.begin<double>(), end = I.end<double>(); it != end; ++it)
{
    //do something here
}

or

for(int row = 0; row < mat.rows; ++row) {
    float* p = mat.ptr(row); //pointer p points to the first place of each row
    for(int col = 0; col < mat.cols; ++col) {
         *p++;  // operation here
    }
}

If you have any difficulty to understand how Method 2 works, I borrow the picture from a blog post in the article Dynamic Two-dimensioned Arrays in C, which is much more intuitive and comprehensible.

See the picture below.

enter image description here

How do I connect to a specific Wi-Fi network in Android programmatically?

The earlier answer works, but the solution can actually be simpler. Looping through the configured networks list is not required as you get the network id when you add the network through the WifiManager.

So the complete, simplified solution would look something like this:

WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);

WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

How to show text in combobox when no item selected?

if ComboBoxStyle is set to DropDownList then the easiest way to make sure the user selects an item is to set SelectedIndex = -1, which will be empty

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

For my project's setup, "${pageContext.request.contextPath}"= refers to "src/main/webapp". Another way to tell is by right clicking on your project in Eclipse and then going to Properties:

enter image description here

How do I close an Android alertdialog

Replying to an old post but hopefully somebody might find this useful. Do this instead

final AlertDialog builder = new AlertDialog.Builder(getActivity()).create();

You can then go ahead and do,

builder.dismiss();

How to draw a path on a map using kml file?

Mathias Lin code working beautifully. However, you might want to consider changing this part inside drawPath method:

 if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                    && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

GeoPoint can be less than zero as well, I switch mine to:

     if (lngLat.length >= 2 && gp1.getLatitudeE6() != 0 && gp1.getLongitudeE6() != 0
                    && gp2.getLatitudeE6() != 0 && gp2.getLongitudeE6() != 0) {

Thank you :D

HTML5 Video Stop onClose

For a JQM+PhoneGap app the following worked for me.

The following was the minimum I had to go to get this to work. I was actually experiencing a stall due to the buffering while spawning ajax requests when the user pressed the back button. Pausing the video in Chrome and the Android browser kept it buffering. The non-async ajax request would get stuck waiting for the buffering to finish, which it never would.

Binding this to the beforepagehide event fixed it.

 $("#SOME_JQM_PAGE").live("pagebeforehide", function(event)
 {
           $("video").each(function () 
           { 
               logger.debug("PAUSE VIDEO");
               this.pause();
               this.src = "";
           });
 });

This will clear every video tag on the page.

The important part is this.src = "";

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

For bootstrap 3.0, this worked for me:

.myclass .glyphicon {color:blue !important;}