Programs & Examples On #Python 2.x

For issues related to development in Python, version 2.x.

How to pick just one item from a generator?

I don't believe there's a convenient way to retrieve an arbitrary value from a generator. The generator will provide a next() method to traverse itself, but the full sequence is not produced immediately to save memory. That's the functional difference between a generator and a list.

Web-scraping JavaScript page with Python

EDIT 30/Dec/2017: This answer appears in top results of Google searches, so I decided to update it. The old answer is still at the end.

dryscape isn't maintained anymore and the library dryscape developers recommend is Python 2 only. I have found using Selenium's python library with Phantom JS as a web driver fast enough and easy to get the work done.

Once you have installed Phantom JS, make sure the phantomjs binary is available in the current path:

phantomjs --version
# result:
2.1.1

Example

To give an example, I created a sample page with following HTML code. (link):

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Javascript scraping test</title>
</head>
<body>
  <p id='intro-text'>No javascript support</p>
  <script>
     document.getElementById('intro-text').innerHTML = 'Yay! Supports javascript';
  </script> 
</body>
</html>

without javascript it says: No javascript support and with javascript: Yay! Supports javascript

Scraping without JS support:

import requests
from bs4 import BeautifulSoup
response = requests.get(my_url)
soup = BeautifulSoup(response.text)
soup.find(id="intro-text")
# Result:
<p id="intro-text">No javascript support</p>

Scraping with JS support:

from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get(my_url)
p_element = driver.find_element_by_id(id_='intro-text')
print(p_element.text)
# result:
'Yay! Supports javascript'

You can also use Python library dryscrape to scrape javascript driven websites.

Scraping with JS support:

import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
session.visit(my_url)
response = session.body()
soup = BeautifulSoup(response)
soup.find(id="intro-text")
# Result:
<p id="intro-text">Yay! Supports javascript</p>

No module named MySQLdb

For Python 3+ version

install mysql-connector as:

pip3 install mysql-connector 

Sample Python DB connection code:

import mysql.connector
db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd=""
)
print(db_connection)

Output:

> <mysql.connector.connection.MySQLConnection object at > 0x000002338A4C6B00>

This means, database is correctly connected.

What is the difference between encode/decode?

anUnicode.encode('encoding') results in a string object and can be called on a unicode object

aString.decode('encoding') results in an unicode object and can be called on a string, encoded in given encoding.


Some more explanations:

You can create some unicode object, which doesn't have any encoding set. The way it is stored by Python in memory is none of your concern. You can search it, split it and call any string manipulating function you like.

But there comes a time, when you'd like to print your unicode object to console or into some text file. So you have to encode it (for example - in UTF-8), you call encode('utf-8') and you get a string with '\u<someNumber>' inside, which is perfectly printable.

Then, again - you'd like to do the opposite - read string encoded in UTF-8 and treat it as an Unicode, so the \u360 would be one character, not 5. Then you decode a string (with selected encoding) and get brand new object of the unicode type.

Just as a side note - you can select some pervert encoding, like 'zip', 'base64', 'rot' and some of them will convert from string to string, but I believe the most common case is one that involves UTF-8/UTF-16 and string.

How to pretty-print a numpy.array without scientific notation and with given precision?

numpy.char.mod may also be useful, depending on the details of your application e.g.:numpy.char.mod('Value=%4.2f', numpy.arange(5, 10, 0.1)) will return a string array with elements "Value=5.00", "Value=5.10" etc. (as a somewhat contrived example).

How to print a percentage value in python?

Just for the sake of completeness, since I noticed no one suggested this simple approach:

>>> print("%.0f%%" % (100 * 1.0/3))
33%

Details:

  • %.0f stands for "print a float with 0 decimal places", so %.2f would print 33.33
  • %% prints a literal %. A bit cleaner than your original +'%'
  • 1.0 instead of 1 takes care of coercing the division to float, so no more 0.0

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

  • The first danger lies in reload(sys).

    When you reload a module, you actually get two copies of the module in your runtime. The old module is a Python object like everything else, and stays alive as long as there are references to it. So, half of the objects will be pointing to the old module, and half to the new one. When you make some change, you will never see it coming when some random object doesn't see the change:

    (This is IPython shell)
    
    In [1]: import sys
    
    In [2]: sys.stdout
    Out[2]: <colorama.ansitowin32.StreamWrapper at 0x3a2aac8>
    
    In [3]: reload(sys)
    <module 'sys' (built-in)>
    
    In [4]: sys.stdout
    Out[4]: <open file '<stdout>', mode 'w' at 0x00000000022E20C0>
    
    In [11]: import IPython.terminal
    
    In [14]: IPython.terminal.interactiveshell.sys.stdout
    Out[14]: <colorama.ansitowin32.StreamWrapper at 0x3a9aac8>
    
  • Now, sys.setdefaultencoding() proper

    All that it affects is implicit conversion str<->unicode. Now, utf-8 is the sanest encoding on the planet (backward-compatible with ASCII and all), the conversion now "just works", what could possibly go wrong?

    Well, anything. And that is the danger.

    • There may be some code that relies on the UnicodeError being thrown for non-ASCII input, or does the transcoding with an error handler, which now produces an unexpected result. And since all code is tested with the default setting, you're strictly on "unsupported" territory here, and no-one gives you guarantees about how their code will behave.
    • The transcoding may produce unexpected or unusable results if not everything on the system uses UTF-8 because Python 2 actually has multiple independent "default string encodings". (Remember, a program must work for the customer, on the customer's equipment.)
      • Again, the worst thing is you will never know that because the conversion is implicit -- you don't really know when and where it happens. (Python Zen, koan 2 ahoy!) You will never know why (and if) your code works on one system and breaks on another. (Or better yet, works in IDE and breaks in console.)

How do I keep Python print from adding newlines or spaces?

For completeness, one other way is to clear the softspace value after performing the write.

import sys
print "hello",
sys.stdout.softspace=0
print "world",
print "!"

prints helloworld !

Using stdout.write() is probably more convenient for most cases though.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

This is a classic python unicode pain point! Consider the following:

a = u'bats\u00E0'
print a
 => batsà

All good so far, but if we call str(a), let's see what happens:

str(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)

Oh dip, that's not gonna do anyone any good! To fix the error, encode the bytes explicitly with .encode and tell python what codec to use:

a.encode('utf-8')
 => 'bats\xc3\xa0'
print a.encode('utf-8')
 => batsà

Voil\u00E0!

The issue is that when you call str(), python uses the default character encoding to try and encode the bytes you gave it, which in your case are sometimes representations of unicode characters. To fix the problem, you have to tell python how to deal with the string you give it by using .encode('whatever_unicode'). Most of the time, you should be fine using utf-8.

For an excellent exposition on this topic, see Ned Batchelder's PyCon talk here: http://nedbatchelder.com/text/unipain.html

Combine several images horizontally with Python

Here's my solution:

from PIL import Image


def join_images(*rows, bg_color=(0, 0, 0, 0), alignment=(0.5, 0.5)):
    rows = [
        [image.convert('RGBA') for image in row]
        for row
        in rows
    ]

    heights = [
        max(image.height for image in row)
        for row
        in rows
    ]

    widths = [
        max(image.width for image in column)
        for column
        in zip(*rows)
    ]

    tmp = Image.new(
        'RGBA',
        size=(sum(widths), sum(heights)),
        color=bg_color
    )

    for i, row in enumerate(rows):
        for j, image in enumerate(row):
            y = sum(heights[:i]) + int((heights[i] - image.height) * alignment[1])
            x = sum(widths[:j]) + int((widths[j] - image.width) * alignment[0])
            tmp.paste(image, (x, y))

    return tmp


def join_images_horizontally(*row, bg_color=(0, 0, 0), alignment=(0.5, 0.5)):
    return join_images(
        row,
        bg_color=bg_color,
        alignment=alignment
    )


def join_images_vertically(*column, bg_color=(0, 0, 0), alignment=(0.5, 0.5)):
    return join_images(
        *[[image] for image in column],
        bg_color=bg_color,
        alignment=alignment
    )

For these images:

images = [
    [Image.open('banana.png'), Image.open('apple.png')],
    [Image.open('lime.png'), Image.open('lemon.png')],
]

Results will look like:


join_images(
    *images,
    bg_color='green',
    alignment=(0.5, 0.5)
).show()

enter image description here


join_images(
    *images,
    bg_color='green',
    alignment=(0, 0)

).show()

enter image description here


join_images(
    *images,
    bg_color='green',
    alignment=(1, 1)
).show()

enter image description here

What is the difference between range and xrange functions in Python 2.X?

It is for optimization reasons.

range() will create a list of values from start to end (0 .. 20 in your example). This will become an expensive operation on very large ranges.

xrange() on the other hand is much more optimised. it will only compute the next value when needed (via an xrange sequence object) and does not create a list of all values like range() does.

Relative imports for the billionth time

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Wrote a little python package to PyPi that might help viewers of this question. The package acts as workaround if one wishes to be able to run python files containing imports containing upper level packages from within a package / project without being directly in the importing file's directory. https://pypi.org/project/import-anywhere/

How to read a CSV file from a URL with Python?

import pandas as pd
url='https://raw.githubusercontent.com/juliencohensolal/BankMarketing/master/rawData/bank-additional-full.csv'
data = pd.read_csv(url,sep=";") # use sep="," for coma separation. 
data.describe()

enter image description here

How to run multiple Python versions on Windows

I strongly recommend the pyenv-win project.

enter image description here

Thanks to kirankotari's work, now we have a Windows version of pyenv.

How to add an element to the beginning of an OrderedDict?

I would suggest adding a prepend() method to this pure Python ActiveState recipe or deriving a subclass from it. The code to do so could be a fairly efficient given that the underlying data structure for ordering is a linked-list.

Update

To prove this approach is feasible, below is code that does what's suggested. As a bonus, I also made a few additional minor changes to get to work in both Python 2.7.15 and 3.7.1.

A prepend() method has been added to the class in the recipe and has been implemented in terms of another method that's been added named move_to_end(), which was added to OrderedDict in Python 3.2.

prepend() can also be implemented directly, almost exactly as shown at the beginning of @Ashwini Chaudhary's answer—and doing so would likely result in it being slightly faster, but that's been left as an exercise for the motivated reader...

# Ordered Dictionary for Py2.4 from https://code.activestate.com/recipes/576693

# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
# Passes Python2.7's test suite and incorporates all the latest updates.

try:
    from thread import get_ident as _get_ident
except ImportError:  # Python 3
#    from dummy_thread import get_ident as _get_ident
    from _thread import get_ident as _get_ident  # Changed - martineau

try:
    from _abcoll import KeysView, ValuesView, ItemsView
except ImportError:
    pass

class MyOrderedDict(dict):
    'Dictionary that remembers insertion order'
    # An inherited dict maps keys to values.
    # The inherited dict provides __getitem__, __len__, __contains__, and get.
    # The remaining methods are order-aware.
    # Big-O running times for all methods are the same as for regular dictionaries.

    # The internal self.__map dictionary maps keys to links in a doubly linked list.
    # The circular doubly linked list starts and ends with a sentinel element.
    # The sentinel element never gets deleted (this simplifies the algorithm).
    # Each link is stored as a list of length three:  [PREV, NEXT, KEY].

    def __init__(self, *args, **kwds):
        '''Initialize an ordered dictionary.  Signature is the same as for
        regular dictionaries, but keyword arguments are not recommended
        because their insertion order is arbitrary.

        '''
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        try:
            self.__root
        except AttributeError:
            self.__root = root = []  # sentinel node
            root[:] = [root, root, None]
            self.__map = {}
        self.__update(*args, **kwds)

    def prepend(self, key, value):  # Added to recipe.
        self.update({key: value})
        self.move_to_end(key, last=False)

    #### Derived from cpython 3.2 source code.
    def move_to_end(self, key, last=True):  # Added to recipe.
        '''Move an existing element to the end (or beginning if last==False).

        Raises KeyError if the element does not exist.
        When last=True, acts like a fast version of self[key]=self.pop(key).
        '''
        PREV, NEXT, KEY = 0, 1, 2

        link = self.__map[key]
        link_prev = link[PREV]
        link_next = link[NEXT]
        link_prev[NEXT] = link_next
        link_next[PREV] = link_prev
        root = self.__root

        if last:
            last = root[PREV]
            link[PREV] = last
            link[NEXT] = root
            last[NEXT] = root[PREV] = link
        else:
            first = root[NEXT]
            link[PREV] = root
            link[NEXT] = first
            root[NEXT] = first[PREV] = link
    ####

    def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
        'od.__setitem__(i, y) <==> od[i]=y'
        # Setting a new item creates a new link which goes at the end of the linked
        # list, and the inherited dictionary is updated with the new key/value pair.
        if key not in self:
            root = self.__root
            last = root[0]
            last[1] = root[0] = self.__map[key] = [last, root, key]
        dict_setitem(self, key, value)

    def __delitem__(self, key, dict_delitem=dict.__delitem__):
        'od.__delitem__(y) <==> del od[y]'
        # Deleting an existing item uses self.__map to find the link which is
        # then removed by updating the links in the predecessor and successor nodes.
        dict_delitem(self, key)
        link_prev, link_next, key = self.__map.pop(key)
        link_prev[1] = link_next
        link_next[0] = link_prev

    def __iter__(self):
        'od.__iter__() <==> iter(od)'
        root = self.__root
        curr = root[1]
        while curr is not root:
            yield curr[2]
            curr = curr[1]

    def __reversed__(self):
        'od.__reversed__() <==> reversed(od)'
        root = self.__root
        curr = root[0]
        while curr is not root:
            yield curr[2]
            curr = curr[0]

    def clear(self):
        'od.clear() -> None.  Remove all items from od.'
        try:
            for node in self.__map.itervalues():
                del node[:]
            root = self.__root
            root[:] = [root, root, None]
            self.__map.clear()
        except AttributeError:
            pass
        dict.clear(self)

    def popitem(self, last=True):
        '''od.popitem() -> (k, v), return and remove a (key, value) pair.
        Pairs are returned in LIFO order if last is true or FIFO order if false.

        '''
        if not self:
            raise KeyError('dictionary is empty')
        root = self.__root
        if last:
            link = root[0]
            link_prev = link[0]
            link_prev[1] = root
            root[0] = link_prev
        else:
            link = root[1]
            link_next = link[1]
            root[1] = link_next
            link_next[0] = root
        key = link[2]
        del self.__map[key]
        value = dict.pop(self, key)
        return key, value

    # -- the following methods do not depend on the internal structure --

    def keys(self):
        'od.keys() -> list of keys in od'
        return list(self)

    def values(self):
        'od.values() -> list of values in od'
        return [self[key] for key in self]

    def items(self):
        'od.items() -> list of (key, value) pairs in od'
        return [(key, self[key]) for key in self]

    def iterkeys(self):
        'od.iterkeys() -> an iterator over the keys in od'
        return iter(self)

    def itervalues(self):
        'od.itervalues -> an iterator over the values in od'
        for k in self:
            yield self[k]

    def iteritems(self):
        'od.iteritems -> an iterator over the (key, value) items in od'
        for k in self:
            yield (k, self[k])

    def update(*args, **kwds):
        '''od.update(E, **F) -> None.  Update od from dict/iterable E and F.

        If E is a dict instance, does:           for k in E: od[k] = E[k]
        If E has a .keys() method, does:         for k in E.keys(): od[k] = E[k]
        Or if E is an iterable of items, does:   for k, v in E: od[k] = v
        In either case, this is followed by:     for k, v in F.items(): od[k] = v

        '''
        if len(args) > 2:
            raise TypeError('update() takes at most 2 positional '
                            'arguments (%d given)' % (len(args),))
        elif not args:
            raise TypeError('update() takes at least 1 argument (0 given)')
        self = args[0]
        # Make progressively weaker assumptions about "other"
        other = ()
        if len(args) == 2:
            other = args[1]
        if isinstance(other, dict):
            for key in other:
                self[key] = other[key]
        elif hasattr(other, 'keys'):
            for key in other.keys():
                self[key] = other[key]
        else:
            for key, value in other:
                self[key] = value
        for key, value in kwds.items():
            self[key] = value

    __update = update  # let subclasses override update without breaking __init__

    __marker = object()

    def pop(self, key, default=__marker):
        '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised.

        '''
        if key in self:
            result = self[key]
            del self[key]
            return result
        if default is self.__marker:
            raise KeyError(key)
        return default

    def setdefault(self, key, default=None):
        'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
        if key in self:
            return self[key]
        self[key] = default
        return default

    def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key]

    def __reduce__(self):
        'Return state information for pickling'
        items = [[k, self[k]] for k in self]
        inst_dict = vars(self).copy()
        for k in vars(MyOrderedDict()):
            inst_dict.pop(k, None)
        if inst_dict:
            return (self.__class__, (items,), inst_dict)
        return self.__class__, (items,)

    def copy(self):
        'od.copy() -> a shallow copy of od'
        return self.__class__(self)

    @classmethod
    def fromkeys(cls, iterable, value=None):
        '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
        and values equal to v (which defaults to None).

        '''
        d = cls()
        for key in iterable:
            d[key] = value
        return d

    def __eq__(self, other):
        '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
        while comparison to a regular mapping is order-insensitive.

        '''
        if isinstance(other, MyOrderedDict):
            return len(self)==len(other) and self.items() == other.items()
        return dict.__eq__(self, other)

    def __ne__(self, other):
        return not self == other

    # -- the following methods are only used in Python 2.7 --

    def viewkeys(self):
        "od.viewkeys() -> a set-like object providing a view on od's keys"
        return KeysView(self)

    def viewvalues(self):
        "od.viewvalues() -> an object providing a view on od's values"
        return ValuesView(self)

    def viewitems(self):
        "od.viewitems() -> a set-like object providing a view on od's items"
        return ItemsView(self)

if __name__ == '__main__':

    d1 = MyOrderedDict([('a', '1'), ('b', '2')])
    d1.update({'c':'3'})
    print(d1)  # -> MyOrderedDict([('a', '1'), ('b', '2'), ('c', '3')])

    d2 = MyOrderedDict([('a', '1'), ('b', '2')])
    d2.prepend('c', 100)
    print(d2)  # -> MyOrderedDict([('c', 100), ('a', '1'), ('b', '2')])

How to redirect 'print' output to a file using python?

If you are using Linux I suggest you to use the tee command. The implementation goes like this:

python python_file.py | tee any_file_name.txt

If you don't want to change anything in the code, I think this might be the best possible solution. You can also implement logger but you need do some changes in the code.

Python division

You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.

>>> 1 / 2
0

You should make one of them a float:

>>> float(10 - 20) / (100 - 10)
-0.1111111111111111

or from __future__ import division, which the forces / to adopt Python 3.x's behavior that always returns a float.

>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111

How do you round UP a number in Python?

You can use floor devision and add 1 to it. 2.3 // 2 + 1

How do I calculate square root in Python?

Perhaps a simple way to remember: add a dot after the numerator (or denominator)

16 ** (1. / 2)   # 4
289 ** (1. / 2)  # 17
27 ** (1. / 3)   # 3

Python - 'ascii' codec can't decode byte

In case you're dealing with Unicode, sometimes instead of encode('utf-8'), you can also try to ignore the special characters, e.g.

"??".encode('ascii','ignore')

or as something.decode('unicode_escape').encode('ascii','ignore') as suggested here.

Not particularly useful in this example, but can work better in other scenarios when it's not possible to convert some special characters.

Alternatively you can consider replacing particular character using replace().

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

In your android_suggest.py, break up that monstrous one-liner return statement into one_step_at_a_time pieces. Log repr(string_passed_to_json.loads) somewhere so that it can be checked after an exception happens. Eye-ball the results. If the problem is not evident, edit your question to show the repr.

How to get string objects instead of Unicode from JSON?

With Python 3.6, sometimes I still run into this problem. For example, when getting response from a REST API and loading the response text to JSON, I still get the unicode strings. Found a simple solution using json.dumps().

response_message = json.loads(json.dumps(response.text))
print(response_message)

What are the differences between the urllib, urllib2, urllib3 and requests module?

You should generally use urllib2, since this makes things a bit easier at times by accepting Request objects and will also raise a URLException on protocol errors. With Google App Engine though, you can't use either. You have to use the URL Fetch API that Google provides in its sandboxed Python environment.

raw_input function in Python

Another example method, to mix the prompt using print, if you need to make your code simpler.

Format:-

x = raw_input () -- This will return the user input as a string

x= int(raw_input()) -- Gets the input number as a string from raw_input() and then converts it to an integer using int().

print '\nWhat\'s your name ?', 
name = raw_input('--> ')
print '\nHow old are you, %s?' % name,
age = int(raw_input())
print '\nHow tall are you (in cms), %s?' % name,
height = int(raw_input())
print '\nHow much do you weigh (in kgs), %s?' % name,
weight = int(raw_input())

print '\nSo, %s is %d years old, %d cms tall and weighs %d kgs.\n' %(
name, age, height, weight)

Safest way to convert float to integer in python?

Another code sample to convert a real/float to an integer using variables. "vel" is a real/float number and converted to the next highest INTEGER, "newvel".

import arcpy.math, os, sys, arcpy.da
.
.
with arcpy.da.SearchCursor(densifybkp,[floseg,vel,Length]) as cursor:
 for row in cursor:
    curvel = float(row[1])
    newvel = int(math.ceil(curvel))

Writing Unicode text to a text file?

Preface: will your viewer work?

Make sure your viewer/editor/terminal (however you are interacting with your utf-8 encoded file) can read the file. This is frequently an issue on Windows, for example, Notepad.

Writing Unicode text to a text file?

In Python 2, use open from the io module (this is the same as the builtin open in Python 3):

import io

Best practice, in general, use UTF-8 for writing to files (we don't even have to worry about byte-order with utf-8).

encoding = 'utf-8'

utf-8 is the most modern and universally usable encoding - it works in all web browsers, most text-editors (see your settings if you have issues) and most terminals/shells.

On Windows, you might try utf-16le if you're limited to viewing output in Notepad (or another limited viewer).

encoding = 'utf-16le' # sorry, Windows users... :(

And just open it with the context manager and write your unicode characters out:

with io.open(filename, 'w', encoding=encoding) as f:
    f.write(unicode_object)

Example using many Unicode characters

Here's an example that attempts to map every possible character up to three bits wide (4 is the max, but that would be going a bit far) from the digital representation (in integers) to an encoded printable output, along with its name, if possible (put this into a file called uni.py):

from __future__ import print_function
import io
from unicodedata import name, category
from curses.ascii import controlnames
from collections import Counter

try: # use these if Python 2
    unicode_chr, range = unichr, xrange
except NameError: # Python 3
    unicode_chr = chr

exclude_categories = set(('Co', 'Cn'))
counts = Counter()
control_names = dict(enumerate(controlnames))
with io.open('unidata', 'w', encoding='utf-8') as f:
    for x in range((2**8)**3): 
        try:
            char = unicode_chr(x)
        except ValueError:
            continue # can't map to unicode, try next x
        cat = category(char)
        counts.update((cat,))
        if cat in exclude_categories:
            continue # get rid of noise & greatly shorten result file
        try:
            uname = name(char)
        except ValueError: # probably control character, don't use actual
            uname = control_names.get(x, '')
            f.write(u'{0:>6x} {1}    {2}\n'.format(x, cat, uname))
        else:
            f.write(u'{0:>6x} {1}  {2}  {3}\n'.format(x, cat, char, uname))
# may as well describe the types we logged.
for cat, count in counts.items():
    print('{0} chars of category, {1}'.format(count, cat))

This should run in the order of about a minute, and you can view the data file, and if your file viewer can display unicode, you'll see it. Information about the categories can be found here. Based on the counts, we can probably improve our results by excluding the Cn and Co categories, which have no symbols associated with them.

$ python uni.py

It will display the hexadecimal mapping, category, symbol (unless can't get the name, so probably a control character), and the name of the symbol. e.g.

I recommend less on Unix or Cygwin (don't print/cat the entire file to your output):

$ less unidata

e.g. will display similar to the following lines which I sampled from it using Python 2 (unicode 5.2):

     0 Cc NUL
    20 Zs     SPACE
    21 Po  !  EXCLAMATION MARK
    b6 So  ¶  PILCROW SIGN
    d0 Lu  Ð  LATIN CAPITAL LETTER ETH
   e59 Nd  ?  THAI DIGIT NINE
  2887 So  ?  BRAILLE PATTERN DOTS-1238
  bc13 Lo  ?  HANGUL SYLLABLE MIH
  ffeb Sm  ?  HALFWIDTH RIGHTWARDS ARROW

My Python 3.5 from Anaconda has unicode 8.0, I would presume most 3's would.

How can I force division to be floating point? Division keeps rounding down to 0?

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.


A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.

How to make an unaware datetime timezone aware in python

All of these examples use an external module, but you can achieve the same result using just the datetime module, as also presented in this SO answer:

from datetime import datetime
from datetime import timezone

dt = datetime.now()
dt.replace(tzinfo=timezone.utc)

print(dt.replace(tzinfo=timezone.utc).isoformat())
'2017-01-12T22:11:31+00:00'

Fewer dependencies and no pytz issues.

NOTE: If you wish to use this with python3 and python2, you can use this as well for the timezone import (hardcoded for UTC):

try:
    from datetime import timezone
    utc = timezone.utc
except ImportError:
    #Hi there python2 user
    class UTC(tzinfo):
        def utcoffset(self, dt):
            return timedelta(0)
        def tzname(self, dt):
            return "UTC"
        def dst(self, dt):
            return timedelta(0)
    utc = UTC()

Malformed String ValueError ast.literal_eval() with String representation of Tuple

From the documentation for ast.literal_eval():

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Decimal isn't on the list of things allowed by ast.literal_eval().

Python string to unicode

>>> a="Hello\u2026"
>>> print a.decode('unicode-escape')
Hello…

write() versus writelines() and concatenated strings

Why am I unable to use a string for a newline in write() but I can use it in writelines()?

The idea is the following: if you want to write a single string you can do this with write(). If you have a sequence of strings you can write them all using writelines().

write(arg) expects a string as argument and writes it to the file. If you provide a list of strings, it will raise an exception (by the way, show errors to us!).

writelines(arg) expects an iterable as argument (an iterable object can be a tuple, a list, a string, or an iterator in the most general sense). Each item contained in the iterator is expected to be a string. A tuple of strings is what you provided, so things worked.

The nature of the string(s) does not matter to both of the functions, i.e. they just write to the file whatever you provide them. The interesting part is that writelines() does not add newline characters on its own, so the method name can actually be quite confusing. It actually behaves like an imaginary method called write_all_of_these_strings(sequence).

What follows is an idiomatic way in Python to write a list of strings to a file while keeping each string in its own line:

lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
    f.write('\n'.join(lines))

This takes care of closing the file for you. The construct '\n'.join(lines) concatenates (connects) the strings in the list lines and uses the character '\n' as glue. It is more efficient than using the + operator.

Starting from the same lines sequence, ending up with the same output, but using writelines():

lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
    f.writelines("%s\n" % l for l in lines)

This makes use of a generator expression and dynamically creates newline-terminated strings. writelines() iterates over this sequence of strings and writes every item.

Edit: Another point you should be aware of:

write() and readlines() existed before writelines() was introduced. writelines() was introduced later as a counterpart of readlines(), so that one could easily write the file content that was just read via readlines():

outfile.writelines(infile.readlines())

Really, this is the main reason why writelines has such a confusing name. Also, today, we do not really want to use this method anymore. readlines() reads the entire file to the memory of your machine before writelines() starts to write the data. First of all, this may waste time. Why not start writing parts of data while reading other parts? But, most importantly, this approach can be very memory consuming. In an extreme scenario, where the input file is larger than the memory of your machine, this approach won't even work. The solution to this problem is to use iterators only. A working example:

with open('inputfile') as infile:
    with open('outputfile') as outfile:
        for line in infile:
            outfile.write(line)

This reads the input file line by line. As soon as one line is read, this line is written to the output file. Schematically spoken, there always is only one single line in memory (compared to the entire file content being in memory in case of the readlines/writelines approach).

Setting the correct encoding when piping stdout in Python

Your code works when run in an script because Python encodes the output to whatever encoding your terminal application is using. If you are piping you must encode it yourself.

A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send.

# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')

Another didactic example is a Python program to convert between ISO-8859-1 and UTF-8, making everything uppercase in between.

import sys
for line in sys.stdin:
    # Decode what you receive:
    line = line.decode('iso8859-1')

    # Work with Unicode internally:
    line = line.upper()

    # Encode what you send:
    line = line.encode('utf-8')
    sys.stdout.write(line)

Setting the system default encoding is a bad idea, because some modules and libraries you use can rely on the fact it is ASCII. Don't do it.

How do you use subprocess.check_output() in Python?

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'—you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

What exactly do "u" and "r" string flags do, and what are raw string literals?

'raw string' means it is stored as it appears. For example, '\' is just a backslash instead of an escaping.

What is the difference between dict.items() and dict.iteritems() in Python2?

dict.items() return list of tuples, and dict.iteritems() return iterator object of tuple in dictionary as (key,value). The tuples are the same, but container is different.

dict.items() basically copies all dictionary into list. Try using following code to compare the execution times of the dict.items() and dict.iteritems(). You will see the difference.

import timeit

d = {i:i*2 for i in xrange(10000000)}  
start = timeit.default_timer() #more memory intensive
for key,value in d.items():
    tmp = key + value #do something like print
t1 = timeit.default_timer() - start

start = timeit.default_timer()
for key,value in d.iteritems(): #less memory intensive
    tmp = key + value
t2 = timeit.default_timer() - start

Output in my machine:

Time with d.items(): 9.04773592949
Time with d.iteritems(): 2.17707300186

This clearly shows that dictionary.iteritems() is much more efficient.

How to use XPath in Python?

Another library is 4Suite: http://sourceforge.net/projects/foursuite/

I do not know how spec-compliant it is. But it has worked very well for my use. It looks abandoned.

How to return dictionary keys as a list in Python?

You can also use a list comprehension:

>>> newdict = {1:0, 2:0, 3:0}
>>> [k  for  k in  newdict.keys()]
[1, 2, 3]

Or, shorter,

>>> [k  for  k in  newdict]
[1, 2, 3]

Note: Order is not guaranteed on versions under 3.7 (ordering is still only an implementation detail with CPython 3.6).

Printing without newline (print 'a',) prints a space, how to remove?

From PEP 3105: print As a Function in the What’s New in Python 2.6 document:

>>> from __future__ import print_function
>>> print('a', end='')

Obviously that only works with python 3.0 or higher (or 2.6+ with a from __future__ import print_function at the beginning). The print statement was removed and became the print() function by default in Python 3.0.

Determine if 2 lists have the same elements, regardless of order?

Determine if 2 lists have the same elements, regardless of order?

Inferring from your example:

x = ['a', 'b']
y = ['b', 'a']

that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are), the most direct and computationally efficient answer uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school).

set(x) == set(y) # prefer this if elements are hashable

In the case that the elements are hashable, but non-unique, the collections.Counter also works semantically as a multiset, but it is far slower:

from collections import Counter
Counter(x) == Counter(y)

Prefer to use sorted:

sorted(x) == sorted(y) 

if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.

Empirical Experiment

An empirical experiment concludes that one should prefer set, then sorted. Only opt for Counter if you need other things like counts or further usage as a multiset.

First setup:

import timeit
import random
from collections import Counter

data = [str(random.randint(0, 100000)) for i in xrange(100)]
data2 = data[:]     # copy the list into a new one

def sets_equal(): 
    return set(data) == set(data2)

def counters_equal(): 
    return Counter(data) == Counter(data2)

def sorted_lists_equal(): 
    return sorted(data) == sorted(data2)

And testing:

>>> min(timeit.repeat(sets_equal))
13.976069927215576
>>> min(timeit.repeat(counters_equal))
73.17287588119507
>>> min(timeit.repeat(sorted_lists_equal))
36.177085876464844

So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.

Python unexpected EOF while parsing

Check if all the parameters of functions are defined before they are called. I faced this problem while practicing Kaggle.

What is the best way to remove accents (normalize) in a Python unicode string?

Actually I work on project compatible python 2.6, 2.7 and 3.4 and I have to create IDs from free user entries.

Thanks to you, I have created this function that works wonders.

import re
import unicodedata

def strip_accents(text):
    """
    Strip accents from input String.

    :param text: The input string.
    :type text: String.

    :returns: The processed String.
    :rtype: String.
    """
    try:
        text = unicode(text, 'utf-8')
    except (TypeError, NameError): # unicode is a default on python 3 
        pass
    text = unicodedata.normalize('NFD', text)
    text = text.encode('ascii', 'ignore')
    text = text.decode("utf-8")
    return str(text)

def text_to_id(text):
    """
    Convert input text to id.

    :param text: The input string.
    :type text: String.

    :returns: The processed String.
    :rtype: String.
    """
    text = strip_accents(text.lower())
    text = re.sub('[ ]+', '_', text)
    text = re.sub('[^0-9a-zA-Z_-]', '', text)
    return text

result:

text_to_id("Montréal, über, 12.89, Mère, Françoise, noël, 889")
>>> 'montreal_uber_1289_mere_francoise_noel_889'

How to print variables without spaces between values

>>> value=42

>>> print "Value is %s"%('"'+str(value)+'"') 

Value is "42"

What is __future__ in Python used for and how/when to use it, and how it works

After Python 3.0 onward, print is no longer just a statement, its a function instead. and is included in PEP 3105.

Also I think the Python 3.0 package has still these special functionality. Lets see its usability through a traditional "Pyramid program" in Python:

from __future__ import print_function

class Star(object):
    def __init__(self,count):
        self.count = count

    def start(self):
        for i in range(1,self.count):
            for j in range (i): 
                print('*', end='') # PEP 3105: print As a Function 
            print()

a = Star(5)
a.start()

Output:
*
**
***
****

If we use normal print function, we won't be able to achieve the same output, since print() comes with a extra newline. So every time the inner for loop execute, it will print * onto the next line.

How to sort a data frame by date

The only way I found to work with hours, through an US format in source (mm-dd-yyyy HH-MM-SS PM/AM)...

df_dataSet$time <- as.POSIXct( df_dataSet$time , format = "%m/%d/%Y %I:%M:%S %p" , tz = "GMT")
class(df_dataSet$time)
df_dataSet <- df_dataSet[do.call(order, df_dataSet), ] 

Postgresql - select something where date = "01/01/11"

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

Fixed positioned div within a relative parent div

Gavin,

The issue you are having is a misunderstanding of positioning. If you want it to be "fixed" relative to the parent, then you really want your #fixed to be position:absolute which will update its position relative to the parent.

This question fully describes positioning types and how to use them effectively.

In summary, your CSS should be

#wrap{ 
    position:relative;
}
#fixed{ 
    position:absolute;
    top:30px;
    left:40px;
}

Get sum of MySQL column in PHP

$sql = "SELECT SUM(Value) FROM Codes";

$result = mysql_query($query);

while($row = mysql_fetch_array($result)){

    sum = $row['SUM(price)'];

}

echo sum;

Sending HTTP POST Request In Java

I suggest using Postman to generate the request code. Simply make the request using Postman then hit the code tab:

code tab

Then you'll get the following window to choose in which language you want your request code to be: request code generation

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

If your class extends Serializable, you can write and read objects through a ByteArrayOutputStream, that's what I usually do.

Connecting to smtp.gmail.com via command line

Gmail require SMTP communication with their server to be encrypted. Although you're opening up a connection to Gmail's server on port 465, unfortunately you won't be able to communicate with it in plaintext as Gmail require you to use STARTTLS/SSL encryption for the connection.

The VMware Authorization Service is not running

type Services at search, then start Services

enter image description here

then start all VM services

enter image description here

Multiline input form field using Bootstrap

I think the problem is that you are using type="text" instead of textarea. What you want is:

<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>

To clarify, a type="text" will always be one row, where-as a textarea can be multiple.

How do I get the HTML code of a web page in PHP?

If your PHP server allows url fopen wrappers then the simplest way is:

$html = file_get_contents('https://stackoverflow.com/questions/ask');

If you need more control then you should look at the cURL functions:

$c = curl_init('https://stackoverflow.com/questions/ask');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
//curl_setopt(... other options you want...)

$html = curl_exec($c);

if (curl_error($c))
    die(curl_error($c));

// Get the status code
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);

curl_close($c);

Quicksort with Python

def quick_sort(list):
    if len(list) ==0:
        return []

    return  quick_sort(filter( lambda item: item < list[0],list)) + [v for v in list if v==list[0] ]  +  quick_sort( filter( lambda item: item > list[0], list))

Is an empty href valid?

The current HTML5 draft also allows ommitting the href attribute completely.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant.

To answer your question: Yes it's valid.

How to obtain Telegram chat_id for a specific user?

Straight out from the documentation:

Suppose the website example.com would like to send notifications to its users via a Telegram bot. Here's what they could do to enable notifications for a user with the ID 123.

  1. Create a bot with a suitable username, e.g. @ExampleComBot
  2. Set up a webhook for incoming messages
  3. Generate a random string of a sufficient length, e.g. $memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
  4. Put the value 123 with the key $memcache_key into Memcache for 3600 seconds (one hour)
  5. Show our user the button https://telegram.me/ExampleComBot?start=vCH1vGWJxfSeofSAs0K5PA
  6. Configure the webhook processor to query Memcached with the parameter that is passed in incoming messages beginning with /start. If the key exists, record the chat_id passed to the webhook as telegram_chat_id for the user 123. Remove the key from Memcache.
  7. Now when we want to send a notification to the user 123, check if they have the field telegram_chat_id. If yes, use the sendMessage method in the Bot API to send them a message in Telegram.

Amazon S3 boto - how to create a folder?

With AWS SDK .Net works perfectly, just add "/" at the end of the folder name string:

var folderKey =  folderName + "/"; //end the folder name with "/"
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretKey);
var request = new PutObjectRequest();
request.WithBucketName(AWSBucket);
request.WithKey(folderKey);
request.WithContentBody(string.Empty);
S3Response response = client.PutObject(request);

Then refresh your AWS console, and you will see the folder

How can I use Async with ForEach?

Starting with C# 8.0, you can create and consume streams asynchronously.

    private async void button1_Click(object sender, EventArgs e)
    {
        IAsyncEnumerable<int> enumerable = GenerateSequence();

        await foreach (var i in enumerable)
        {
            Debug.WriteLine(i);
        }
    }

    public static async IAsyncEnumerable<int> GenerateSequence()
    {
        for (int i = 0; i < 20; i++)
        {
            await Task.Delay(100);
            yield return i;
        }
    }

More

Creating a PDF from a RDLC Report in the Background

You can instanciate LocalReport

                FicheInscriptionBean fiche = new FicheInscriptionBean();
                fiche.ToFicheInscriptionBean(inscription);List<FicheInscriptionBean> list = new List<FicheInscriptionBean>();
                list.Add(fiche);
                ReportDataSource rds = new ReportDataSource();
                rds = new ReportDataSource("InscriptionDataSet", list);
                // attachement du QrCode.
                string stringToCode = numinscription + "," + inscription.Nom + "," + inscription.Prenom + "," + inscription.Cin;
                Bitmap BitmapCaptcha = PostulerFiche.GenerateQrCode(fiche.NumInscription + ":" + fiche.Cin, Brushes.Black, Brushes.White, 200);
                MemoryStream ms = new MemoryStream();
                BitmapCaptcha.Save(ms, ImageFormat.Gif);
                var base64Data = Convert.ToBase64String(ms.ToArray());
                string QR_IMG = base64Data;
                ReportParameter parameter = new ReportParameter("QR_IMG", QR_IMG, true);

                LocalReport report = new LocalReport();
                report.ReportPath = Page.Server.MapPath("~/rdlc/FicheInscription.rdlc");
                report.DataSources.Clear();
                report.SetParameters(new ReportParameter[] { parameter });
                report.DataSources.Add(rds);
                report.Refresh();

                string FileName = "FichePreinscription_" + numinscription + ".pdf";
                string extension;
                string encoding;
                string mimeType;
                string[] streams;
                Warning[] warnings;
                Byte[] mybytes = report.Render("PDF", null,
                              out extension, out encoding,
                              out mimeType, out streams, out warnings);
                using (FileStream fs = File.Create(Server.MapPath("~/rdlc/Reports/" + FileName)))
                {
                    fs.Write(mybytes, 0, mybytes.Length);
                }
                Response.ClearHeaders();
                Response.ClearContent();
                Response.Buffer = true;
                Response.Clear();
                Response.Charset = "";
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + FileName + "\"");
                Response.WriteFile(Server.MapPath("~/rdlc/Reports/" + FileName));

                Response.Flush();
                File.Delete(Server.MapPath("~/rdlc/Reports/" + FileName));
                Response.Close();
                Response.End();

Why does using an Underscore character in a LIKE filter give me all the results?

Underscore is a wildcard for something. for example 'A_%' will look for all match that Start whit 'A' and have minimum 1 extra character after that

Maven Out of Memory Build Failure

Add option

-XX:MaxPermSize=512m

to MAVEN_OPTS

maven-compiler-plugin options

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.5.1</version>
    <configuration>
      <fork>true</fork>
      <meminitial>1024m</meminitial>
      <maxmem>2024m</maxmem>
    </configuration>
  </plugin>

How do I replace text in a selection?

As @JOPLOmacedo stated, ctrl + F is what you need, but if you can't use that shortcut you can check in menu:

  • Find -> Find..

    and there you have it.
    You can also set a custom keybind for Find going in:

  • Preferences -> Key Bindings - User

    As your request for the selection only request, there is a button right next to the search field where you can opt-in for "in selection".

  • How can I add (simple) tracing in C#?

    DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

    There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

    CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

    Finalize vs Dispose

    The main difference between Dispose and Finalize is that:

    Dispose is usually called by your code. The resources are freed instantly when you call it. People forget to call the method, so using() {} statement is invented. When your program finishes the execution of the code inside the {}, it will call Dispose method automatically.

    Finalize is not called by your code. It is mean to be called by the Garbage Collector (GC). That means the resource might be freed anytime in future whenever GC decides to do so. When GC does its work, it will go through many Finalize methods. If you have heavy logic in this, it will make the process slow. It may cause performance issues for your program. So be careful about what you put in there.

    I personally would write most of the destruction logic in Dispose. Hopefully, this clears up the confusion.

    Can we convert a byte array into an InputStream in Java?

    If you use Robert Harder's Base64 utility, then you can do:

    InputStream is = new Base64.InputStream(cph);
    

    Or with sun's JRE, you can do:

    InputStream is = new
    com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)
    

    However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.

    There are other Stack Overflow questions about Base64 decoding, such as this one.

    Setting the MySQL root user password on OS X

    To reference MySQL 8.0.15 + , the password() function is not available. Use the command below.

    Kindly use

    UPDATE mysql.user SET authentication_string='password' WHERE User='root';
    

    How can I connect to MySQL on a WAMP server?

    Try opening Port 3306, and using that in the connection string not 8080.

    Check if a string within a list contains a specific string with Linq

    I think you want Any:

    if (myList.Any(str => str.Contains("Mdd LH")))
    

    It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)

    Graphical DIFF programs for linux

    I have used Meld once, which seemed very nice, and I may try more often. vimdiff works well, if you know vim well. Lastly I would mention I've found xxdiff does a reasonable job for a quick comparison. There are many diff programs out there which do a good job.

    NameError: name 'datetime' is not defined

    You need to import the module datetime first:

    >>> import datetime
    

    After that it works:

    >>> import datetime
    >>> date = datetime.date.today()
    >>> date
    datetime.date(2013, 11, 12)
    

    How do I break out of nested loops in Java?

    You can do the following:

    1. set a local variable to false

    2. set that variable true in the first loop, when you want to break

    3. then you can check in the outer loop, that whether the condition is set then break from the outer loop as well.

      boolean isBreakNeeded = false;
      for (int i = 0; i < some.length; i++) {
          for (int j = 0; j < some.lengthasWell; j++) {
              //want to set variable if (){
              isBreakNeeded = true;
              break;
          }
      
          if (isBreakNeeded) {
              break; //will make you break from the outer loop as well
          }
      }
      

    Android Studio: Module won't show up in "Edit Configuration"

    In Android Studio 3.1.2 I have faced the same issue. I resolved this issue by click on "File->Sync Project with Gradle Files".This works for me. :)

    How to bring view in front of everything?

    If you are using ConstraintLayout, just put the element after the other elements to make it on front than the others

    Can I map a hostname *and* a port with /etc/hosts?

    If you really need to do this, use reverse proxy.

    For example, with nginx as reverse proxy

    server {
      listen       api.mydomain.com:80;
      server_name  api.mydomain.com;
      location / {
        proxy_pass http://127.0.0.1:8000;
      }
    }
    

    Rails: call another controller action from a controller

    You can use a redirect to that action :

    redirect_to your_controller_action_url
    

    More on : Rails Guide

    To just render the new action :

    redirect_to your_controller_action_url and return
    

    How to hide a TemplateField column in a GridView

    GridView1.Columns[columnIndex].Visible = false;
    

    Coarse-grained vs fine-grained

    Corse-grained services provides broader functionalities as compared to fine-grained service. Depending on the business domain, a single service can be created to serve a single business unit or specialised multiple fine-grained services can be created if subunits are largely independent of each other. Coarse grained service may get more difficult may be less adaptable to change due to its size while fine-grained service may introduce additional complexity of managing multiple services.

    How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

    From the jQuery documentation: you specify the asynchronous option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

    Here's what your code would look like if changed as suggested:

    beforecreate: function (node, targetNode, type, to) {
        jQuery.ajax({
            url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
            success: function (result) {
                if (result.isOk == false) alert(result.message);
            },
            async: false
        });
    }
    

    NSRange from Swift Range?

    func formatAttributedStringWithHighlights(text: String, highlightedSubString: String?, formattingAttributes: [String: AnyObject]) -> NSAttributedString {
        let mutableString = NSMutableAttributedString(string: text)
    
        let text = text as NSString         // convert to NSString be we need NSRange
        if let highlightedSubString = highlightedSubString {
            let highlightedSubStringRange = text.rangeOfString(highlightedSubString) // find first occurence
            if highlightedSubStringRange.length > 0 {       // check for not found
                mutableString.setAttributes(formattingAttributes, range: highlightedSubStringRange)
            }
        }
    
        return mutableString
    }
    

    Adding value labels on a matplotlib bar chart

    Firstly freq_series.plot returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax rather than fig to be more consistent with other code examples.

    You can get the list of the bars produced in the plot from the ax.patches member. Then you can use the technique demonstrated in this matplotlib gallery example to add the labels using the ax.text method.

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    # Bring some raw data.
    frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
    # In my original code I create a series and run on that, 
    # so for consistency I create a series from the list.
    freq_series = pd.Series.from_array(frequencies)
    
    x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
                121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
    
    # Plot the figure.
    plt.figure(figsize=(12, 8))
    ax = freq_series.plot(kind='bar')
    ax.set_title('Amount Frequency')
    ax.set_xlabel('Amount ($)')
    ax.set_ylabel('Frequency')
    ax.set_xticklabels(x_labels)
    
    rects = ax.patches
    
    # Make some labels.
    labels = ["label%d" % i for i in xrange(len(rects))]
    
    for rect, label in zip(rects, labels):
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
                ha='center', va='bottom')
    

    This produces a labeled plot that looks like:

    enter image description here

    mat-form-field must contain a MatFormFieldControl

    Quoting from the official documentation here:

    Error: mat-form-field must contain a MatFormFieldControl

    This error occurs when you have not added a form field control to your form field. If your form field contains a native <input> or <textarea> element, make sure you've added the matInput directive to it and have imported MatInputModule. Other components that can act as a form field control include <mat-select>, <mat-chip-list>, and any custom form field controls you've created.

    Learn more about creating a "custom form field control" here

    Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

    The solution for me was to run mvn with -X:

    $ mvn package -X
    

    Then look backwards through the output until you see the failure and then keep going until you see the last jar file that mvn tried to process:

    ...
    ... <<output ommitted>>
    ...
    [DEBUG] Processing JAR /Users/snowch/.m2/repository/org/eclipse/jetty/jetty-server/9.2.15.v20160210/jetty-server-9.2.15.v20160210.jar
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 3.607 s
    [INFO] Finished at: 2017-10-04T14:30:13+01:00
    [INFO] Final Memory: 23M/370M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:3.1.0:shade (default) on project kafka-connect-on-cloud-foundry: Error creating shaded jar: invalid LOC header (bad signature) -> [Help 1]
    org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:3.1.0:shade (default) on project kafka-connect-on-cloud-foundry: Error creating shaded jar: invalid LOC header (bad signature)
    

    Look at the last jar before it failed and remove that from the local repository, i.e.

    $ rm -rf /Users/snowch/.m2/repository/org/eclipse/jetty/jetty-server/9.2.15.v20160210/
    

    How to convert Seconds to HH:MM:SS using T-SQL

    You can try this

    set @duration= 112000
    SELECT 
       "Time" = cast (@duration/3600 as varchar(3)) +'H'
             + Case 
           when ((@duration%3600 )/60)<10 then
                     '0'+ cast ((@duration%3600 )/60)as varchar(3))
           else 
                   cast ((@duration/60) as varchar(3))
           End
    

    JQuery string contains check

    You can use javascript's indexOf function.

    _x000D_
    _x000D_
    var str1 = "ABCDEFGHIJKLMNOP";_x000D_
    var str2 = "DEFG";_x000D_
    if(str1.indexOf(str2) != -1){_x000D_
        console.log(str2 + " found");_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    Is there a NumPy function to return the first index of something in an array?

    There are lots of operations in NumPy that could perhaps be put together to accomplish this. This will return indices of elements equal to item:

    numpy.nonzero(array - item)
    

    You could then take the first elements of the lists to get a single element.

    How to dynamically add and remove form fields in Angular 2

    addAccordian(type, data) { console.log(type, data);

    let form = this.form;
    
    if (!form.controls[type]) {
      let ownerAccordian = new FormArray([]);
      const group = new FormGroup({});
      ownerAccordian.push(
        this.applicationService.createControlWithGroup(data, group)
      );
      form.controls[type] = ownerAccordian;
    } else {
      const group = new FormGroup({});
      (<FormArray>form.get(type)).push(
        this.applicationService.createControlWithGroup(data, group)
      );
    }
    console.log(this.form);
    

    }

    Get rid of "The value for annotation attribute must be a constant expression" message

    The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

    See also here: How to supply value to an annotation from a Constant java

    It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

    Explicit vs implicit SQL joins

    Performance wise, it should not make any difference. The explicit join syntax seems cleaner to me as it clearly defines relationships between tables in the from clause and does not clutter up the where clause.

    jQuery Datepicker onchange event issue

    $('#inputfield').change(function() { 
        dosomething();
    });
    

    Re-ordering columns in pandas dataframe based on column name

    Don't forget to add "inplace=True" to Wes' answer or set the result to a new DataFrame.

    df.sort_index(axis=1, inplace=True)
    

    $.ajax - dataType

    • contentType is the HTTP header sent to the server, specifying a particular format.
      Example: I'm sending JSON or XML
    • dataType is you telling jQuery what kind of response to expect.
      Expecting JSON, or XML, or HTML, etc. The default is for jQuery to try and figure it out.

    The $.ajax() documentation has full descriptions of these as well.


    In your particular case, the first is asking for the response to be in UTF-8, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.

    So the first would be:

    success: function(data) {
      // get data, e.g. data.title;
    }
    

    The second:

    success: function(data) {
      alert("Here's lots of data, just a string: " + data);
    }
    

    Safest way to run BAT file from Powershell script

    cmd.exe /c '\my-app\my-file.bat'
    

    Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

    This happened to me when I imported a Java 1.8 project from Eclipse Luna into Eclipse Kepler.

    1. Right click on project > Build path > configure build path...
    2. Select the Libraries tab, you should see the Java 1.8 jre with an error
    3. Select the java 1.8 jre and click the Remove button
    4. Add Library... > JRE System Library > Next > workspace default > Finish
    5. Click OK to close the properties window
    6. Go to the project menu > Clean... > OK

    Et voilà, that worked for me.

    How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

    If you want to ignore the certificate all together then take a look at the answer here: Ignore self-signed ssl cert using Jersey Client

    Although this will make your app vulnerable to man-in-the-middle attacks.

    Or, try adding the cert to your java store as a trusted cert. This site may be helpful. http://blog.icodejava.com/tag/get-public-key-of-ssl-certificate-in-java/

    Here's another thread showing how to add a cert to your store. Java SSL connect, add server cert to keystore programmatically

    The key is:

    KeyStore.Entry newEntry = new KeyStore.TrustedCertificateEntry(someCert);
    ks.setEntry("someAlias", newEntry, null);
    

    PuTTY Connection Manager download?

    PuTTY Session Manager is a tool that allows system administrators to organise their PuTTY sessions into folders and assign hotkeys to favourite sessions. Multiple sessions can be launched with one click. Requires MS Windows and the .NET 2.0 Runtime.

    http://sourceforge.net/projects/puttysm/

    How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

    Add these 2 lines

    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 0
    

    So you have:

       // Do any additional setup after loading the view, typically from a nib.
            let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
            layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
            layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
            layout.minimumInteritemSpacing = 0
            layout.minimumLineSpacing = 0
            collectionView!.collectionViewLayout = layout
    

    That will remove all the spaces and give you a grid layout:

    enter image description here

    If you want the first column to have a width equal to the screen width then add the following function:

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        if indexPath.row == 0
        {
            return CGSize(width: screenWidth, height: screenWidth/3)
        }
        return CGSize(width: screenWidth/3, height: screenWidth/3);
    
    }
    

    Grid layout will now look like (I've also added a blue background to first cell): enter image description here

    nvm is not compatible with the npm config "prefix" option:

    Just resolved the issue. I symlinked $HOME/.nvm to $DEV_ZONE/env/node/nvm directory. I was facing same issue. I replaced NVM_DIR in $HOME/.zshrc as follows

    export NVM_DIR="$DEV_ZONE/env/node/nvm"
    

    BTW, please install NVM using curl or wget command not by using brew. For more please check the comment in this issue on Github: 855#issuecomment-146115434

    How do I create a foreign key in SQL Server?

    Necromancing.
    Actually, doing this correctly is a little bit trickier.

    You first need to check if the primary-key exists for the column you want to set your foreign key to reference to.

    In this example, a foreign key on table T_ZO_SYS_Language_Forms is created, referencing dbo.T_SYS_Language_Forms.LANG_UID

    -- First, chech if the table exists...
    IF 0 < (
        SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
        WHERE TABLE_TYPE = 'BASE TABLE'
        AND TABLE_SCHEMA = 'dbo'
        AND TABLE_NAME = 'T_SYS_Language_Forms'
    )
    BEGIN
        -- Check for NULL values in the primary-key column
        IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
        BEGIN
            ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 
    
            -- No, don't drop, FK references might already exist...
            -- Drop PK if exists 
            -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
            --DECLARE @pkDropCommand nvarchar(1000) 
            --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
            --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
            --AND TABLE_SCHEMA = 'dbo' 
            --AND TABLE_NAME = 'T_SYS_Language_Forms' 
            ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            --))
            ---- PRINT @pkDropCommand 
            --EXECUTE(@pkDropCommand) 
    
            -- Instead do
            -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';
    
    
            -- Check if they keys are unique (it is very possible they might not be) 
            IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
            BEGIN
    
                -- If no Primary key for this table
                IF 0 =  
                (
                    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                    WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                    AND TABLE_SCHEMA = 'dbo' 
                    AND TABLE_NAME = 'T_SYS_Language_Forms' 
                    -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
                )
                    ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
                ;
    
                -- Adding foreign key
                IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                    ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
            END -- End uniqueness check
            ELSE
                PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
        END -- End NULL check
        ELSE
            PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
    END 
    

    How can I clear the Scanner buffer in Java?

    Other people have suggested using in.nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.

    You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.

    in = new Scanner(System.in);

    If you do this, don't call in.close() first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt(); System.in probably shouldn't be closed during your program.

    (The above approach is specific to System.in. It might not be appropriate for other input streams.)

    If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.

    HttpContext.Current.Request.Url.Host what it returns?

    Yes, as long as the url you type into the browser www.someshopping.com and you aren't using url rewriting then

    string currentURL = HttpContext.Current.Request.Url.Host;
    

    will return www.someshopping.com

    Note the difference between a local debugging environment and a production environment

    C# using Sendkey function to send a key to another application

    If notepad is already started, you should write:

    // import the function in your class
    [DllImport ("User32.dll")]
    static extern int SetForegroundWindow(IntPtr point);
    
    //...
    
    Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
    if (p != null)
    {
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
    }
    

    GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

    If you want to start notepad and send the key, you should write:

    Process p = Process.Start("notepad.exe");
    p.WaitForInputIdle();
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
    

    The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

    How to insert a data table into SQL Server database table?

    From my understanding of the question,this can use a fairly straight forward solution.Anyway below is the method i propose ,this method takes in a data table and then using SQL statements to insert into a table in the database.Please mind that my solution is using MySQLConnection and MySqlCommand replace it with SqlConnection and SqlCommand.

    public void InsertTableIntoDB_CreditLimitSimple(System.Data.DataTable tblFormat)
        {
            for (int i = 0; i < tblFormat.Rows.Count; i++)
            {
    
                String InsertQuery = string.Empty;
    
                InsertQuery = "INSERT INTO customercredit " +
                              "(ACCOUNT_CODE,NAME,CURRENCY,CREDIT_LIMIT) " +
                              "VALUES ('" + tblFormat.Rows[i]["AccountCode"].ToString() + "','" + tblFormat.Rows[i]["Name"].ToString() + "','" + tblFormat.Rows[i]["Currency"].ToString() + "','" + tblFormat.Rows[i]["CreditLimit"].ToString() + "')";
    
    
    
                using (MySqlConnection destinationConnection = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
                using (var dbcm = new MySqlCommand(InsertQuery, destinationConnection))
                {
                    destinationConnection.Open();
                    dbcm.ExecuteNonQuery();
                }
            }
        }//CreditLimit
    

    Add x and y labels to a pandas plot

    It is possible to set both labels together with axis.set function. Look for the example:

    import pandas as pd
    import matplotlib.pyplot as plt
    values = [[1,2], [2,5]]
    df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])
    ax = df2.plot(lw=2,colormap='jet',marker='.',markersize=10,title='Video streaming dropout by category')
    # set labels for both axes
    ax.set(xlabel='x axis', ylabel='y axis')
    plt.show()
    

    enter image description here

    Node.js Port 3000 already in use but it actually isn't?

    check for any process running on the same port by entering the command:

    sudo ps -ef
    

    You can find the process running on the respective node port, then kill the node by

    kill -9 <node id>
    

    If the problem still remains then just kill all the node

    killall node
    

    How can I convert an image into Base64 string using JavaScript?

    Try this code:

    For a file upload change event, call this function:

    $("#fileproof").on('change', function () {
        readImage($(this)).done(function (base64Data) { $('#<%=hfimgbs64.ClientID%>').val(base64Data); });
    });
    
    function readImage(inputElement) {
        var deferred = $.Deferred();
    
        var files = inputElement.get(0).files;
    
        if (files && files[0]) {
            var fr = new FileReader();
            fr.onload = function (e) {
                deferred.resolve(e.target.result);
            };
            fr.readAsDataURL(files[0]);
        } else {
            deferred.resolve(undefined);
        }
    
        return deferred.promise();
    }
    

    Store Base64 data in hidden filed to use.

    How can I wait In Node.js (JavaScript)? l need to pause for a period of time

    Since, javascript engine (v8) runs code based on sequence of events in event-queue, There is no strict that javascript exactly trigger the execution at after specified time. That is, when you set some seconds to execute the code later, triggering code is purely base on sequence in event queue. So triggering execution of code may take more than specified time.

    So Node.js follows,

    process.nextTick()
    

    to run the code later instead setTimeout(). For example,

    process.nextTick(function(){
        console.log("This will be printed later");
    });
    

    How can I get the iOS 7 default blue color programmatically?

    This extension gives you native system blue color.

    extension UIColor {
    
        static var systemBlue: UIColor {
            return UIButton(type: .system).tintColor
        }
    
    }
    

    UPDATE

    Please forget what I wrote above, just figured out - there're native extension with predefined system colors we've been looking for, including system blue:

    // System colors
    
    extension UIColor {
    
    
        /* Some colors that are used by system elements and applications.
         * These return named colors whose values may vary between different contexts and releases.
         * Do not make assumptions about the color spaces or actual colors used.
         */
    
        ... 
    
        @available(iOS 7.0, *)
        open class var systemBlue: UIColor { get }
        ... 
    }
    

    You can use it directly:

    myView.tintColor = .systemBlue
    

    Need a row count after SELECT statement: what's the optimal SQL approach?

    If you're using SQL Server, after your query you can select the @@RowCount function (or if your result set might have more than 2 billion rows use the RowCount_Big() function). This will return the number of rows selected by the previous statement or number of rows affected by an insert/update/delete statement.

    SELECT my_table.my_col
      FROM my_table
     WHERE my_table.foo = 'bar'
    
    SELECT @@Rowcount
    

    Or if you want to row count included in the result sent similar to Approach #2, you can use the the OVER clause.

    SELECT my_table.my_col,
        count(*) OVER(PARTITION BY my_table.foo) AS 'Count'
      FROM my_table
     WHERE my_table.foo = 'bar'
    

    Using the OVER clause will have much better performance than using a subquery to get the row count. Using the @@RowCount will have the best performance because the there won't be any query cost for the select @@RowCount statement

    Update in response to comment: The example I gave would give the # of rows in partition - defined in this case by "PARTITION BY my_table.foo". The value of the column in each row is the # of rows with the same value of my_table.foo. Since your example query had the clause "WHERE my_table.foo = 'bar'", all rows in the resultset will have the same value of my_table.foo and therefore the value in the column will be the same for all rows and equal (in this case) this the # of rows in the query.

    Here is a better/simpler example of how to include a column in each row that is the total # of rows in the resultset. Simply remove the optional Partition By clause.

    SELECT my_table.my_col, count(*) OVER() AS 'Count'
      FROM my_table
     WHERE my_table.foo = 'bar'
    

    What's the best UML diagramming tool?

    If you're looking to get out the door and working on UML without having to learn a complex new tool I would check out Violet UML. I've used it to some pretty great success in the past.

    How to change a TextView's style at runtime

    See doco for setText() in TextView http://developer.android.com/reference/android/widget/TextView.html

    To style your strings, attach android.text.style.* objects to a SpannableString, or see the Available Resource Types documentation for an example of setting formatted text in the XML resource file.

    javascript create array from for loop

    even shorter if you can lose the yearStart value:

    var yearStart = 2000;
    var yearEnd = 2040;
    
    var arr = [];
    
    while(yearStart < yearEnd+1){
      arr.push(yearStart++);
    }
    

    UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

    let yearStart = 2000;
    let yearEnd = 2040;
    let years = Array(yearEnd-yearStart+1)
        .fill()
        .map(() => yearStart++);
    

    Why is Visual Studio 2013 very slow?

    I have the same problem, but it just gets slow when trying to stop debugging in Visual Studio 2013, and I try this:

    • Close Visual Studio, then
    • Find the work project folder
    • Delete .suo file
    • Delete /obj folder
    • Open Visual Studio
    • Rebuild

    How to reload/refresh jQuery dataTable?

    Use this code ,when you want to refresh your datatable:

     $("#my-button").click(function() {
        $('#my-datatable').DataTable().clear().draw();
     });
    

    jQuery ajax call to REST service

    From the use of 8080 I'm assuming you are using a tomcat servlet container to serve your rest api. If this is the case you can also consider to have your webserver proxy the requests to the servlet container.

    With apache you would typically use mod_jk (although there are other alternatives) to serve the api trough the web server behind port 80 instead of 8080 which would solve the cross domain issue.

    This is common practice, have the 'static' content in the webserver and dynamic content in the container, but both served from behind the same domain.

    The url for the rest api would be http://localhost/restws/json/product/get

    Here a description on how to use mod_jk to connect apache to tomcat: http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html

    How to list the contents of a package using YUM?

    $ yum install -y yum-utils
    
    $ repoquery -l packagename
    

    how to find host name from IP with out login to the host

    Use nslookup

    nslookup 208.77.188.166 
    ...
    Non-authoritative answer:
    166.188.77.208.in-addr.arpa     name = www.example.com.
    

    How to disable scrolling the document body?

    Answer : document.body.scroll = 'no';

    Converting NSString to NSDate (and back again)

    UPDATE 2019 (Swift 4):

    Made a Date extension for that. It uses NSDataDetector instead of NSDateFormatter.

    // Just throw at it without any format.
    var date: Date? = Date.FromString("02-14-2019 17:05:05")
    

    Pretty enjoyable, it even recognizes things like "Tomorrow at 5".

    XCTAssertEqual(Date.FromString("2019-02-14"),                    Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("2019.02.14"),                    Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("2019/02/14"),                    Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("2019 Feb 14"),                   Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("2019 Feb 14th"),                 Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("20190214"),                      Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("02-14-2019"),                    Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("02.14.2019 5:00 PM"),            Date.FromCalendar(2019, 2, 14, 17))
    XCTAssertEqual(Date.FromString("02/14/2019 17:00"),              Date.FromCalendar(2019, 2, 14, 17))
    XCTAssertEqual(Date.FromString("14 February 2019 at 5 hour"),    Date.FromCalendar(2019, 2, 14, 17))
    XCTAssertEqual(Date.FromString("02-14-2019 17:05:05"),           Date.FromCalendar(2019, 2, 14, 17, 05, 05))
    XCTAssertEqual(Date.FromString("17:05, 14 February 2019 (UTC)"), Date.FromCalendar(2019, 2, 14, 17, 05))
    XCTAssertEqual(Date.FromString("02-14-2019 17:05:05 GMT"),       Date.FromCalendar(2019, 2, 14, 17, 05, 05))
    XCTAssertEqual(Date.FromString("02-13-2019 Tomorrow"),           Date.FromCalendar(2019, 2, 14))
    XCTAssertEqual(Date.FromString("2019 Feb 14th Tomorrow at 5"),   Date.FromCalendar(2019, 2, 14, 17))
    

    Goes like:

    extension Date
    {
    
    
        public static func FromString(_ dateString: String) -> Date?
        {
            // Date detector.
            let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
    
            // Enumerate matches.
            var matchedDate: Date?
            var matchedTimeZone: TimeZone?
            detector.enumerateMatches(
                in: dateString,
                options: [],
                range: NSRange(location: 0, length: dateString.utf16.count),
                using:
                {
                    (eachResult, _, _) in
    
                    // Lookup matches.
                    matchedDate = eachResult?.date
                    matchedTimeZone = eachResult?.timeZone
    
                    // Convert to GMT (!) if no timezone detected.
                    if matchedTimeZone == nil, let detectedDate = matchedDate
                    { matchedDate = Calendar.current.date(byAdding: .second, value: TimeZone.current.secondsFromGMT(), to: detectedDate)! }
            })
    
            // Result.
            return matchedDate
        }
    }
    

    UPDATE 2014:

    Made an NSString extension for that.

    // Simple as this.   
    date = dateString.dateValue;
    

    Thanks to NSDataDetector, it recognizes a whole lot of format.

    '2014-01-16' dateValue is <2014-01-16 11:00:00 +0000>
    '2014.01.16' dateValue is <2014-01-16 11:00:00 +0000>
    '2014/01/16' dateValue is <2014-01-16 11:00:00 +0000>
    '2014 Jan 16' dateValue is <2014-01-16 11:00:00 +0000>
    '2014 Jan 16th' dateValue is <2014-01-16 11:00:00 +0000>
    '20140116' dateValue is <2014-01-16 11:00:00 +0000>
    '01-16-2014' dateValue is <2014-01-16 11:00:00 +0000>
    '01.16.2014' dateValue is <2014-01-16 11:00:00 +0000>
    '01/16/2014' dateValue is <2014-01-16 11:00:00 +0000>
    '16 January 2014' dateValue is <2014-01-16 11:00:00 +0000>
    '01-16-2014 17:05:05' dateValue is <2014-01-16 16:05:05 +0000>
    '01-16-2014 T 17:05:05 UTC' dateValue is <2014-01-16 17:05:05 +0000>
    '17:05, 1 January 2014 (UTC)' dateValue is <2014-01-01 16:05:00 +0000>
    

    Part of eppz!kit, grab the category NSString+EPPZKit.h from GitHub.


    ORIGINAL ANSWER 2013:

    Whether you're not sure (or don't care) about the date format contained in the string, use NSDataDetector for parsing date.

    //Role players.
    NSString *dateString = @"Wed, 03 Jul 2013 02:16:02 -0700";
    __block NSDate *detectedDate;
    
    //Detect.
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:nil];
    [detector enumerateMatchesInString:dateString
                               options:kNilOptions
                                 range:NSMakeRange(0, [dateString length])
                            usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
    { detectedDate = result.date; }];
    

    Are there bookmarks in Visual Studio Code?

    Under the general heading of 'editors always forget to document getting out…' to toggle go to another line and press the combination ctrl+shift+'N' to erase the current bookmark do the same on marked line…

    How to implement HorizontalScrollView like Gallery?

    I implemented something similar with Horizontal Variable ListView The only drawback is, it works only with Android 2.3 and later.

    Using this library is as simple as implementing a ListView with a corresponding Adapter. The library also provides an example

    C++/CLI Converting from System::String^ to std::string

    Check out System::Runtime::InteropServices::Marshal::StringToCoTaskMemUni() and its friends.

    Sorry can't post code now; I don't have VS on this machine to check it compiles before posting.

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

    1. Add Internet permission in Androidmanifest.xml file

    uses-permission android:name="android.permission.INTERNET

    1. Open cmd in windows
    2. type "ipconfig" then press enter
    3. find IPv4 Address. . . . . . . . . . . : 192.168.X.X
    4. use this URL "http://192.168.X.X:your_virtual_server_port/your_service.php"

    Unable to install Android Studio in Ubuntu

    None of these options worked for me on Ubuntu 12.10 (yeah, I need to upgrade). However, I found an easy solution. Download the source from here: https://github.com/miracle2k/android-platform_sdk/blob/master/emulator/mksdcard/mksdcard.c. Then simply compile with "gcc mksdcard.c -o mksdcard". Backup mksdcard in the SDK tools subfolder and replace with the newly compiled one. Android Studio will now be happy with your SDK.

    getResources().getColor() is deprecated

    You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).

    ContextCompat.getColor(context, R.color.my_color)
    

    As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.

    You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:

    compile 'com.android.support:support-v4:23.0.1'
    

    Passing multiple values for a single parameter in Reporting Services

    If you want to pass multiple values to RS via a query string all you need to do is repeat the report parameter for each value.

    For example; I have a RS column called COLS and this column expects one or more values.

    &rp:COLS=1&rp:COLS=1&rp:COLS=5 etc..
    

    What is SELF JOIN and when would you use it?

    A self join is simply when you join a table with itself. There is no SELF JOIN keyword, you just write an ordinary join where both tables involved in the join are the same table. One thing to notice is that when you are self joining it is necessary to use an alias for the table otherwise the table name would be ambiguous.

    It is useful when you want to correlate pairs of rows from the same table, for example a parent - child relationship. The following query returns the names of all immediate subcategories of the category 'Kitchen'.

    SELECT T2.name
    FROM category T1
    JOIN category T2
    ON T2.parent = T1.id
    WHERE T1.name = 'Kitchen'
    

    How to replace all double quotes to single quotes using jquery?

    You can also use replaceAll(search, replaceWith) [MDN].

    Then, make sure you have a string by wrapping one type of quotes by a different type:

     'a "b" c'.replaceAll('"', "'")
     // result: "a 'b' c"
        
     'a "b" c'.replaceAll(`"`, `'`)
     // result: "a 'b' c"
    
     // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
     'a "b" c'.replaceAll(/\"/g, "'")
     // result: "a 'b' c"
    

    Important(!) if you choose regex:

    when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

    How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

    If it is going to be a web based application, you can also use the ServletContextListener interface.

    public class SLF4JBridgeListener implements ServletContextListener {
    
       @Autowired 
       ThreadPoolTaskExecutor executor;
    
       @Autowired 
       ThreadPoolTaskScheduler scheduler;
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
    
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
             scheduler.shutdown();
             executor.shutdown();     
    
        }
    

    }

    Jenkins not executing jobs (pending - waiting for next executor)

    In my case it is similar to @Michael Easter: I got a problem in a job due to lack of disk space. I cleared some space, restarted Jenkins but still the problem persisted.

    The solution was to go to Jenkins -> Manage Jenkins -> Manage Nodes and just Click on the button to update the status.

    How can I post data as form data instead of a request payload?

    You can try with below solution

    $http({
            method: 'POST',
            url: url-post,
            data: data-post-object-json,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            transformRequest: function(obj) {
                var str = [];
                for (var key in obj) {
                    if (obj[key] instanceof Array) {
                        for(var idx in obj[key]){
                            var subObj = obj[key][idx];
                            for(var subKey in subObj){
                                str.push(encodeURIComponent(key) + "[" + idx + "][" + encodeURIComponent(subKey) + "]=" + encodeURIComponent(subObj[subKey]));
                            }
                        }
                    }
                    else {
                        str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
                    }
                }
                return str.join("&");
            }
        }).success(function(response) {
              /* Do something */
            });
    

    AngularJs ReferenceError: angular is not defined

    Always make sure that js file (angular.min.js) is referenced first in the HTML file. For example:

    ----------------- This reference will THROW error -------------------------

    < script src="otherXYZ.js"></script>
    < script src="angular.min.js"></script>
    

    ----------------- This reference will WORK as expected -------------------

    < script src="angular.min.js"></script>
    < script src="otherXYZ.js"></script>
    

    Remove last character of a StringBuilder?

    With Java-8 you can use static method of String class,

    String#join(CharSequence delimiter,Iterable<? extends CharSequence> elements).


    public class Test {
    
        public static void main(String[] args) {
    
            List<String> names = new ArrayList<>();
            names.add("James");
            names.add("Harry");
            names.add("Roy");
            System.out.println(String.join(",", names));
        }
    }
    

    OUTPUT

    James,Harry,Roy
    

    With android studio no jvm found, JAVA_HOME has been set

    For me the case was completely different. I had created a studio64.exe.vmoptions file in C:\Users\YourUserName\.AndroidStudio3.4\config. In that folder, I had a typo of extra spaces. Due to that I was getting the same error.

    I replaced the studio64.exe.vmoptions with the following code.

    # custom Android Studio VM options, see https://developer.android.com/studio/intro/studio-config.html
    
    -server
    -Xms1G
    -Xmx8G
    # I have 8GB RAM so it is 8G. Replace it with your RAM size.
    -XX:MaxPermSize=1G
    -XX:ReservedCodeCacheSize=512m
    -XX:+UseCompressedOops
    -XX:+UseConcMarkSweepGC
    -XX:SoftRefLRUPolicyMSPerMB=50
    -da
    -Djna.nosys=true
    -Djna.boot.library.path=
    
    -Djna.debug_load=true
    -Djna.debug_load.jna=true
    -Dsun.io.useCanonCaches=false
    -Djava.net.preferIPv4Stack=true
    -XX:+HeapDumpOnOutOfMemoryError
    -Didea.paths.selector=AndroidStudio2.1
    -Didea.platform.prefix=AndroidStudio
    

    Trigger insert old values- values that was updated

    Here's an example update trigger:

    create table Employees (id int identity, Name varchar(50), Password varchar(50))
    create table Log (id int identity, EmployeeId int, LogDate datetime, 
        OldName varchar(50))
    go
    create trigger Employees_Trigger_Update on Employees
    after update
    as
    insert into Log (EmployeeId, LogDate, OldName) 
    select id, getdate(), name
    from deleted
    go
    insert into Employees (Name, Password) values ('Zaphoid', '6')
    insert into Employees (Name, Password) values ('Beeblebox', '7')
    update Employees set Name = 'Ford' where id = 1
    select * from Log
    

    This will print:

    id   EmployeeId   LogDate                   OldName
    1    1            2010-07-05 20:11:54.127   Zaphoid
    

    Magento addFieldToFilter: Two fields, match as OR, not AND

    To filter by multiple attributes use something like:

    //for AND
        $collection = Mage::getModel('sales/order')->getCollection()
        ->addAttributeToSelect('*')
        ->addFieldToFilter('my_field1', 'my_value1')
        ->addFieldToFilter('my_field2', 'my_value2');
    
        echo $collection->getSelect()->__toString();
    
    //for OR - please note 'attribute' is the key name and must remain the same, only replace //the value (my_field1, my_field2) with your attribute name
    
    
        $collection = Mage::getModel('sales/order')->getCollection()
            ->addAttributeToSelect('*')
            ->addFieldToFilter(
                array(
                    array('attribute'=>'my_field1','eq'=>'my_value1'),
                    array('attribute'=>'my_field2', 'eq'=>'my_value2')
                )
            );
    

    For more information check: http://docs.magentocommerce.com/Varien/Varien_Data/Varien_Data_Collection_Db.html#_getConditionSql

    How to find the kafka version in linux

    go to kafka/libs folder we can see multiple jars search for something similar kafka_2.11-0.10.1.1.jar.asc in this case the kafka version is 0.10.1.1

    How do I create a file and write to it?

    It's worth a try for Java 7+:

     Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());
    

    It looks promising...

    How can I get the current time in C#?

    DateTime.Now.ToShortTimeString().ToString()
    

    This Will give you DateTime as 10:50PM

    The Definitive C Book Guide and List

    Beginner

    Introductory, no previous programming experience

    • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

      * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

    • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

    Introductory, with previous programming experience

    • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

    • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

    Best practices

    • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

    • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

    • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


    Intermediate

    • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

    • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

    • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

    • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

    • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

    • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

    • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

    • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

    • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

    • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


    Advanced

    • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

    • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

    • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

    • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


    Reference Style - All Levels

    • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

    • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

    • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

    C++11/14/17/… References:

    • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

    • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

    • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

    • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

    • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

    • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


    Classics / Older

    Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

    • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

    • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

    • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

    • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

    • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

    • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

    • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

    • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

    "replace" function examples

    Here's an example where I found the replace( ) function helpful for giving me insight. The problem required a long integer vector be changed into a character vector and with its integers replaced by given character values.

    ## figuring out replace( )
    (test <- c(rep(1,3),rep(2,2),rep(3,1)))
    

    which looks like

    [1] 1 1 1 2 2 3
    

    and I want to replace every 1 with an A and 2 with a B and 3 with a C

    letts <- c("A","B","C")
    

    so in my own secret little "dirty-verse" I used a loop

    for(i in 1:3)
    {test <- replace(test,test==i,letts[i])}
    

    which did what I wanted

    test
    [1] "A" "A" "A" "B" "B" "C"
    

    In the first sentence I purposefully left out that the real objective was to make the big vector of integers a factor vector and assign the integer values (levels) some names (labels).

    So another way of doing the replace( ) application here would be

    (test <- factor(test,labels=letts))
    [1] A A A B B C
    Levels: A B C
    

    Mongoose: Get full list of users

    To make function to wait for list to be fetched.

    getArrayOfData() {
        return DataModel.find({}).then(function (storedDataArray) {
            return storedDataArray;
        }).catch(function(err){
            if (err) {
                throw new Error(err.message);
            }
        });
    }
    

    Limit to 2 decimal places with a simple pipe

    Well now will be different after angular 5:

    {{ number | currency :'GBP':'symbol':'1.2-2' }}
    

    How to make a <button> in Bootstrap look like a normal link in nav-tabs?

    In bootstrap 3, this works well for me:

    .btn-link.btn-anchor {
        outline: none !important;
        padding: 0;
        border: 0;
        vertical-align: baseline;
    }
    

    Used like:

    <button type="button" class="btn-link btn-anchor">My Button</button>
    

    Demo

    Accessing the last entry in a Map

    HashMap doesn't have "the last position", as it is not sorted.

    You may use other Map which implements java.util.SortedMap, most popular one is TreeMap.

    Converting .NET DateTime to JSON

    If you're having trouble getting to the time information, you can try something like this:

        d.date = d.date.replace('/Date(', '');
        d.date = d.date.replace(')/', '');  
        var expDate = new Date(parseInt(d.date));
    

    How do I iterate over the words of a string?

    Here's a simple solution that uses only the standard regex library

    #include <regex>
    #include <string>
    #include <vector>
    
    std::vector<string> Tokenize( const string str, const std::regex regex )
    {
        using namespace std;
    
        std::vector<string> result;
    
        sregex_token_iterator it( str.begin(), str.end(), regex, -1 );
        sregex_token_iterator reg_end;
    
        for ( ; it != reg_end; ++it ) {
            if ( !it->str().empty() ) //token could be empty:check
                result.emplace_back( it->str() );
        }
    
        return result;
    }
    

    The regex argument allows checking for multiple arguments (spaces, commas, etc.)

    I usually only check to split on spaces and commas, so I also have this default function:

    std::vector<string> TokenizeDefault( const string str )
    {
        using namespace std;
    
        regex re( "[\\s,]+" );
    
        return Tokenize( str, re );
    }
    

    The "[\\s,]+" checks for spaces (\\s) and commas (,).

    Note, if you want to split wstring instead of string,

    • change all std::regex to std::wregex
    • change all sregex_token_iterator to wsregex_token_iterator

    Note, you might also want to take the string argument by reference, depending on your compiler.

    Disable button in WPF?

    In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text that is bound to your TextBox and you would have an ICommand property Apply (or similar) that is bound to the button:

    <Button Command="Apply">Apply</Button>
    

    The ICommand interface has a Method CanExecute that is where you return true if (!string.IsNullOrWhiteSpace(this.Text). The rest is done by WPF for you (enabling/disabling, executing the actual command on click).

    The linked article explains it in detail.

    Check if MySQL table exists or not

    MySQL way:

    SHOW TABLES LIKE 'pattern';

    There's also a deprecated PHP function for listing all db tables, take a look at http://php.net/manual/en/function.mysql-list-tables.php

    Checkout that link, there are plenty of useful insight on the comments over there.

    What is the use of "assert"?

    Python assert is basically a debugging aid which test condition for internal self-check of your code. Assert makes debugging really easy when your code gets into impossible edge cases. Assert check those impossible cases.

    Let's say there is a function to calculate price of item after discount :

    def calculate_discount(price, discount):
        discounted_price = price - [discount*price]
        assert 0 <= discounted_price <= price
        return discounted_price
    

    here, discounted_price can never be less than 0 and greater than actual price. So, in case the above condition is violated assert raises an Assertion Error, which helps the developer to identify that something impossible had happened.

    Hope it helps :)

    .NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

    There are subtle and not-so-subtle differences between generic and non-generic collections. They merely use different underlying data structures. For example, Hashtable guarantees one-writer-many-readers without sync. Dictionary does not.

    Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

    If the URL works fine in the web browser on the same machine, it might be that the Java code isn't using the HTTP proxy the browser is using for connecting to the URL.

    How to get the last element of a slice?

    For just reading the last element of a slice:

    sl[len(sl)-1]
    

    For removing it:

    sl = sl[:len(sl)-1]
    

    See this page about slice tricks

    .htaccess 301 redirect of single page

    redirect 301 /contact.php /contact-us.php
    

    There is no point using the redirectmatch rule and then have to write your links so they are exact match. If you don't include you don't have to exclude! Just use redirect without match and then use links normally

    ICommand MVVM implementation

    I've just created a little example showing how to implement commands in convention over configuration style. However it requires Reflection.Emit() to be available. The supporting code may seem a little weird but once written it can be used many times.

    Teaser:

    public class SampleViewModel: BaseViewModelStub
    {
        public string Name { get; set; }
    
        [UiCommand]
        public void HelloWorld()
        {
            MessageBox.Show("Hello World!");
        }
    
        [UiCommand]
        public void Print()
        {
            MessageBox.Show(String.Concat("Hello, ", Name, "!"), "SampleViewModel");
        }
    
        public bool CanPrint()
        {
            return !String.IsNullOrEmpty(Name);
        }
    }
    

    }

    UPDATE: now there seem to exist some libraries like http://www.codeproject.com/Articles/101881/Executing-Command-Logic-in-a-View-Model that solve the problem of ICommand boilerplate code.

    javascript date + 7 days

    The simple way to get a date x days in the future is to increment the date:

    function addDays(dateObj, numDays) {
      return dateObj.setDate(dateObj.getDate() + numDays);
    }
    

    Note that this modifies the supplied date object, e.g.

    function addDays(dateObj, numDays) {
       dateObj.setDate(dateObj.getDate() + numDays);
       return dateObj;
    }
    
    var now = new Date();
    var tomorrow = addDays(new Date(), 1);
    var nextWeek = addDays(new Date(), 7);
    
    alert(
        'Today: ' + now +
        '\nTomorrow: ' + tomorrow +
        '\nNext week: ' + nextWeek
    );
    

    Copy folder recursively, excluding some folders

    Quick Start

    Run:

    rsync -av --exclude='path1/in/source' --exclude='path2/in/source' [source]/ [destination]
    

    Notes

    • -avr will create a new directory named [destination].
    • source and source/ create different results:
      • source — copy the contents of source into destination.
      • source/ — copy the folder source into destination.
    • To exclude many files:
      • --exclude-from=FILEFILE is the name of a file containing other files or directories to exclude.
    • --exclude may also contain wildcards:
      • e.g. --exclude=*/.svn*

    Modified from: https://stackoverflow.com/a/2194500/749232


    Example

    Starting folder structure:

    .
    +-- destination
    +-- source
        +-- fileToCopy.rtf
        +-- fileToExclude.rtf
    

    Run:

    rsync -av --exclude='fileToCopy.rtf' source/ destination
    

    Ending folder structure:

    .
    +-- destination
    ¦   +-- fileToExclude.rtf
    +-- source
        +-- fileToCopy.rtf
        +-- fileToExclude.rtf
    

    Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

    As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

    Using an HTTP PROXY - Python

    Run batch file as a Windows service

    On Windows 2019 Server, you can run a Minecraft java server with these commands:

    sc create minecraft-server DisplayName= "minecraft-server" binpath= "cmd.exe /C C:\Users\Administrator\Desktop\rungui1151.lnk" type= own start= auto

    The .lnk file is a standard windows shortcut to a batch file.

    --- .bat file begins ---

    java -Xmx40960M -Xms40960M -d64 -jar minecraft_server.1.15.1.jar

    --- .bat file ends ---

    All this because:

    service does not know how to start in a folder,

    cmd.exe does not know how to start in a folder

    Starting the service will produce "timely manner" error, but the log file reveals the server is running.

    If you need to shut down the server, just go into task manager and find the server java in background processes and end it, or terminate the server from in the game using the /stop command, or for other programs/servers, use the methods relevant to the server.

    Facebook database design?

    It's not possible to retrieve data from RDBMS for user friends data for data which cross more than half a billion at a constant time so Facebook implemented this using a hash database (no SQL) and they opensourced the database called Cassandra.

    So every user has its own key and the friends details in a queue; to know how cassandra works look at this:

    http://prasath.posterous.com/cassandra-55

    Checking during array iteration, if the current element is the last element

    $myarray = array(
      'test1' => 'foo',
      'test2' => 'bar',
      'test3' => 'baz',
      'test4' => 'waldo'
    );
    
    $myarray2 = array(
    'foo',
    'bar',
    'baz',
    'waldo'
    );
    
    // Get the last array_key
    $last = array_pop(array_keys($myarray));
    foreach($myarray as $key => $value) {
      if($key != $last) {
        echo "$key -> $value\n";
      }
    }
    
    // Get the last array_key
    $last = array_pop(array_keys($myarray2));
    foreach($myarray2 as $key => $value) {
      if($key != $last) {
        echo "$key -> $value\n";
      }
    }
    

    Since array_pop works on the temporary array created by array_keys it doesn't modify the original array at all.

    $ php test.php
    test1 -> foo
    test2 -> bar
    test3 -> baz
    0 -> foo
    1 -> bar
    2 -> baz
    

    How can I set up an editor to work with Git on Windows?

    I needed to do both of the following to get Git to launch Notepad++ in Windows:

    • Add the following to .gitconfig:

      editor = 'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin
      
    • Modify the shortcut to launch the Git Bash shell to run as administrator, and then use that to launch the Git Bash shell. I was guessing that the context menu entry "Git Bash here" was not launching Notepad++ with the required permissions.

    After doing both of the above, it worked.

    Resizable table columns with jQuery

    So I started writing my own, just bare bones functionality for now, will be working on it next week... http://jsfiddle.net/ydTCZ/

    Error while installing json gem 'mkmf.rb can't find header files for ruby'

    I also encountered this problem because I install Ruby on Ubuntu via brightbox, and I thought ruby-dev is the trunk of ruby. So I did not install. Install ruby2.3-dev fixes it:

    sudo apt-get install ruby2.3-dev
    

    How to fetch JSON file in Angular 2

    In Angular 5

    you can just say

    this.http.get<Example>('assets/example.json')
    

    This will give you Observable<Example>

    What is the garbage collector in Java?

    The basic principles of garbage collection are to find data objects in a program that cannot be accessed in the future, and to reclaim the resources used by those objects. https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29

    Advantages

    1) Saves from bugs, which occur when a piece of memory is freed while there are still pointers to it, and one of those pointers is dereferenced. https://en.wikipedia.org/wiki/Dangling_pointer

    2) Double free bugs, which occur when the program tries to free a region of memory that has already been freed, and perhaps already been allocated again.

    3) Prevents from certain kinds of memory leaks, in which a program fails to free memory occupied by objects that have become unreachable, which can lead to memory exhaustion.

    Disadvantages

    1) Consuming additional resources, performance impacts, possible stalls in program execution, and incompatibility with manual resource management. Garbage collection consumes computing resources in deciding which memory to free, even though the programmer may have already known this information.

    2) The moment when the garbage is actually collected can be unpredictable, resulting in stalls (pauses to shift/free memory) scattered throughout a session. Unpredictable stalls can be unacceptable in real-time environments, in transaction processing, or in interactive programs.


    Oracle tutorial http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

    Garbage collection is the process identifying which objects are in use and which are not, and deleting the unused objects.

    In a programming languages like C, C++, allocating and freeing memory is a manual process.

    int * array = new int[size];
    processArray(array); //do some work.
    delete array; //Free memory
    

    The first step in the process is called marking. This is where the garbage collector identifies which pieces of memory are in use and which are not.

    Step 2a. Normal deletion removes unreferenced objects leaving referenced objects and pointers to free space.

    To improve performance, we want to delete unreferenced objects and also compact the remaining referenced objects. We want to keep referenced objects together, so it will be faster to allocate new memory.

    As stated earlier, having to mark and compact all the objects in a JVM is inefficient. As more and more objects are allocated, the list of objects grows and grows leading to longer and longer garbage collection time.

    Continue reading this tutorial, and you will know how GC takes this challenge.

    In short, there are three regions of the heap, YoungGeneration for short life objects, OldGeneration for long period objects, and PermanentGeneration for objects that live during the application life, for example, classes, libraries.

    how do I query sql for a latest record date for each user

    SELECT MAX(DATE) AS dates 
    FROM assignment  
    JOIN paper_submission_detail ON  assignment.PAPER_SUB_ID = 
         paper_submission_detail.PAPER_SUB_ID 
    

    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 "*"
    

    ClassNotFoundException: org.slf4j.LoggerFactory

    It needs "slf4j-simple-1.7.2.jar" to resolve the problem.

    I downloaded a zip file "slf4j-1.7.2.zip" from http://slf4j.org/download.html. I extracted the zip file and i got slf4j-simple-1.7.2.jar

    Uncaught TypeError: Cannot read property 'split' of undefined

    og_date = "2012-10-01";
    console.log(og_date); // => "2012-10-01"
    
    console.log(og_date.split('-')); // => [ '2012', '10', '01' ]
    

    og_date.value would only work if the date were stored as a property on the og_date object. Such as: var og_date = {}; og_date.value="2012-10-01"; In that case, your original console.log would work.

    Remove HTML tags from string including &nbsp in C#

    I took @Ravi Thapliyal's code and made a method: It is simple and might not clean everything, but so far it is doing what I need it to do.

    public static string ScrubHtml(string value) {
        var step1 = Regex.Replace(value, @"<[^>]+>|&nbsp;", "").Trim();
        var step2 = Regex.Replace(step1, @"\s{2,}", " ");
        return step2;
    }
    

    Disable double-tap "zoom" option in browser on touch devices

    You should set the css property touch-action to none as described in this other answer https://stackoverflow.com/a/42288386/1128216

    .disable-doubletap-to-zoom {
        touch-action: none;
    }
    

    javascript find and remove object in array based on key value

    Make sure you coerce the object id to an integer if you test for strict equality:

    var result = $.grep(data, function(e, i) { 
      return +e.id !== id;
    });
    

    Demo

    Read environment variables in Node.js

    If you want to see all the Enviroment Variables on execution time just write in some nodejs file like server.js:

    console.log(process.env);

    Where does Chrome store extensions?

    This link "Finding All Installed Browsers in Windows XP and Vista – beware 64bit!" may be useful for Windows as suggested by "How to find all the browsers installed on a machine".

    The installed web browsers are saved in this registry,

    HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet

    HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Clients\StartMenuInternet.

    The following untracked working tree files would be overwritten by merge, but I don't care

    Update - a better version

    This tool (https://github.com/mklepaczewski/git-clean-before-merge) will:

    • delete untracked files that are identical to their git pull equivalents,
    • revert changes to modified files who's modified version is identical to their git pull equivalents,
    • report modified/untracked files that differ from their git pull version,
    • the tool has the --pretend option that will not modify any files.

    Old version

    How this answer differ from other answers?

    The method presented here removes only files that would be overwritten by merge. If you have other untracked (possibly ignored) files in the directory this method won't remove them.

    The solution

    This snippet will extract all untracked files that would be overwritten by git pull and delete them.

    git pull 2>&1|grep -E '^\s'|cut -f2-|xargs -I {} rm -rf "{}"
    

    and then just do:

    git pull
    

    This is not git porcelain command so always double check what it would do with:

    git pull 2>&1|grep -E '^\s'|cut -f2-|xargs -I {} echo "{}"
    

    Explanation - because one liners are scary:

    Here's a breakdown of what it does:

    1. git pull 2>&1 - capture git pull output and redirect it all to stdout so we can easily capture it with grep.
    2. grep -E '^\s - the intent is to capture the list of the untracked files that would be overwritten by git pull. The filenames have a bunch of whitespace characters in front of them so we utilize it to get them.
    3. cut -f2- - remove whitespace from the beginning of each line captured in 2.
    4. xargs -I {} rm -rf "{}" - us xargs to iterate over all files, save their name in "{}" and call rm for each of them. We use -rf to force delete and remove untracked directories.

    It would be great to replace steps 1-3 with porcelain command, but I'm not aware of any equivalent.

    How to return a struct from a function in C++?

    You have a scope problem. Define the struct before the function, not inside it.

    position fixed is not working

    Double-check that you haven't enabled backface-visibility on any of the containing elements, as that will wreck position: fixed. For me, I was using a CSS3 animation library...

    Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

    First, open Device Manager by searching for it in the Windows search bar.

    Then, click ports and right click the port the Arduino is connected to. Then, go to Port settingsAdvanced. Next, select any port that is not in use and is not the port the Arduino is currently connected to. Then click OK and unplug + replug your Arduino. This works most of the time with any Arduino board.

    Python 3.1.1 string to hex

    In Python 3, all strings are unicode. Usually, if you encode an unicode object to a string, you use .encode('TEXT_ENCODING'), since hex is not a text encoding, you should use codecs.encode() to handle arbitrary codecs. For example:

    >>>> "hello".encode('hex')
    LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
    >>>> import codecs
    >>>> codecs.encode(b"hello", 'hex')
    b'68656c6c6f'
    

    Again, since "hello" is unicode, you need to indicate it as a byte string before encoding to hexadecimal. This may be more inline with what your original approach of using the encode method.

    The differences between binascii.hexlify and codecs.encode are as follow:

    • binascii.hexlify

      Hexadecimal representation of binary data.

      The return value is a bytes object.

      Type: builtin_function_or_method

    • codecs.encode

      encode(obj, [encoding[,errors]]) -> object

      Encodes obj using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a ValueError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle ValueErrors.

      Type: builtin_function_or_method

    Is there a way to SELECT and UPDATE rows at the same time?

    in SQL 2008 a new TSQL statement "MERGE" is introduced which performs insert, update, or delete operations on a target table based on the results of a join with a source table. You can synchronize two tables by inserting, updating, or deleting rows in one table based on differences found in the other table.

    http://blogs.msdn.com/ajaiman/archive/2008/06/25/tsql-merge-statement-sql-2008.aspx http://msdn.microsoft.com/en-us/library/bb510625.aspx

    Find Item in ObservableCollection without using a loop

    ObservableCollection is a list so if you don't know the element position you have to look at each element until you find the expected one.

    Possible optimization If your elements are sorted use a binary search to improve performances otherwise use a Dictionary as index.

    Practical uses of git reset --soft?

    One possible usage would be when you want to continue your work on a different machine. It would work like this:

    1. Checkout a new branch with a stash-like name,

      git checkout -b <branchname>_stash
      
    2. Push your stash branch up,

      git push -u origin <branchname>_stash
      
    3. Switch to your other machine.

    4. Pull down both your stash and existing branches,

      git checkout <branchname>_stash; git checkout <branchname>
      
    5. You should be on your existing branch now. Merge in the changes from the stash branch,

      git merge <branchname>_stash
      
    6. Soft reset your existing branch to 1 before your merge,

      git reset --soft HEAD^
      
    7. Remove your stash branch,

      git branch -d <branchname>_stash
      
    8. Also remove your stash branch from origin,

      git push origin :<branchname>_stash
      
    9. Continue working with your changes as if you had stashed them normally.

    I think, in the future, GitHub and co. should offer this "remote stash" functionality in fewer steps.

    How do you count the lines of code in a Visual Studio solution?

    You can use the Project Line Counter add-in in Visual Studio 2010. Normally it doesn't work with Visual Studio 2010, but it does with a helpful .reg file from here: http://www.onemanmmo.com/index.php?cmd=newsitem&comment=news.1.41.0

    How to create and write to a txt file using VBA

    Use FSO to create the file and write to it.

    Dim fso as Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim oFile as Object
    Set oFile = FSO.CreateTextFile(strPath)
    oFile.WriteLine "test" 
    oFile.Close
    Set fso = Nothing
    Set oFile = Nothing    
    

    See the documentation here:

    How to calculate mean, median, mode and range from a set of numbers

    As already pointed out by Nico Huysamen, finding multiple mode in Java 1.8 can be done alternatively as below.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.HashMap;
    import java.util.Map;
    
    public static void mode(List<Integer> numArr) {
        Map<Integer, Integer> freq = new HashMap<Integer, Integer>();;
        Map<Integer, List<Integer>> mode = new HashMap<Integer, List<Integer>>();
    
        int modeFreq = 1; //record the highest frequence
        for(int x=0; x<numArr.size(); x++) { //1st for loop to record mode
            Integer curr = numArr.get(x); //O(1)
            freq.merge(curr, 1, (a, b) -> a + b); //increment the frequency for existing element, O(1)
            int currFreq = freq.get(curr); //get frequency for current element, O(1)
    
            //lazy instantiate a list if no existing list, then
            //record mapping of frequency to element (frequency, element), overall O(1)
            mode.computeIfAbsent(currFreq, k -> new ArrayList<>()).add(curr);
    
            if(modeFreq < currFreq) modeFreq = currFreq; //update highest frequency
        }
        mode.get(modeFreq).forEach(x -> System.out.println("Mode = " + x)); //pretty print the result //another for loop to return result
    }
    

    Happy coding!

    What does the percentage sign mean in Python

    x % n == 0
    which means the x/n and the value of reminder will taken as a result and compare with zero....

    example: 4/5==0

    4/5 reminder is 4

    4==0 (False)

    delete image from folder PHP

    You can delete files in PHP using the unlink() function.

    unlink('path/to/file.jpg');
    

    How to iterate over the files of a certain directory, in Java?

    Here is an example that lists all the files on my desktop. you should change the path variable to your path.

    Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.

    public static void main(String[] args) {
        File path = new File("c:/documents and settings/Zachary/desktop");
    
        File [] files = path.listFiles();
        for (int i = 0; i < files.length; i++){
            if (files[i].isFile()){ //this line weeds out other directories/folders
                System.out.println(files[i]);
            }
        }
    }
    

    Where's the DateTime 'Z' format specifier?

    Round tripping dates through strings has always been a pain...but the docs to indicate that the 'o' specifier is the one to use for round tripping which captures the UTC state. When parsed the result will usually have Kind == Utc if the original was UTC. I've found that the best thing to do is always normalize dates to either UTC or local prior to serializing then instruct the parser on which normalization you've chosen.

    DateTime now = DateTime.Now;
    DateTime utcNow = now.ToUniversalTime();
    
    string nowStr = now.ToString( "o" );
    string utcNowStr = utcNow.ToString( "o" );
    
    now = DateTime.Parse( nowStr );
    utcNow = DateTime.Parse( nowStr, null, DateTimeStyles.AdjustToUniversal );
    
    Debug.Assert( now == utcNow );
    

    How to list all databases in the mongo shell?

    For database list:

    show databases
    show dbs
    

    For table/collection list:

    show collections
    show tables
    db.getCollectionNames()
    

    pandas GroupBy columns with NaN (missing) values

    I am not able to add a comment to M. Kiewisch since I do not have enough reputation points (only have 41 but need more than 50 to comment).

    Anyway, just want to point out that M. Kiewisch solution does not work as is and may need more tweaking. Consider for example

    >>> df = pd.DataFrame({'a': [1, 2, 3, 5], 'b': [4, np.NaN, 6, 4]})
    >>> df
       a    b
    0  1  4.0
    1  2  NaN
    2  3  6.0
    3  5  4.0
    >>> df.groupby(['b']).sum()
         a
    b
    4.0  6
    6.0  3
    >>> df.astype(str).groupby(['b']).sum()
          a
    b
    4.0  15
    6.0   3
    nan   2
    

    which shows that for group b=4.0, the corresponding value is 15 instead of 6. Here it is just concatenating 1 and 5 as strings instead of adding it as numbers.

    Singular matrix issue with Numpy

    Use SVD or QR-decomposition to calculate exact solution in real or complex number fields:

    numpy.linalg.svd numpy.linalg.qr

    Getting Image from API in Angular 4/5+?

    There is no need to use angular http, you can get with js native functions

    _x000D_
    _x000D_
    // you will ned this function to fetch the image blob._x000D_
    async function getImage(url, fileName) {_x000D_
         // on the first then you will return blob from response_x000D_
        return await fetch(url).then(r => r.blob())_x000D_
        .then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
             _x000D_
            return new File([blob], fileName+'.'+   blob.type.split('/')[1]) ;_x000D_
        });_x000D_
    }_x000D_
    _x000D_
    // example url_x000D_
    var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
    _x000D_
    // calling the function_x000D_
    getImage(url, 'your-name-image').then(function(file) {_x000D_
    _x000D_
        // with file reader you will transform the file in a data url file;_x000D_
        var reader = new FileReader();_x000D_
        reader.readAsDataURL(file);_x000D_
        reader.onloadend = () => {_x000D_
        _x000D_
        // just putting the data url to img element_x000D_
            document.querySelector('#image').src = reader.result ;_x000D_
        }_x000D_
    })
    _x000D_
    <img src="" id="image"/>
    _x000D_
    _x000D_
    _x000D_

    How to change the buttons text using javascript

    Another solution could be using jquery button selector inside the if else statement $("#buttonId").text("your text");

    function showFilterItem() {
    if (filterstatus == 0) {
        filterstatus = 1;
        $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
        $("#ShowButton").text("Hide Filter");
    }
    else {
        filterstatus = 0;
        $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
         $("#ShowButton").text("Show Filter");
    }}
    

    Tomcat: LifecycleException when deploying

    I had this problem, where it just would not deploy on Tomcat , then i removed all @webServlet Annotations from all my servlet code and it deployed successfully.

    How can I view an object with an alert()

    you can use toSource method like this

    alert(product.toSource());
    

    Is it possible to cherry-pick a commit from another git repository?

    You can do it in one line as following. Hope you are in git repository which need the cherry-picked change and you have checked out to correct branch.

    git fetch ssh://[email protected]:7999/repo_to_get_it_from.git branchToPickFrom && git cherry-pick 02a197e9533
    # 
    

    git fetch [branch URL] [Branch to cherry-pick from] && git cherry-pick [commit ID]

    How to POST request using RestSharp

    My RestSharp POST method:

    var client = new RestClient(ServiceUrl);
    
    var request = new RestRequest("/resource/", Method.POST);
    
    // Json to post.
    string jsonToSend = JsonHelper.ToJson(json);
    
    request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
    request.RequestFormat = DataFormat.Json;
    
    try
    {
        client.ExecuteAsync(request, response =>
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                // OK
            }
            else
            {
                // NOK
            }
        });
    }
    catch (Exception error)
    {
        // Log
    }
    

    What tools do you use to test your public REST API?

    Postman in the chrome store is simple but powerful.

    Is there an equivalent of CSS max-width that works in HTML emails?

    Yes, there is a way to emulate max-width using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.

    Suppose you want the equivalent of a centered div with max-width of 350px. You create a table, set the width to 100%. The table has three cells in a row. Set the width of the center TD to 350 (using the HTML width attribute, not CSS), and there you go.

    If you want your content aligned left instead of centered, just leave out the first empty cell.

    Example:

    <table border="0" cellspacing="0" width="100%">
        <tr>
            <td></td>
            <td width="350">The width of this cell should be a maximum of 
                      350 pixels, but shrink to widths less than 350 pixels.
            </td>
            <td></td>
         </tr>
    </table> 
    

    In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:

    http://jsfiddle.net/YcwM7/

    Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

    Mostly the default shortcut key combination is Ctrl + Alt + Left/Right. (I'm using the linux version)

    Or you can have a toolbar option for it. Enable the tool bar by View -> Toolbar. The Left and Right Arrows will do the same. If you hover over it then you can see the shortcut key combination also.

    enter image description here enter image description here

    Just in case the key combination is not working (this can be due to several reasons like you are using a virtual machine, etc) you can change this default key combination, or you can add an extra combination (ex: For Back/Move to previous Ctrl + Alt + < or Comma).

    Go to Settings -> select keymap (type keymap in the search bar) -> **Editor Actions -> search for back and find Navigate options -> change the settings as you prefer.

    enter image description here

    MSSQL Error 'The underlying provider failed on Open'

    I got rid of this by resetting IIS, but still using Integrated Authentication in the connection string.

    Select first and last row from grouped data

    I know the question specified dplyr. But, since others already posted solutions using other packages, I decided to have a go using other packages too:

    Base package:

    df <- df[with(df, order(id, stopSequence, stopId)), ]
    merge(df[!duplicated(df$id), ], 
          df[!duplicated(df$id, fromLast = TRUE), ], 
          all = TRUE)
    

    data.table:

    df <-  setDT(df)
    df[order(id, stopSequence)][, .SD[c(1,.N)], by=id]
    

    sqldf:

    library(sqldf)
    min <- sqldf("SELECT id, stopId, min(stopSequence) AS StopSequence
          FROM df GROUP BY id 
          ORDER BY id, StopSequence, stopId")
    max <- sqldf("SELECT id, stopId, max(stopSequence) AS StopSequence
          FROM df GROUP BY id 
          ORDER BY id, StopSequence, stopId")
    sqldf("SELECT * FROM min
          UNION
          SELECT * FROM max")
    

    In one query:

    sqldf("SELECT * 
            FROM (SELECT id, stopId, min(stopSequence) AS StopSequence
                  FROM df GROUP BY id 
                  ORDER BY id, StopSequence, stopId)
            UNION
            SELECT *
            FROM (SELECT id, stopId, max(stopSequence) AS StopSequence
                  FROM df GROUP BY id 
                  ORDER BY id, StopSequence, stopId)")
    

    Output:

      id stopId StopSequence
    1  1      a            1
    2  1      c            3
    3  2      b            1
    4  2      c            4
    5  3      a            3
    6  3      b            1
    

    Show/hide forms using buttons and JavaScript

    There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?

    _x000D_
    _x000D_
    var someCondition = true;_x000D_
    _x000D_
    if (someCondition == true){_x000D_
        document.getElementById('hidden div').hidden = false;_x000D_
    }
    _x000D_
    <div id="hidden div" hidden>_x000D_
        stuff hidden by default_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden

    EXCEL Multiple Ranges - need different answers for each range

    use

    =VLOOKUP(D4,F4:G9,2)
    

    with the range F4:G9:

    0   0.1
    1   0.15
    5   0.2
    15  0.3
    30  1
    100 1.3
    

    and D4 being the value in question, e.g. 18.75 -> result: 0.3

    Best C++ IDE or Editor for Windows

    c++ IDE for MSWindows 1-Visual Studio 2-CodeBlocks (nighitly build) others (devcpp, netbeans, eclips,...) just sucks, dont waste your time

    Return list using select new in LINQ

    You're creating a new type of object therefore it's anonymous. You can return a dynamic.

    public dynamic GetProjectForCombo()
    {
        using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
        {
            var query = from pro in db.Projects
                    select new { pro.ProjectName, pro.ProjectId };
    
            return query.ToList();
        }
    }
    

    What are 'get' and 'set' in Swift?

    The getting and setting of variables within classes refers to either retrieving ("getting") or altering ("setting") their contents.

    Consider a variable members of a class family. Naturally, this variable would need to be an integer, since a family can never consist of two point something people.

    So you would probably go ahead by defining the members variable like this:

    class family {
       var members:Int
    }
    

    This, however, will give people using this class the possibility to set the number of family members to something like 0 or 1. And since there is no such thing as a family of 1 or 0, this is quite unfortunate.

    This is where the getters and setters come in. This way you can decide for yourself how variables can be altered and what values they can receive, as well as deciding what content they return.

    Returning to our family class, let's make sure nobody can set the members value to anything less than 2:

    class family {
      var _members:Int = 2
      var members:Int {
       get {
         return _members
       }
       set (newVal) {
         if newVal >= 2 {
           _members = newVal
         } else {
           println('error: cannot have family with less than 2 members')
         }
       }
      }
    }
    

    Now we can access the members variable as before, by typing instanceOfFamily.members, and thanks to the setter function, we can also set it's value as before, by typing, for example: instanceOfFamily.members = 3. What has changed, however, is the fact that we cannot set this variable to anything smaller than 2 anymore.

    Note the introduction of the _members variable, which is the actual variable to store the value that we set through the members setter function. The original members has now become a computed property, meaning that it only acts as an interface to deal with our actual variable.

    How to update values in a specific row in a Python Pandas DataFrame?

    Update null elements with value in the same location in other. Combines a DataFrame with other DataFrame using func to element-wise combine columns. The row and column indexes of the resulting DataFrame will be the union of the two.

    df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})
    df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
    df1.combine_first(df2)
         A    B
    0  1.0  3.0
    1  0.0  4.0
    

    more information in this link

    Common elements comparison between 2 lists

    1) Method1 saving list1 is dictionary and then iterating each elem in list2

    def findarrayhash(a,b):
        h1={k:1 for k in a}
        for val in b:
            if val in h1:
                print("common found",val)
                del h1[val]
            else:
                print("different found",val)
        for key in h1.iterkeys():
            print ("different found",key)
    

    Finding Common and Different elements:

    2) Method2 using set

    def findarrayset(a,b):
        common = set(a)&set(b)
        diff=set(a)^set(b)
        print list(common)
        print list(diff) 
    

    Reading rows from a CSV file in Python

    One can do it using pandas library.

    Example:

    import numpy as np
    import pandas as pd
    
    file = r"C:\Users\unknown\Documents\Example.csv"
    df1 = pd.read_csv(file)
    df1.head()
    

    Setting attribute disabled on a SPAN element does not prevent click events

    There is a dirty trick, what I have used:

    I am using bootstrap, so I just added .disabled class to the element which I want to disable. Bootstrap handles the rest of the things.

    Suggestion are heartily welcome towards this.

    Adding class on run time:

    $('#element').addClass('disabled');
    

    Android studio - Failed to find target android-18

    This will also happen if you have written compileSdkVersion = 22 e.g. (as used in the "new new" Android build system) instead of compileSdkVersion 22.

    Fast query runs slow in SSRS

    Had the same problem, and fixed it by giving the shared dataset a default parameter and updating that dataset in the reporting server.

    assign value using linq

    It can be done this way as well

    foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
                    {
                        //do your stuff here
                        company.Id= 2;
                        company.Name= "Sample"
                    }
    

    Maximum on http header values?

    No, HTTP does not define any limit. However most web servers do limit size of headers they accept. For example in Apache default limit is 8KB, in IIS it's 16K. Server will return 413 Entity Too Large error if headers size exceeds that limit.

    Related question: How big can a user agent string get?

    Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

    In the second image it looks like you want the image to fill the box, but the example you created DOES keep the aspect ratio (the pets look normal, not slim or fat).

    I have no clue if you photoshopped those images as example or the second one is "how it should be" as well (you said IS, while the first example you said "should")

    Anyway, I have to assume:

    If "the images are not resized keeping the aspect ration" and you show me an image which DOES keep the aspect ratio of the pixels, I have to assume you are trying to accomplish the aspect ratio of the "cropping" area (the inner of the green) WILE keeping the aspect ratio of the pixels. I.e. you want to fill the cell with the image, by enlarging and cropping the image.

    If that's your problem, the code you provided does NOT reflect "your problem", but your starting example.

    Given the previous two assumptions, what you need can't be accomplished with actual images if the height of the box is dynamic, but with background images. Either by using "background-size: contain" or these techniques (smart paddings in percents that limit the cropping or max sizes anywhere you want): http://fofwebdesign.co.uk/template/_testing/scale-img/scale-img.htm

    The only way this is possible with images is if we FORGET about your second iimage, and the cells have a fixed height, and FORTUNATELY, judging by your sample images, the height stays the same!

    So if your container's height doesn't change, and you want to keep your images square, you just have to set the max-height of the images to that known value (minus paddings or borders, depending on the box-sizing property of the cells)

    Like this:

    <div class="content">
      <div class="row">    
          <div class="cell">    
              <img src="http://lorempixel.com/output/people-q-c-320-320-2.jpg"/>
          </div>
          <div class="cell">    
              <img src="http://lorempixel.com/output/people-q-c-320-320-7.jpg"/>
          </div>
        </div>
    </div>
    

    And the CSS:

    .content {
        background-color: green;
    }
    
    .row {
        display: -webkit-box;
        display: -moz-box;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
    
        -webkit-box-orient: horizontal; 
        -moz-box-orient: horizontal;
        box-orient: horizontal;
        flex-direction: row;
    
        -webkit-box-pack: center;
        -moz-box-pack: center;
        box-pack: center;
        justify-content: center;
    
        -webkit-box-align: center;
        -moz-box-align: center;
        box-align: center;  
        align-items: center;
    
    }
    
    .cell {
        -webkit-box-flex: 1;
        -moz-box-flex: 1;
        box-flex: 1;
        -webkit-flex: 1 1 auto;
        flex: 1 1 auto;
        padding: 10px;
        border: solid 10px red;
        text-align: center;
        height: 300px;
        display: flex;
        align-items: center;
        box-sizing: content-box;
    }
    img {
        margin: auto;
        width: 100%;
        max-width: 300px;
        max-height:100%
    }
    

    http://jsfiddle.net/z25heocL/

    Your code is invalid (opening tags are instead of closing ones, so they output NESTED cells, not siblings, he used a SCREENSHOT of your images inside the faulty code, and the flex box is not holding the cells but both examples in a column (you setup "row" but the corrupt code nesting one cell inside the other resulted in a flex inside a flex, finally working as COLUMNS. I have no idea what you wanted to accomplish, and how you came up with that code, but I'm guessing what you want is this.

    I added display: flex to the cells too, so the image gets centered (I think display: table could have been used here as well with all this markup)

    Converting an int to a binary string representation in Java?

    You should really use Integer.toBinaryString() (as shown above), but if for some reason you want your own:

    // Like Integer.toBinaryString, but always returns 32 chars
    public static String asBitString(int value) {
      final char[] buf = new char[32];
      for (int i = 31; i >= 0; i--) {
        buf[31 - i] = ((1 << i) & value) == 0 ? '0' : '1';
      }
      return new String(buf);
    }
    

    MySQL add days to a date

    For your need:

    UPDATE classes 
    SET `date` = DATE_ADD(`date`, INTERVAL 2 DAY)
    WHERE id = 161
    

    Loop timer in JavaScript

    It should be:

    function moveItem() {
      jQuery(".stripTransmitter ul li a").trigger('click');
    }
    setInterval(moveItem,2000);
    

    setInterval(f, t) calls the the argument function, f, once every t milliseconds.

    Prevent Caching in ASP.NET MVC for specific actions using an attribute

    Output Caching in MVC

    [OutputCache(NoStore = true, Duration = 0, Location="None", VaryByParam = "*")]
    
    OR
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
    
    

    How To Auto-Format / Indent XML/HTML in Notepad++

    It's been the third time that I install Windows and npp and after some time I realize the tidy function no longer work. So I google for a solution, come to this thread, then with the help of few more so threads I finally fix it. I'll put a summary of all my actions once and for all.

    1. Install TextFX plugin: Plugins -> Plugin Manager -> Show Plugin Manager. Select TextFX Characters and install. After a restart of npp, the menu 'TextFX' should be visible. (credits: @remipod).

    2. Install libtidy.dll by pasting the Config folder from an old npp package: Follow instructions in this answer.

    3. After having a Config folder in your latest npp installation destination (typically C:\Program Files (x86)\Notepad++\plugins), npp needs write access to that folder. Right click Config folder -> Properties -> Security tab -> select Users, click Edit -> check Full control to allow read/write access. Note that you need administrator privileges to do that.

    4. Restart npp and verify TextFX -> TextFX HTML Tidy -> Tidy: Reindent XML works.

    How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

    As it was said already @INC is an array and you're free to add anything you want.

    My CGI REST script looks like:

    #!/usr/bin/perl
    use strict;
    use warnings;
    BEGIN {
        push @INC, 'fully_qualified_path_to_module_wiht_our_REST.pm';
    }
    use Modules::Rest;
    gone(@_);
    

    Subroutine gone is exported by Rest.pm.

    System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

    After trying all the mentioned solutions I found the PlatformTarget somehow added to AnyCPU configuration in my project .csproj.

    <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
        <DebugType>pdbonly</DebugType>
        <Optimize>true</Optimize>
        <OutputPath>bin\Release\</OutputPath>
        <DefineConstants>TRACE</DefineConstants>
        <ErrorReport>prompt</ErrorReport>
        <WarningLevel>4</WarningLevel>
        <PlatformTarget>x64</PlatformTarget>
    </PropertyGroup>
    

    Removing the line worked for me.

    How do I loop through a date range?

    1 Year later, may it help someone,

    This version includes a predicate, to be more flexible.

    Usage

    var today = DateTime.UtcNow;
    var birthday = new DateTime(2018, 01, 01);
    

    Daily to my birthday

    var toBirthday = today.RangeTo(birthday);  
    

    Monthly to my birthday, Step 2 months

    var toBirthday = today.RangeTo(birthday, x => x.AddMonths(2));
    

    Yearly to my birthday

    var toBirthday = today.RangeTo(birthday, x => x.AddYears(1));
    

    Use RangeFrom instead

    // same result
    var fromToday = birthday.RangeFrom(today);
    var toBirthday = today.RangeTo(birthday);
    

    Implementation

    public static class DateTimeExtensions 
    {
    
        public static IEnumerable<DateTime> RangeTo(this DateTime from, DateTime to, Func<DateTime, DateTime> step = null)
        {
            if (step == null)
            {
                step = x => x.AddDays(1);
            }
    
            while (from < to)
            {
                yield return from;
                from = step(from);
            }
        }
    
        public static IEnumerable<DateTime> RangeFrom(this DateTime to, DateTime from, Func<DateTime, DateTime> step = null)
        {
            return from.RangeTo(to, step);
        }
    }
    

    Extras

    You could throw an Exception if the fromDate > toDate, but I prefer to return an empty range instead []

    Check if a given key already exists in a dictionary and increment it

    Agreed with cgoldberg. How I do it is:

    try:
        dict[key] += 1
    except KeyError:
        dict[key] = 1
    

    So either do it as above, or use a default dict as others have suggested. Don't use if statements. That's not Pythonic.

    Looping through array and removing items, without breaking for loop

    The array is being re-indexed when you do a .splice(), which means you'll skip over an index when one is removed, and your cached .length is obsolete.

    To fix it, you'd either need to decrement i after a .splice(), or simply iterate in reverse...

    var i = Auction.auctions.length
    while (i--) {
        ...
        if (...) { 
            Auction.auctions.splice(i, 1);
        } 
    }
    

    This way the re-indexing doesn't affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.

    How to make a redirection on page load in JSF 1.x

    Assume that foo.jsp is your jsp file. and following code is the button that you want do redirect.

    <h:commandButton value="Redirect" action="#{trial.enter }"/>  
    

    And now we'll check the method for directing in your java (service) class

     public String enter() {
                if (userName.equals("xyz") && password.equals("123")) {
                    return "enter";
                } else {
                    return null;
                }
            } 
    

    and now this is a part of faces-config.xml file

    <managed-bean>
            <managed-bean-name>'class_name'</managed-bean-name>
            <managed-bean-class>'package_name'</managed-bean-class>
            <managed-bean-scope>request</managed-bean-scope>
        </managed-bean>
    
    
        <navigation-case>
                    <from-outcome>enter</from-outcome>
                    <to-view-id>/foo.jsp</to-view-id>
                    <redirect />
                </navigation-case>
    

    How to make a JFrame button open another JFrame class in Netbeans?

    Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)

    btnLogin.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) {
            this.setVisible(false);
            new FrmMain().setVisible(true); // Main Form to show after the Login Form..
        }
    });
    

    Simple VBA selection: Selecting 5 cells to the right of the active cell

    This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

    Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


    Sub testForStackOverflow()
        Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
    End Sub
    

    How do you list volumes in docker containers?

    docker inspect -f '{{ json .Mounts }}' containerid | jq '.[]'
    

    How to simulate a click with JavaScript?

    document.getElementById('elementId').dispatchEvent(new MouseEvent("click",{bubbles: true, cancellable: true}));
    

    Follow this link to know about the mouse events using Javascript and browser compatibility for the same

    https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent#Browser_compatibility

    changing the language of error message in required field in html5 contact form

    setCustomValidity's purpose is not just to set the validation message, it itself marks the field as invalid. It allows you to write custom validation checks which aren't natively supported.

    You have two possible ways to set a custom message, an easy one that does not involve Javascript and one that does.

    The easiest way is to simply use the title attribute on the input element - its content is displayed together with the standard browser message.

    <input type="text" required title="Lütfen isaretli yerleri doldurunuz" />
    

    enter image description here

    If you want only your custom message to be displayed, a bit of Javascript is required. I have provided both examples for you in this fiddle.

    How to build PDF file from binary string returned from a web-service using javascript

    Is there any solution like building a pdf file on file system in order to let the user download it?

    Try setting responseType of XMLHttpRequest to blob , substituting download attribute at a element for window.open to allow download of response from XMLHttpRequest as .pdf file

    var request = new XMLHttpRequest();
    request.open("GET", "/path/to/pdf", true); 
    request.responseType = "blob";
    request.onload = function (e) {
        if (this.status === 200) {
            // `blob` response
            console.log(this.response);
            // create `objectURL` of `this.response` : `.pdf` as `Blob`
            var file = window.URL.createObjectURL(this.response);
            var a = document.createElement("a");
            a.href = file;
            a.download = this.response.name || "detailPDF";
            document.body.appendChild(a);
            a.click();
            // remove `a` following `Save As` dialog, 
            // `window` regains `focus`
            window.onfocus = function () {                     
              document.body.removeChild(a)
            }
        };
    };
    request.send();
    

    How do you convert an entire directory with ffmpeg?

    Of course, now PowerShell has come along, specifically designed to make something exactly like this extremely easy.

    And, yes, PowerShell is also available on other operating systems other than just Windows, but it comes pre-installed on Windows, so this should be useful to everyone.

    First, you'll want to list all of the files within the current directory, so, we'll start off with:

    ls
    

    You can also use ls -Recurse if you want to recursively convert all files in subdirectories too.

    Then, we'll filter those down to only the type of file we want to convert - e.g. "avi".

    ls | Where { $_.Extension -eq ".avi" }
    

    After that, we'll pass that information to FFmpeg through a ForEach.

    For FFmpeg's input, we will use the FullName - that's the entire path to the file. And for FFmpeg's output we will use the Name - but replacing the .avi at the end with .mp3. So, it will look something like this:

    $_.Name.Replace(".avi", ".mp3")
    

    So, let's put all of that together and this is the result:

    ls | Where { $_.Extension -eq ".avi" } | ForEach { ffmpeg -i $_.FullName $_.Name.Replace(".avi", ".mp3") }
    

    That will convert all ".avi" files into ".mp3" files through FFmpeg, just replace the three things in quotes to decide what type of conversion you want, and feel free to add any other arguments to FFmpeg within the ForEach.

    You could take this a step further and add Remove-Item to the end to automatically delete the old files.

    If ffmpeg isn't in your path, and it's actually in the directory you're currently in, write ./ffmpeg there instead of just ffmpeg.

    Hope this helps anyone.

    Do you (really) write exception safe code?

    Some of us have been using exception for over 20 years. PL/I has them, for example. The premise that they are a new and dangerous technology seems questionable to me.

    Server Error in '/' Application. ASP.NET

    http://www.velocityreviews.com/forums/t123353-configuration-error.html


    If you want to use inetpub/wwwroot/aspnet as your application, remove this line :

    Line 26: and any other lines which define MachineToApplication beyond application level

    If you want to use d:\inetpub\wwwroot\aspnet\begin\chapter02\ as your application, create an IIS Application which points to d:\inetpub\wwwroot\aspnet\begin\chapter02\


    maybe you can refer link above. For my application, my web.config store in d:\inetpub\wwwroot\aspnet\begin\chapter02\ and when i move the web.config to d:\inetpub\wwwroot\aspnet and the problem is solve. Please check also does your application have two web.config file.

    How to make a class JSON serializable

    There are many approaches to this problem. 'ObjDict' (pip install objdict) is another. There is an emphasis on providing javascript like objects which can also act like dictionaries to best handle data loaded from JSON, but there are other features which can be useful as well. This provides another alternative solution to the original problem.

    Share variables between files in Node.js?

    I'm unable to find an scenario where a global var is the best option, of course you can have one, but take a look at these examples and you may find a better way to accomplish the same:

    Scenario 1: Put the stuff in config files

    You need some value that it's the same across the application, but it changes depending on the environment (production, dev or test), the mailer type as example, you'd need:

    // File: config/environments/production.json
    {
        "mailerType": "SMTP",
        "mailerConfig": {
          "service": "Gmail",
          ....
    }
    

    and

    // File: config/environments/test.json
    {
        "mailerType": "Stub",
        "mailerConfig": {
          "error": false
        }
    }
    

    (make a similar config for dev too)

    To decide which config will be loaded make a main config file (this will be used all over the application)

    // File: config/config.js
    var _ = require('underscore');
    
    module.exports = _.extend(
        require(__dirname + '/../config/environments/' + process.env.NODE_ENV + '.json') || {});
    

    And now you can get the data like this:

    // File: server.js
    ...
    var config = require('./config/config');
    ...
    mailer.setTransport(nodemailer.createTransport(config.mailerType, config.mailerConfig));
    

    Scenario 2: Use a constants file

    // File: constants.js
    module.exports = {
      appName: 'My neat app',
      currentAPIVersion: 3
    };
    

    And use it this way

    // File: config/routes.js
    
    var constants = require('../constants');
    
    module.exports = function(app, passport, auth) {
      var apiroot = '/api/v' + constants.currentAPIVersion;
    ...
      app.post(apiroot + '/users', users.create);
    ...
    

    Scenario 3: Use a helper function to get/set the data

    Not a big fan of this one, but at least you can track the use of the 'name' (citing the OP's example) and put validations in place.

    // File: helpers/nameHelper.js
    
    var _name = 'I shall not be null'
    
    exports.getName = function() {
      return _name;
    };
    
    exports.setName = function(name) {
      //validate the name...
      _name = name;
    };
    

    And use it

    // File: controllers/users.js
    
    var nameHelper = require('../helpers/nameHelper.js');
    
    exports.create = function(req, res, next) {
      var user = new User();
      user.name = req.body.name || nameHelper.getName();
      ...
    

    There could be a use case when there is no other solution than having a global var, but usually you can share the data in your app using one of these scenarios, if you are starting to use node.js (as I was sometime ago) try to organize the way you handle the data over there because it can get messy really quick.

    ORACLE: Updating multiple columns at once

    I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.

    this is a generic example let me know if this explains the point i mentioned

    CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
    IS
        empName VARCHAR2(50);
        empSalary NUMBER(7,2);      
    BEGIN
        UPDATE emp
        SET sal = sal + 1000
        WHERE empno = 7499
        RETURNING ename, sal
        INTO empName, empSalary;
    
        DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
        DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
    END;
    

    Simplest way to download and unzip files in Node.js cross-platform?

    Checkout adm-zip.

    ADM-ZIP is a pure JavaScript implementation for zip data compression for NodeJS.

    The library allows you to:

    • decompress zip files directly to disk or in-memory buffers
    • compress files and store them to disk in .zip format or in compressed buffers
    • update content of/add new/delete files from an existing .zip