Programs & Examples On #Iterable

An iterable is an object, such as a string or collection, that can be iterated over, yielding up its members one at a time.

Convert Java Array to Iterable

First of all, I can only agree that Arrays.asList(T...) is clearly the best solution for Wrapper types or arrays with non-primtive datatypes. This method calls a constructor of a simple private static AbstractList implementation in the Arrays class which basically saves the given array reference as field and simulates a list by overriding the needed methods.

If you can choose between a primtive type or a Wrapper type for your array, I would use the Wrapper type for such situations but of course, it's not always useful or required. There would be only two possibilities you can do:

1) You can create a class with a static method for each primitive datatype array (boolean, byte, short, int, long, char, float, double returning an Iterable<WrapperType>. These methods would use anonymous classes of Iterator (besides Iterable) which are allowed to contain the reference of the comprising method's argument (for example an int[]) as field in order to implement the methods.

-> This approach is performant and saves you memory (except for the memory of the newly created methods, even though, using Arrays.asList() would take memory in the same way)

2) Since arrays don't have methods (as to be read on the side you linked) they can't provide an Iterator instance either. If you really are too lazy to write new classes, you must use an instance of an already existing class that implements Iterable because there is no other way around than instantiating Iterable or a subtype.
The ONLY way to create an existing Collection derivative implementing Iterable is to use a loop (except you use anonymous classes as described above) or you instantiate an Iterable implementing class whose constructor allows a primtive type array (because Object[] doesn't allow arrays with primitive type elements) but as far as I know, the Java API doesn't feature a class like that.

The reason for the loop can be explained easily:
for each Collection you need Objects and primtive datatypes aren't objects. Objects are much bigger than primitive types so that they require additional data which must be generated for each element of the primitive type array. That means if two ways of three (using Arrays.asList(T...) or using an existing Collection) require an aggregate of objects, you need to create for each primitive value of your int[] array the wrapper object. The third way would use the array as is and use it in an anonymous class as I think it's preferable due to fast performance.

There is also a third strategy using an Object as argument for the method where you want to use the array or Iterable and it would require type checks to figure out which type the argument has, however I wouldn't recommend it at all as you usually need to consider that the Object hasn't always the required type and that you need seperate code for certain cases.

In conclusion, it's the fault of Java's problematic Generic Type system which doesn't allow to use primitive types as generic type which would save a lot of code by using simply Arrays.asList(T...). So you need to program for each primitive type array, you need, such a method (which basically makes no difference to the memory used by a C++ program which would create for each used type argument a seperate method.

Python - TypeError: 'int' object is not iterable

If the case is:

n=int(input())

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

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

Understanding slice notation

The Python tutorial talks about it (scroll down a bit until you get to the part about slicing).

The ASCII art diagram is helpful too for remembering how slices work:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n.

How do I add the contents of an iterable to a set?

You can add elements of a list to a set like this:

>>> foo = set(range(0, 4))
>>> foo
set([0, 1, 2, 3])
>>> foo.update(range(2, 6))
>>> foo
set([0, 1, 2, 3, 4, 5])

What exactly are iterator, iterable, and iteration?

Here's my cheat sheet:

 sequence
  +
  |
  v
   def __getitem__(self, index: int):
  +    ...
  |    raise IndexError
  |
  |
  |              def __iter__(self):
  |             +     ...
  |             |     return <iterator>
  |             |
  |             |
  +--> or <-----+        def __next__(self):
       +        |       +    ...
       |        |       |    raise StopIteration
       v        |       |
    iterable    |       |
           +    |       |
           |    |       v
           |    +----> and +-------> iterator
           |                               ^
           v                               |
   iter(<iterable>) +----------------------+
                                           |
   def generator():                        |
  +    yield 1                             |
  |                 generator_expression +-+
  |                                        |
  +-> generator() +-> generator_iterator +-+

Quiz: Do you see how...

  1. every iterator is an iterable?
  2. a container object's __iter__() method can be implemented as a generator?
  3. an iterable that has a __next__ method is not necessarily an iterator?

Answers:

  1. Every iterator must have an __iter__ method. Having __iter__ is enough to be an iterable. Therefore every iterator is an iterable.
  2. When __iter__ is called it should return an iterator (return <iterator> in the diagram above). Calling a generator returns a generator iterator which is a type of iterator.

    class Iterable1:
        def __iter__(self):
            # a method (which is a function defined inside a class body)
            # calling iter() converts iterable (tuple) to iterator
            return iter((1,2,3))
    
    class Iterable2:
        def __iter__(self):
            # a generator
            for i in (1, 2, 3):
                yield i
    
    class Iterable3:
        def __iter__(self):
            # with PEP 380 syntax
            yield from (1, 2, 3)
    
    # passes
    assert list(Iterable1()) == list(Iterable2()) == list(Iterable3()) == [1, 2, 3]
    
  3. Here is an example:

    class MyIterable:
    
        def __init__(self):
            self.n = 0
    
        def __getitem__(self, index: int):
            return (1, 2, 3)[index]
    
        def __next__(self):
            n = self.n = self.n + 1
            if n > 3:
                raise StopIteration
            return n
    
    # if you can iter it without raising a TypeError, then it's an iterable.
    iter(MyIterable())
    
    # but obviously `MyIterable()` is not an iterator since it does not have
    # an `__iter__` method.
    from collections.abc import Iterator
    assert isinstance(MyIterable(), Iterator)  # AssertionError
    

Get size of an Iterable in Java

This is perhaps a bit late, but may help someone. I come across similar issue with Iterable in my codebase and solution was to use for each without explicitly calling values.iterator();.

int size = 0;
for(T value : values) {
   size++;
}

Convert Iterable to Stream using Java 8 JDK

If you can use Guava library, since version 21, you can use

Streams.stream(iterable)

What is the difference between iterator and iterable and how to use them?

An implementation of Iterable is one that provides an Iterator of itself:

public interface Iterable<T>
{
    Iterator<T> iterator();
}

An iterator is a simple way of allowing some to loop through a collection of data without assignment privileges (though with ability to remove).

public interface Iterator<E>
{
    boolean hasNext();
    E next();
    void remove();
}

See Javadoc.

Java: Get first item from a collection

You could do this:

String strz[] = strs.toArray(String[strs.size()]);
String theFirstOne = strz[0];

The javadoc for Collection gives the following caveat wrt ordering of the elements of the array:

If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

In Python, how do I determine if an object is iterable?

I'd like to shed a little bit more light on the interplay of iter, __iter__ and __getitem__ and what happens behind the curtains. Armed with that knowledge, you will be able to understand why the best you can do is

try:
    iter(maybe_iterable)
    print('iteration will probably work')
except TypeError:
    print('not iterable')

I will list the facts first and then follow up with a quick reminder of what happens when you employ a for loop in python, followed by a discussion to illustrate the facts.

Facts

  1. You can get an iterator from any object o by calling iter(o) if at least one of the following conditions holds true:

    a) o has an __iter__ method which returns an iterator object. An iterator is any object with an __iter__ and a __next__ (Python 2: next) method.

    b) o has a __getitem__ method.

  2. Checking for an instance of Iterable or Sequence, or checking for the attribute __iter__ is not enough.

  3. If an object o implements only __getitem__, but not __iter__, iter(o) will construct an iterator that tries to fetch items from o by integer index, starting at index 0. The iterator will catch any IndexError (but no other errors) that is raised and then raises StopIteration itself.

  4. In the most general sense, there's no way to check whether the iterator returned by iter is sane other than to try it out.

  5. If an object o implements __iter__, the iter function will make sure that the object returned by __iter__ is an iterator. There is no sanity check if an object only implements __getitem__.

  6. __iter__ wins. If an object o implements both __iter__ and __getitem__, iter(o) will call __iter__.

  7. If you want to make your own objects iterable, always implement the __iter__ method.

for loops

In order to follow along, you need an understanding of what happens when you employ a for loop in Python. Feel free to skip right to the next section if you already know.

When you use for item in o for some iterable object o, Python calls iter(o) and expects an iterator object as the return value. An iterator is any object which implements a __next__ (or next in Python 2) method and an __iter__ method.

By convention, the __iter__ method of an iterator should return the object itself (i.e. return self). Python then calls next on the iterator until StopIteration is raised. All of this happens implicitly, but the following demonstration makes it visible:

import random

class DemoIterable(object):
    def __iter__(self):
        print('__iter__ called')
        return DemoIterator()

class DemoIterator(object):
    def __iter__(self):
        return self

    def __next__(self):
        print('__next__ called')
        r = random.randint(1, 10)
        if r == 5:
            print('raising StopIteration')
            raise StopIteration
        return r

Iteration over a DemoIterable:

>>> di = DemoIterable()
>>> for x in di:
...     print(x)
...
__iter__ called
__next__ called
9
__next__ called
8
__next__ called
10
__next__ called
3
__next__ called
10
__next__ called
raising StopIteration

Discussion and illustrations

On point 1 and 2: getting an iterator and unreliable checks

Consider the following class:

class BasicIterable(object):
    def __getitem__(self, item):
        if item == 3:
            raise IndexError
        return item

Calling iter with an instance of BasicIterable will return an iterator without any problems because BasicIterable implements __getitem__.

>>> b = BasicIterable()
>>> iter(b)
<iterator object at 0x7f1ab216e320>

However, it is important to note that b does not have the __iter__ attribute and is not considered an instance of Iterable or Sequence:

>>> from collections import Iterable, Sequence
>>> hasattr(b, '__iter__')
False
>>> isinstance(b, Iterable)
False
>>> isinstance(b, Sequence)
False

This is why Fluent Python by Luciano Ramalho recommends calling iter and handling the potential TypeError as the most accurate way to check whether an object is iterable. Quoting directly from the book:

As of Python 3.4, the most accurate way to check whether an object x is iterable is to call iter(x) and handle a TypeError exception if it isn’t. This is more accurate than using isinstance(x, abc.Iterable) , because iter(x) also considers the legacy __getitem__ method, while the Iterable ABC does not.

On point 3: Iterating over objects which only provide __getitem__, but not __iter__

Iterating over an instance of BasicIterable works as expected: Python constructs an iterator that tries to fetch items by index, starting at zero, until an IndexError is raised. The demo object's __getitem__ method simply returns the item which was supplied as the argument to __getitem__(self, item) by the iterator returned by iter.

>>> b = BasicIterable()
>>> it = iter(b)
>>> next(it)
0
>>> next(it)
1
>>> next(it)
2
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Note that the iterator raises StopIteration when it cannot return the next item and that the IndexError which is raised for item == 3 is handled internally. This is why looping over a BasicIterable with a for loop works as expected:

>>> for x in b:
...     print(x)
...
0
1
2

Here's another example in order to drive home the concept of how the iterator returned by iter tries to access items by index. WrappedDict does not inherit from dict, which means instances won't have an __iter__ method.

class WrappedDict(object): # note: no inheritance from dict!
    def __init__(self, dic):
        self._dict = dic

    def __getitem__(self, item):
        try:
            return self._dict[item] # delegate to dict.__getitem__
        except KeyError:
            raise IndexError

Note that calls to __getitem__ are delegated to dict.__getitem__ for which the square bracket notation is simply a shorthand.

>>> w = WrappedDict({-1: 'not printed',
...                   0: 'hi', 1: 'StackOverflow', 2: '!',
...                   4: 'not printed', 
...                   'x': 'not printed'})
>>> for x in w:
...     print(x)
... 
hi
StackOverflow
!

On point 4 and 5: iter checks for an iterator when it calls __iter__:

When iter(o) is called for an object o, iter will make sure that the return value of __iter__, if the method is present, is an iterator. This means that the returned object must implement __next__ (or next in Python 2) and __iter__. iter cannot perform any sanity checks for objects which only provide __getitem__, because it has no way to check whether the items of the object are accessible by integer index.

class FailIterIterable(object):
    def __iter__(self):
        return object() # not an iterator

class FailGetitemIterable(object):
    def __getitem__(self, item):
        raise Exception

Note that constructing an iterator from FailIterIterable instances fails immediately, while constructing an iterator from FailGetItemIterable succeeds, but will throw an Exception on the first call to __next__.

>>> fii = FailIterIterable()
>>> iter(fii)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: iter() returned non-iterator of type 'object'
>>>
>>> fgi = FailGetitemIterable()
>>> it = iter(fgi)
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/iterdemo.py", line 42, in __getitem__
    raise Exception
Exception

On point 6: __iter__ wins

This one is straightforward. If an object implements __iter__ and __getitem__, iter will call __iter__. Consider the following class

class IterWinsDemo(object):
    def __iter__(self):
        return iter(['__iter__', 'wins'])

    def __getitem__(self, item):
        return ['__getitem__', 'wins'][item]

and the output when looping over an instance:

>>> iwd = IterWinsDemo()
>>> for x in iwd:
...     print(x)
...
__iter__
wins

On point 7: your iterable classes should implement __iter__

You might ask yourself why most builtin sequences like list implement an __iter__ method when __getitem__ would be sufficient.

class WrappedList(object): # note: no inheritance from list!
    def __init__(self, lst):
        self._list = lst

    def __getitem__(self, item):
        return self._list[item]

After all, iteration over instances of the class above, which delegates calls to __getitem__ to list.__getitem__ (using the square bracket notation), will work fine:

>>> wl = WrappedList(['A', 'B', 'C'])
>>> for x in wl:
...     print(x)
... 
A
B
C

The reasons your custom iterables should implement __iter__ are as follows:

  1. If you implement __iter__, instances will be considered iterables, and isinstance(o, collections.abc.Iterable) will return True.
  2. If the object returned by __iter__ is not an iterator, iter will fail immediately and raise a TypeError.
  3. The special handling of __getitem__ exists for backwards compatibility reasons. Quoting again from Fluent Python:

That is why any Python sequence is iterable: they all implement __getitem__ . In fact, the standard sequences also implement __iter__, and yours should too, because the special handling of __getitem__ exists for backward compatibility reasons and may be gone in the future (although it is not deprecated as I write this).

Easy way to convert Iterable to Collection

I didn't see a simple one line solution without any dependencies. I simple use

List<Users> list;
Iterable<IterableUsers> users = getUsers();

// one line solution
list = StreamSupport.stream(users.spliterator(), true).collect(Collectors.toList());

Remove rows with all or some NAs (missing values) in data.frame

We can also use the subset function for this.

finalData<-subset(data,!(is.na(data["mmul"]) | is.na(data["rnor"])))

This will give only those rows that do not have NA in both mmul and rnor

Moment js date time comparison

moment(d).isAfter(ahead30now); // true

http://momentjs.com/docs/#/query/is-after/

if (moment(d).isAfter(ahead30now)) {
    // allow input time
    console.log('UTC TIME DB', d.format());
} else {

}

How to determine if a String has non-alphanumeric characters?

Though it won't work for numbers, you can check if the lowercase and uppercase values are same or not, For non-alphabetic characters they will be same, You should check for number before this for better usability

GitLab remote: HTTP Basic: Access denied and fatal Authentication

GO TO C:\Users\<<USER>> AND DELETE THE .gitconfig file then try a command that connects to upstream like git clone, git pull or git push. You will be prompted to re-enter your credentials. Kindly do so.

How to align the checkbox and label in same line in html?

None of these suggestions above worked for me as-is. I had to use the following to center a checkbox with the label text displayed to the right of the box:

<style>
.checkboxes {
  display: flex;
  justify-content: center;
  align-items: center;
  vertical-align: middle;
  word-wrap: break-word;
}
</style>

<label for="checkbox1" class="checkboxes"><input type="checkbox" id="checkbox1" name="checked" value="yes" class="checkboxes"/>
Check the box.</label>

How to edit log message already committed in Subversion?

If your repository enables setting revision properties via the pre-revprop-change hook you can change log messages much easier.

svn propedit --revprop -r 1234 svn:log url://to/repository

Or in TortoiseSVN, AnkhSVN and probably many other subversion clients by right clicking on a log entry and then 'change log message'.

How to read keyboard-input?

Non-blocking, multi-threaded example:

As blocking on keyboard input (since the input() function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive.

This works by creating one thread to run in the background, continually calling input() and then passing any data it receives to a queue.

In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.

1. Bare Python 3 code example (no comments):

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        input_str = input()
        inputQueue.put(input_str)

def main():
    EXIT_COMMAND = "exit"
    inputQueue = queue.Queue()

    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    while (True):
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        time.sleep(0.01) 
    print("End.")

if (__name__ == '__main__'): 
    main()

2. Same Python 3 code as above, but with extensive explanatory comments:

"""
read_keyboard_input.py

Gabriel Staples
www.ElectricRCAircraftGuy.com
14 Nov. 2018

References:
- https://pyserial.readthedocs.io/en/latest/pyserial_api.html
- *****https://www.tutorialspoint.com/python/python_multithreading.htm
- *****https://en.wikibooks.org/wiki/Python_Programming/Threading
- https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass
- https://docs.python.org/3/library/queue.html
- https://docs.python.org/3.7/library/threading.html

To install PySerial: `sudo python3 -m pip install pyserial`

To run this program: `python3 this_filename.py`

"""

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        # Receive keyboard input from user.
        input_str = input()
        
        # Enqueue this input string.
        # Note: Lock not required here since we are only calling a single Queue method, not a sequence of them 
        # which would otherwise need to be treated as one atomic operation.
        inputQueue.put(input_str)

def main():

    EXIT_COMMAND = "exit" # Command to exit this program

    # The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue
    # method calls in a row.  Use this if you have such a need, as follows:
    # 1. Pass queueLock as an input parameter to whichever function requires it.
    # 2. Call queueLock.acquire() to obtain the lock.
    # 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling
    # inputQueue.qsize(), followed by inputQueue.put(), for example.
    # 4. Call queueLock.release() to release the lock.
    # queueLock = threading.Lock() 

    #Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.
    inputQueue = queue.Queue()

    # Create & start a thread to read keyboard inputs.
    # Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since
    # this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.
    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    # Main loop
    while (True):

        # Read keyboard inputs
        # Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure
        # multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this
        # example program, no locks are required.
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break # exit the while loop
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        # Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.
        time.sleep(0.01) 
    
    print("End.")

# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:
if (__name__ == '__main__'): 
    main()

Sample output:

$ python3 read_keyboard_input.py
Ready for keyboard input:
hey
input_str = hey
hello
input_str = hello
7000
input_str = 7000
exit
input_str = exit
Exiting serial terminal.
End.

The Python Queue library is thread-safe:

Note that Queue.put() and Queue.get() and other Queue class methods are thread-safe! That means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added):

The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.

References:

  1. https://pyserial.readthedocs.io/en/latest/pyserial_api.html
  2. *****https://www.tutorialspoint.com/python/python_multithreading.htm
  3. *****https://en.wikibooks.org/wiki/Python_Programming/Threading
  4. Python: How do I make a subclass from a superclass?
  5. https://docs.python.org/3/library/queue.html
  6. https://docs.python.org/3.7/library/threading.html

Related/Cross-Linked:

  1. PySerial non-blocking read loop

Display html text in uitextview

Use following block of code for ios 7+.

NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p><img src='http://blogs.babble.com/famecrawler/files/2010/11/mickey_mouse-1097.jpg' width=70 height=100 />";
NSAttributedString *attributedString = [[NSAttributedString alloc]
          initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
               options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
    documentAttributes: nil
                 error: nil
];
textView.attributedText = attributedString;

Can my enums have friendly names?

One problem with this trick is that description attribute cannot be localized. I do like a technique by Sacha Barber where he creates his own version of Description attribute which would pick up values from the corresponding resource manager.

http://www.codeproject.com/KB/WPF/FriendlyEnums.aspx

Although the article is around a problem that's generally faced by WPF developers when binding to enums, you can jump directly to the part where he creates the LocalizableDescriptionAttribute.

Is there a CSS parent selector?

There isn't a way to do this in CSS 2. You could add the class to the li and reference the a:

li.active > a {
    property: value;
}

Fatal error: Call to undefined function mysql_connect()

This Code Can Help You

<?php 

$servername = "localhost";
$username = "root";
$password = "";


$con = new mysqli($servername, $username, $password);

?>

But Change The "servername","username" and "password"

Downloading and unzipping a .zip file without writing to disk

Vishal's example, however great, confuses when it comes to the file name, and I do not see the merit of redefing 'zipfile'.

Here is my example that downloads a zip that contains some files, one of which is a csv file that I subsequently read into a pandas DataFrame:

from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen
import pandas

url = urlopen("https://www.federalreserve.gov/apps/mdrm/pdf/MDRM.zip")
zf = ZipFile(StringIO(url.read()))
for item in zf.namelist():
    print("File in zip: "+  item)
# find the first matching csv file in the zip:
match = [s for s in zf.namelist() if ".csv" in s][0]
# the first line of the file contains a string - that line shall de ignored, hence skiprows
df = pandas.read_csv(zf.open(match), low_memory=False, skiprows=[0])

(Note, I use Python 2.7.13)

This is the exact solution that worked for me. I just tweaked it a little bit for Python 3 version by removing StringIO and adding IO library

Python 3 Version

from io import BytesIO
from zipfile import ZipFile
import pandas
import requests

url = "https://www.nseindia.com/content/indices/mcwb_jun19.zip"
content = requests.get(url)
zf = ZipFile(BytesIO(content.content))

for item in zf.namelist():
    print("File in zip: "+  item)

# find the first matching csv file in the zip:
match = [s for s in zf.namelist() if ".csv" in s][0]
# the first line of the file contains a string - that line shall de     ignored, hence skiprows
df = pandas.read_csv(zf.open(match), low_memory=False, skiprows=[0])

How to convert an Image to base64 string in java?

I think you might want:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

How can I check if a view is visible or not in Android?

You'd use the corresponding method getVisibility(). Method names prefixed with 'get' and 'set' are Java's convention for representing properties. Some language have actual language constructs for properties but Java isn't one of them. So when you see something labeled 'setX', you can be 99% certain there's a corresponding 'getX' that will tell you the value.

Can HTML checkboxes be set to readonly?

If you want ALL your checkboxes to be "locked" so user can't change the "checked" state if "readonly" attibute is present, then you can use jQuery:

$(':checkbox').click(function () {
    if (typeof ($(this).attr('readonly')) != "undefined") {
        return false;
    }
});

Cool thing about this code is that it allows you to change the "readonly" attribute all over your code without having to rebind every checkbox.

It works for radio buttons as well.

How to Disable GUI Button in Java

Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. Its more efficient..

if (command.equals("w"))
{
    FileConverter fc = new FileConverter();
    btnConvertDocuments.setEnabled(false);
}

Where does Console.WriteLine go in ASP.NET?

Unless you are in a strict console application, I wouldn't use it, because you can't really see it. I would use Trace.WriteLine() for debugging-type information that can be turned on and off in production.

How to view .img files?

The file extension .img does not say anything about its content.

Most commonly .img files are a floppy/CD/DVD/ISO image, a filesystem image, a disk image, or even just (custom) binary data.

In case it is an CD/DVD image or a specific filesystem image (like fat, ntfs, ...) you can open these files with 7-Zip.

On *nix based systems also the file tool or (libmagic) could help you find out what it is.

Retrieving Property name from lambda expression

Starting with .NET 4.0 you can use ExpressionVisitor to find properties:

class ExprVisitor : ExpressionVisitor {
    public bool IsFound { get; private set; }
    public string MemberName { get; private set; }
    public Type MemberType { get; private set; }
    protected override Expression VisitMember(MemberExpression node) {
        if (!IsFound && node.Member.MemberType == MemberTypes.Property) {
            IsFound = true;
            MemberName = node.Member.Name;
            MemberType = node.Type;
        }
        return base.VisitMember(node);
    }
}

Here is how you use this visitor:

var visitor = new ExprVisitor();
visitor.Visit(expr);
if (visitor.IsFound) {
    Console.WriteLine("First property in the expression tree: Name={0}, Type={1}", visitor.MemberName, visitor.MemberType.FullName);
} else {
    Console.WriteLine("No properties found.");
}

How to get the correct range to set the value to a cell?

Use setValue method of Range class to set the value of particular cell.

function storeValue() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  // ss is now the spreadsheet the script is associated with
  var sheet = ss.getSheets()[0]; // sheets are counted starting from 0
  // sheet is the first worksheet in the spreadsheet
  var cell = sheet.getRange("B2"); 
  cell.setValue(100);
}

You can also select a cell using row and column numbers.

var cell = sheet.getRange(2, 3); // here cell is C2

It's also possible to set value of multiple cells at once.

var values = [
  ["2.000", "1,000,000", "$2.99"]
];

var range = sheet.getRange("B2:D2");
range.setValues(values);

What is the best way to conditionally apply a class?

This will probably get downvoted to oblivion, but here is how I used 1.1.5's ternary operators to switch classes depending on whether a row in a table is the first, middle or last -- except if there is only one row in the table:

<span class="attribute-row" ng-class="(restaurant.Attributes.length === 1) || ($first ? 'attribute-first-row': false || $middle ? 'attribute-middle-row': false || $last ? 'attribute-last-row': false)">
</span>

How to find the Center Coordinate of Rectangle?

We can calculate using mid point of line formula,

centre (x,y) =  new Point((boundRect.tl().x+boundRect.br().x)/2,(boundRect.tl().y+boundRect.br().y)/2)

Event system in Python

We use an EventHook as suggested from Michael Foord in his Event Pattern:

Just add EventHooks to your classes with:

class MyBroadcaster()
    def __init__():
        self.onChange = EventHook()

theBroadcaster = MyBroadcaster()

# add a listener to the event
theBroadcaster.onChange += myFunction

# remove listener from the event
theBroadcaster.onChange -= myFunction

# fire event
theBroadcaster.onChange.fire()

We add the functionality to remove all listener from an object to Michaels class and ended up with this:

class EventHook(object):

    def __init__(self):
        self.__handlers = []

    def __iadd__(self, handler):
        self.__handlers.append(handler)
        return self

    def __isub__(self, handler):
        self.__handlers.remove(handler)
        return self

    def fire(self, *args, **keywargs):
        for handler in self.__handlers:
            handler(*args, **keywargs)

    def clearObjectHandlers(self, inObject):
        for theHandler in self.__handlers:
            if theHandler.im_self == inObject:
                self -= theHandler

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

Starting from version 19.1 they have renamed filenames:

? SmartGit grep -rl 'listx' ./19.1
./19.1/preferences.yml
./19.1/.backup/preferences.yml

It is possible to delete them to reset the license setting.

input() error - NameError: name '...' is not defined

Here is an input function which is compatible with both Python 2.7 and Python 3+: (Slightly modified answer by @Hardian) to avoid UnboundLocalError: local variable 'input' referenced before assignment error

def input_compatible(prompt=None):
    try:
        input_func = raw_input
    except NameError:
        input_func = input
    return input_func(prompt)

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

Image Greyscale with CSS & re-color on mouse-over?

You can use a sprite which has both version—the colored and the monochrome—stored into it.

How can I set selected option selected in vue.js 2?

<select v-model="challan.warehouse_id">
<option value="">Select Warehouse</option>
<option v-for="warehouse in warehouses" v-bind:value="warehouse.id"  >
   {{ warehouse.name }}
</option>

Here "challan.warehouse_id" come from "challan" object you get from:

editChallan: function() {
    let that = this;
    axios.post('/api/challan_list/get_challan_data', {
    challan_id: that.challan_id
 })
 .then(function (response) {
    that.challan = response.data;
 })
 .catch(function (error) {
    that.errors = error;
  }); 
 }

Linq to SQL .Sum() without group ... into

What about:

itemsInCart.AsEnumerable().Sum(o=>o.Price);

AsEnumerable makes the difference, this query will execute locally (Linq To Objects).

Setting DataContext in XAML in WPF

There are several issues here.

  1. You can't assign DataContext as DataContext="{Binding Employee}" because it's a complex object which can't be assigned as string. So you have to use <Window.DataContext></Window.DataContext> syntax.
  2. You assign the class that represents the data context object to the view, not an individual property so {Binding Employee} is invalid here, you just have to specify an object.
  3. Now when you assign data context using valid syntax like below
   <Window.DataContext>
      <local:Employee/>
   </Window.DataContext>

know that you are creating a new instance of the Employee class and assigning it as the data context object. You may well have nothing in default constructor so nothing will show up. But then how do you manage it in code behind file? You have typecast the DataContext.

    private void my_button_Click(object sender, RoutedEventArgs e)
    {
        Employee e = (Employee) DataContext;
    }
  1. A second way is to assign the data context in the code behind file itself. The advantage then is your code behind file already knows it and can work with it.

    public partial class MainWindow : Window
    {
       Employee employee = new Employee();
    
       public MainWindow()
       {
           InitializeComponent();
    
           DataContext = employee;
       }
    }
    

How do I pass a unique_ptr argument to a constructor or a function?

Edit: This answer is wrong, even though, strictly speaking, the code works. I'm only leaving it here because the discussion under it is too useful. This other answer is the best answer given at the time I last edited this: How do I pass a unique_ptr argument to a constructor or a function?

The basic idea of ::std::move is that people who are passing you the unique_ptr should be using it to express the knowledge that they know the unique_ptr they're passing in will lose ownership.

This means you should be using an rvalue reference to a unique_ptr in your methods, not a unique_ptr itself. This won't work anyway because passing in a plain old unique_ptr would require making a copy, and that's explicitly forbidden in the interface for unique_ptr. Interestingly enough, using a named rvalue reference turns it back into an lvalue again, so you need to use ::std::move inside your methods as well.

This means your two methods should look like this:

Base(Base::UPtr &&n) : next(::std::move(n)) {} // Spaces for readability

void setNext(Base::UPtr &&n) { next = ::std::move(n); }

Then people using the methods would do this:

Base::UPtr objptr{ new Base; }
Base::UPtr objptr2{ new Base; }
Base fred(::std::move(objptr)); // objptr now loses ownership
fred.setNext(::std::move(objptr2)); // objptr2 now loses ownership

As you see, the ::std::move expresses that the pointer is going to lose ownership at the point where it's most relevant and helpful to know. If this happened invisibly, it would be very confusing for people using your class to have objptr suddenly lose ownership for no readily apparent reason.

adding multiple entries to a HashMap at once in one statement

Another approach may be writing special function to extract all elements values from one string by regular-expression:

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main (String[] args){
        HashMap<String,Integer> hashMapStringInteger = createHashMapStringIntegerInOneStat("'one' => '1', 'two' => '2' , 'three'=>'3'  ");

        System.out.println(hashMapStringInteger); // {one=1, two=2, three=3}
    }

    private static HashMap<String, Integer> createHashMapStringIntegerInOneStat(String str) {
        HashMap<String, Integer> returnVar = new HashMap<String, Integer>();

        String currentStr = str;
        Pattern pattern1 = Pattern.compile("^\\s*'([^']*)'\\s*=\\s*>\\s*'([^']*)'\\s*,?\\s*(.*)$");

        // Parse all elements in the given string.
        boolean thereIsMore = true;
        while (thereIsMore){
            Matcher matcher = pattern1.matcher(currentStr);
            if (matcher.find()) {
                returnVar.put(matcher.group(1),Integer.valueOf(matcher.group(2)));
                currentStr = matcher.group(3);
            }
            else{
                thereIsMore = false;
            }
        }

        // Validate that all elements in the given string were parsed properly
        if (currentStr.length() > 0){
            System.out.println("WARNING: Problematic string format. given String: " + str);
        }

        return returnVar;
    }
}

SQL Group By with an Order By

You can get around this limit with the deprecated syntax: ORDER BY 1 DESC

This syntax is not deprecated at all, it's E121-03 from SQL99.

How to make a div with no content have a width?

Try to add display:block; to your test1

Android/Java - Date Difference in days

One another way:

public static int numberOfDaysBetweenDates(Calendar fromDay, Calendar toDay) {
        fromDay = calendarStartOfDay(fromDay);
        toDay = calendarStartOfDay(toDay);
        long from = fromDay.getTimeInMillis();
        long to = toDay.getTimeInMillis();
        return (int) TimeUnit.MILLISECONDS.toDays(to - from);
    }

How to scroll page in flutter

you can scroll any part of content in two ways ...

  1. you can use the list view directly
  2. or SingleChildScrollView

most of the time i use List view directly when ever there is a keybord intraction in that specific screen so that the content dont get overlap by the keyboard and more over scrolls to top ....

this trick will be helpful many a times....

Get a list of dates between two dates

select * from table_name where col_Date between '2011/02/25' AND DATEADD(s,-1,DATEADD(d,1,'2011/02/27'))

Here, first add a day to the current endDate, it will be 2011-02-28 00:00:00, then you subtract one second to make the end date 2011-02-27 23:59:59. By doing this, you can get all the dates between the given intervals.

output:
2011/02/25
2011/02/26
2011/02/27

How to get the last N records in mongodb?

If I understand your question, you need to sort in ascending order.

Assuming you have some id or date field called "x" you would do ...

.sort()


db.foo.find().sort({x:1});

The 1 will sort ascending (oldest to newest) and -1 will sort descending (newest to oldest.)

If you use the auto created _id field it has a date embedded in it ... so you can use that to order by ...

db.foo.find().sort({_id:1});

That will return back all your documents sorted from oldest to newest.

Natural Order


You can also use a Natural Order mentioned above ...

db.foo.find().sort({$natural:1});

Again, using 1 or -1 depending on the order you want.

Use .limit()


Lastly, it's good practice to add a limit when doing this sort of wide open query so you could do either ...

db.foo.find().sort({_id:1}).limit(50);

or

db.foo.find().sort({$natural:1}).limit(50);

Accessing Google Account Id /username via Android

Retrieve profile information for a signed-in user Use the GoogleSignInResult.getSignInAccount method to request profile information for the currently signed in user. You can call the getSignInAccount method after the sign-in intent succeeds.

GoogleSignInResult result = 
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();

How to do a PUT request with curl?

I am late to this thread, but I too had a similar requirement. Since my script was constructing the request for curl dynamically, I wanted a similar structure of the command across GET, POST and PUT.

Here is what works for me

For PUT request:

curl --request PUT --url http://localhost:8080/put --header 'content-type: application/x-www-form-urlencoded' --data 'bar=baz&foo=foo1'

For POST request:

curl --request POST --url http://localhost:8080/post --header 'content-type: application/x-www-form-urlencoded' --data 'bar=baz&foo=foo1'

For GET request:

curl --request GET --url 'http://localhost:8080/get?foo=bar&foz=baz'

CSS hide scroll bar, but have element scrollable

if you use sass, you can try this

&::-webkit-scrollbar { 

}

Maximum call stack size exceeded error

I was facing same issue I have resolved it by removing a field name which was used twice on ajax e.g

    jQuery.ajax({
    url : '/search-result',
    data : {
      searchField : searchField,
      searchFieldValue : searchField,
      nid    :  nid,
      indexName : indexName,
      indexType : indexType
    },
.....

JavaFX Location is not set error message

mine was strange... IntelliJ specific quirk.

I looked at my output classes and there was a folder:

x.y.z

instead of

x/y/z

but if you have certain options set in IntelliJ, in the navigator they will both look like x.y.z

so check your output folder if you're scratching your head

Make content horizontally scroll inside a div

if you remove the float: left from the a and add white-space: nowrap to the outer div

#myWorkContent{
    width:530px;
    height:210px;
    border: 13px solid #bed5cd;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}
#myWorkContent a {
    display: inline;
}

this should work for any size or amount of images..

or even:

#myWorkContent a {
    display: inline-block;
    vertical-align: middle;
}

which would also vertically align images of different heights if required

test code

How to build an APK file in Eclipse?

Right click on the project in Eclipse -> Android tools -> Export without signed key. Connect your device. Mount it by sdk/tools.

How do I get class name in PHP?

This will return pure class name even when using namespace:

echo substr(strrchr(__CLASS__, "\\"), 1);    

How to register ASP.NET 2.0 to web server(IIS7)?

If anyone like me is still unable to register ASP.NET with IIS.

You just need to run these three commands one by one in command prompt

cd c:\windows\Microsoft.Net\Framework\v2.0.50727

after that, Run

aspnet_regiis.exe -i -enable

and Finally Reset IIS

iisreset

Hope it helps the person in need... cheers!

How do you define a class of constants in Java?

Or 4. Put them in the class that contains the logic that uses the constants the most

... sorry, couldn't resist ;-)

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

For the sake of completion:

 apply(people[,-1], 2, function(x) sum(x))
#Height Weight 
#   199    425 

input type="submit" Vs button tag are they interchangeable?

The <input type="button"> is just a button and won't do anything by itself. The <input type="submit">, when inside a form element, will submit the form when clicked.

Another useful 'special' button is the <input type="reset"> that will clear the form.

How to unmerge a Git merge?

git revert -m allows to un-merge still keeping the history of both merge and un-do operation. Might be good for documenting probably.

Trying to create a file in Android: open failed: EROFS (Read-only file system)

Google have restricted write access to the external sdcard. From API 19 there is a framework called Storage Access Framework which allows you the set up "contracts" to allow write access.

For further info:

Android - How to use new Storage Access Framework to copy files to external sd card

Set font-weight using Bootstrap classes

I found this on the Bootstrap website, but it really isn't a Bootstrap class, it's just HTML.

<strong>rendered as bold text</strong>

Visual Studio 2010 shortcut to find classes and methods?

Use the "Go To Find Combo Box" with the ">of" command. CTRL+/ or CTRL+D are the standard hotkeys.

For example, go to the combo box (CTRL+/) and type: >of MyClassName. As you type, intellisense will refine the options in the dropdown.

In my experience, this is faster than Navigate To and doesn't bring up another dialog to deal with. Also, this combo box has a lot of other nifty little shortcut commands:

Using the Go To Find Combo Box

This textbox used to be the default on the Standard toolbar in Visual Studio. It was removed in Visual Studio 2012, so you have to add it back using menu Tools ? Customize. The hotkeys may have changed too: I'm not sure since mine are all customized.

Updating a date in Oracle SQL table

Here is how you set the date and time:

update user set expiry_date=TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss') where id=123;

Get Selected value from dropdown using JavaScript

The first thing i noticed is that you have a semi colon just after your closing bracket for your if statement );

You should also try and clean up your if statement by declaring a variable for the answer separately.

function answers() {

var select = document.getElementById("mySelect");
var answer = select.options[select.selectedIndex].value;

    if(answer == "To measure time"){
        alert("Thats correct"); 
    }

}

http://jsfiddle.net/zpdEp/

How to call external url in jquery?

Hi url should be calling a function which in return will give response

$.ajax({
url:'function to call url',
...
...

});

try using/calling API facebook method

How to call javascript from a href?

Using JQuery would be good;

<a href="#" id="youLink">Call JavaScript </a>



$("#yourLink").click(function(e){
//do what ever you want...
});

How do you add an in-app purchase to an iOS application?

I know I am quite late to post this, but I share similar experience when I learned the ropes of IAP model.

In-app purchase is one of the most comprehensive workflow in iOS implemented by Storekit framework. The entire documentation is quite clear if you patience to read it, but is somewhat advanced in nature of technicality.

To summarize:

1 - Request the products - use SKProductRequest & SKProductRequestDelegate classes to issue request for Product IDs and receive them back from your own itunesconnect store.

These SKProducts should be used to populate your store UI which the user can use to buy a specific product.

2 - Issue payment request - use SKPayment & SKPaymentQueue to add payment to the transaction queue.

3 - Monitor transaction queue for status update - use SKPaymentTransactionObserver Protocol's updatedTransactions method to monitor status:

SKPaymentTransactionStatePurchasing - don't do anything
SKPaymentTransactionStatePurchased - unlock product, finish the transaction
SKPaymentTransactionStateFailed - show error, finish the transaction
SKPaymentTransactionStateRestored - unlock product, finish the transaction

4 - Restore button flow - use SKPaymentQueue's restoreCompletedTransactions to accomplish this - step 3 will take care of the rest, along with SKPaymentTransactionObserver's following methods:

paymentQueueRestoreCompletedTransactionsFinished
restoreCompletedTransactionsFailedWithError

Here is a step by step tutorial (authored by me as a result of my own attempts to understand it) that explains it. At the end it also provides code sample that you can directly use.

Here is another one I created to explain certain things that only text could describe in better manner.

How do I add comments to package.json for npm install?

To summarise all of these answers:

  1. Add a single top-level field called // that contains a comment string. This works, but it sucks because you can't put comments near the thing they are commenting on.

  2. Add multiple top-level fields starting with //, e.g. //dependencies that contains a comment string. This is better, but it still only allows you to make top-level comments. You can't comment individual dependencies.

  3. Add echo commands to your scripts. This works, but it sucks because you can only use it in scripts.

These solutions are also all not very readable. They add a ton of visual noise and IDEs will not syntax highlight them as comments.

I think the only reasonable solution is to generate the package.json from another file. The simplest way is to write your JSON as JavaScript and use Node.js to write it to package.json. Save this file as package.json.mjs, chmod +x it, and then you can just run it to generate your package.json.

#!/usr/bin/env node

import { writeFileSync } from "fs";

const config = {
  // TODO: Think of better name.
  name: "foo",
  dependencies: {
    // Bar 2.0 does not work due to bug 12345.
    bar: "^1.2.0",
  },
  // Look at these beautify comments. Perfectly syntax highlighted, you
  // can put them anywhere and there no risk of some tool removing them.
};

writeFileSync("package.json", JSON.stringify({
    "//": "This file is \x40generated from package.json.mjs; do not edit.",
    ...config
  }, null, 2));

It uses the // key to warn people from editing it. \x40generated is deliberate. It turns into @generated in package.json and means some code review systems will collapse that file by default.

It's an extra step in your build system, but it beats all of the other hacks here.

What is the correct syntax for 'else if'?

def function(a):
    if a == '1':
        print ('1a')
    else if a == '2'
        print ('2a')
    else print ('3a')

Should be corrected to:

def function(a):
    if a == '1':
        print('1a')
    elif a == '2':
        print('2a')
    else:
        print('3a')

As you can see, else if should be changed to elif, there should be colons after '2' and else, there should be a new line after the else statement, and close the space between print and the parentheses.

How to apply !important using .css()?

There's no need to go to the complexity of @AramKocharyan's answer, nor the need to insert any style tags dynamically.

Just overwrite style, but you don't have to parse anything, why would you?

// Accepts the hyphenated versions (i.e. not 'cssFloat')
function addStyle(element, property, value, important) {
    // Remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    // Insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

Can't use removeProperty(), because it won't remove !important rules in Chrome.
Can't use element.style[property] = '', because it only accepts camelCase in Firefox.

You could probably make this shorter with jQuery, but this vanilla function will run on modern browsers, Internet Explorer 8, etc.

Check if string begins with something?

Have a look at JavaScript substring() method.

How to use type: "POST" in jsonp ajax call

Here is the JSONP I wrote to share with everyone:

the page to send req
http://c64.tw/r20/eqDiv/fr64.html

please save the srec below to .html youself
c64.tw/r20/eqDiv/src/fr64.txt
the page to resp, please save the srec below to .jsp youself
c64.tw/r20/eqDiv/src/doFr64.txt

or embedded the code in your page:

function callbackForJsonp(resp) {

var elemDivResp = $("#idForDivResp");
elemDivResp.empty();

try {

    elemDivResp.html($("#idForF1").val() + " + " + $("#idForF2").val() + "<br/>");
    elemDivResp.append(" = " + resp.ans + "<br/>");
    elemDivResp.append(" = " + resp.ans2 + "<br/>");

} catch (e) {

    alert("callbackForJsonp=" + e);

}

}

$(document).ready(function() {

var testUrl = "http://c64.tw/r20/eqDiv/doFr64.jsp?callback=?";

$(document.body).prepend("post to " + testUrl + "<br/><br/>");

$("#idForBtnToGo").click(function() {

    $.ajax({

        url : testUrl,
        type : "POST",

        data : {
            f1 : $("#idForF1").val(),
            f2 : $("#idForF2").val(),
            op : "add"
        },

        dataType : "jsonp",
        crossDomain : true,
        //jsonpCallback : "callbackForJsonp",
        success : callbackForJsonp,

        //success : function(resp) {

        //console.log("Yes, you success");
        //callbackForJsonp(resp);

        //},

        error : function(XMLHttpRequest, status, err) {

            console.log(XMLHttpRequest.status + "\n" + err);
            //alert(XMLHttpRequest.status + "\n" + err);

        }

    });

});

});

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

I seconded Matthieu answer

I commented #Listen 443 in httpd-ssl file and apache can be started

Because the file already has VirtualHost default:443

Where are the recorded macros stored in Notepad++?

For Windows 7 macros are stored at C:\Users\Username\AppData\Roaming\Notepad++\shortcuts.xml.

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

Other than the options mentioned above, there are a couple of other Solutions.

1. Modifying the project file (.CsProj) file

MSBuild supports the EnvironmentName Property which can help to set the right environment variable as per the Environment you wish to Deploy. The environment name would be added in the web.config during the Publish phase.

Simply open the project file (*.csProj) and add the following XML.

<!-- Custom Property Group added to add the Environment name during publish
  The EnvironmentName property is used during the publish for the Environment variable in web.config
  -->
  <PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
    <EnvironmentName>Development</EnvironmentName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
    <EnvironmentName>Production</EnvironmentName>
  </PropertyGroup>

Above code would add the environment name as Development for Debug configuration or if no configuration is specified. For any other Configuration the Environment name would be Production in the generated web.config file. More details here

2. Adding the EnvironmentName Property in the publish profiles.

We can add the <EnvironmentName> property in the publish profile as well. Open the publish profile file which is located at the Properties/PublishProfiles/{profilename.pubxml} This will set the Environment name in web.config when the project is published. More Details here

<PropertyGroup>
  <EnvironmentName>Development</EnvironmentName>
</PropertyGroup>

3. Command line options using dotnet publish

Additionaly, we can pass the property EnvironmentName as a command line option to the dotnet publish command. Following command would include the environment variable as Development in the web.config file.

dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development

Shell script to set environment variables

Run the script as source= to run in debug mode as well.

source= ./myscript.sh

jquery - Click event not working for dynamically created button

You could also create the input button in this way:

var button = '<input type="button" id="questionButton" value='+variable+'> <br />';


It might be the syntax of the Button creation that is off somehow.

Android: Create spinner programmatically from array

This worked for me with a string-array named shoes loaded from the projects resources:

Spinner              spinnerCountShoes = (Spinner)findViewById(R.id.spinner_countshoes);
ArrayAdapter<String> spinnerCountShoesArrayAdapter = new ArrayAdapter<String>(
                     this,
                     android.R.layout.simple_spinner_dropdown_item, 
                     getResources().getStringArray(R.array.shoes));
spinnerCountShoes.setAdapter(spinnerCountShoesArrayAdapter);

This is my resource file (res/values/arrays.xml) with the string-array named shoes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="shoes">
        <item>0</item>
        <item>5</item>
        <item>10</item>
        <item>100</item>
        <item>1000</item>
        <item>10000</item>
    </string-array>
</resources>

With this method it's easier to make it multilingual (if necessary).

Popup Message boxes

JOptionPane.showMessageDialog(btn1, "you are clicked save button","title of dialog",2);

btn1 is a JButton variable and its used in this dialog to dialog open position btn1 or textfield etc, by default use null position of the frame.next your message and next is the title of dialog. 2 numbers of alert type icon 3 is the information 1,2,3,4. Ok I hope you understand it

How to pass macro definition from "make" command line arguments (-D) to C source code?

Call make command this way:

make CFLAGS=-Dvar=42

And be sure to use $(CFLAGS) in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make command will override the CFLAGS value already defined the Makefile.

Alternatively you could set -Dvar=42 in another variable than CFLAGS and then reuse this variable in CFLAGS to avoid completely overriding CFLAGS.

Java, looping through result set

The problem with your code is :

     String  show[]= {rs4.getString(1)};
     String actuate[]={rs4.getString(2)};

This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.

Here is one more way to solve this :

    StringBuilder sids = new StringBuilder ();
    StringBuilder lids = new StringBuilder ();

    while (rs4.next()) {
        sids.append(rs4.getString(1)).append(" ");
        lids.append(rs4.getString(2)).append(" ");
    }

    String show[] = sids.toString().split(" "); 
    String actuate[] = lids.toString().split(" ");

These arrays will have all the required element.

How to uninstall pip on OSX?

Since pip is a package, pip uninstall pip Will do it.
EDIT: If that does not work, try sudo -H pip uninstall pip.

com.sun.jdi.InvocationException occurred invoking method

I faced the same problem once. In my case it was because of overridden equals method. One values was coming null.

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

An old thread, but there is another alternative.

Since 9i you can use pipelined table function.

First, create a type as a table of varchar:

CREATE TYPE t_string_max IS TABLE OF VARCHAR2(32767);

Second, wrap your code in a pipelined function declaration:

CREATE FUNCTION fn_foo (bar VARCHAR2) -- your params
  RETURN t_string_max PIPELINED IS 
  -- your vars
BEGIN
  -- your code
END;
/

Replace all DBMS_OUTPUT.PUT_LINE for PIPE ROW.

Finally, call it like this:

SELECT * FROM TABLE(fn_foo('param'));

Hope it helps.

Create a BufferedImage from file and make it TYPE_INT_ARGB

try {
    File img = new File("somefile.png");
    BufferedImage image = ImageIO.read(img ); 
    System.out.println(image);
} catch (IOException e) { 
    e.printStackTrace(); 
}

Example output for my image file:

BufferedImage@5d391d: type = 5 ColorModel: #pixelBits = 24 
numComponents = 3 color 
space = java.awt.color.ICC_ColorSpace@50a649 
transparency = 1 
has alpha = false 
isAlphaPre = false 
ByteInterleavedRaster: 
width = 800 
height = 600 
#numDataElements 3 
dataOff[0] = 2

You can run System.out.println(object); on just about any object and get some information about it.

SmartGit Installation and Usage on Ubuntu

Seems a bit too late, but there is a PPA repository with SmartGit, enjoy! =)

How to get base64 encoded data from html image

You can try following sample http://jsfiddle.net/xKJB8/3/

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

Importing Excel into a DataTable Quickly

In case anyone else is using EPPlus. This implementation is pretty naive, but there are comments that draw attention to such. If you were to layer one more method GetWorkbookAsDataSet() on top it would do what the OP is asking for.

    /// <summary>
    /// Assumption: Worksheet is in table format with no weird padding or blank column headers.
    /// 
    /// Assertion: Duplicate column names will be aliased by appending a sequence number (eg. Column, Column1, Column2)
    /// </summary>
    /// <param name="worksheet"></param>
    /// <returns></returns>
    public static DataTable GetWorksheetAsDataTable(ExcelWorksheet worksheet)
    {
        var dt = new DataTable(worksheet.Name);
        dt.Columns.AddRange(GetDataColumns(worksheet).ToArray());
        var headerOffset = 1; //have to skip header row
        var width = dt.Columns.Count;
        var depth = GetTableDepth(worksheet, headerOffset);
        for (var i = 1; i <= depth; i++)
        {
            var row = dt.NewRow();
            for (var j = 1; j <= width; j++)
            {
                var currentValue = worksheet.Cells[i + headerOffset, j].Value;

                //have to decrement b/c excel is 1 based and datatable is 0 based.
                row[j - 1] = currentValue == null ? null : currentValue.ToString();
            }

            dt.Rows.Add(row);
        }

        return dt;
    }

    /// <summary>
    /// Assumption: There are no null or empty cells in the first column
    /// </summary>
    /// <param name="worksheet"></param>
    /// <returns></returns>
    private static int GetTableDepth(ExcelWorksheet worksheet, int headerOffset)
    {
        var i = 1;
        var j = 1;
        var cellValue = worksheet.Cells[i + headerOffset, j].Value;
        while (cellValue != null)
        {
            i++;
            cellValue = worksheet.Cells[i + headerOffset, j].Value;
        }

        return i - 1; //subtract one because we're going from rownumber (1 based) to depth (0 based)
    }

    private static IEnumerable<DataColumn> GetDataColumns(ExcelWorksheet worksheet)
    {
        return GatherColumnNames(worksheet).Select(x => new DataColumn(x));
    }

    private static IEnumerable<string> GatherColumnNames(ExcelWorksheet worksheet)
    {
        var columns = new List<string>();

        var i = 1;
        var j = 1;
        var columnName = worksheet.Cells[i, j].Value;
        while (columnName != null)
        {
            columns.Add(GetUniqueColumnName(columns, columnName.ToString()));
            j++;
            columnName = worksheet.Cells[i, j].Value;
        }

        return columns;
    }

    private static string GetUniqueColumnName(IEnumerable<string> columnNames, string columnName)
    {
        var colName = columnName;
        var i = 1;
        while (columnNames.Contains(colName))
        {
            colName = columnName + i.ToString();
            i++;
        }

        return colName;
    }

iOS8 Beta Ad-Hoc App Download (itms-services)

I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:

"Cannot install at this time". 

Finally Zillan's link helped me to get apple documentation. So, check:

  1. make sure the internet reachability in your device as you will be in local network/ intranet.
  2. Also make sure the address ax.init.itunes.apple.com is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load).

As soon as I changed the proxy it installed completely. Hope it will help someone.

How to read a specific line using the specific line number from a file in Java?

You can also take a look at LineNumberReader, subclass of BufferedReader. Along with the readline method, it also has setter/getter methods to access line number. Very useful to keep track of the number of lines read, while reading data from file.

How to upgrade rubygems

To update just one gem (and it's dependencies), do:

    bundle update gem-name

But to update just the gem alone (without updating it's dependencies), do

    bundle update --source gem-name

How to crop an image using C#?

You can use Graphics.DrawImage to draw a cropped image onto the graphics object from a bitmap.

Rectangle cropRect = new Rectangle(...);
Bitmap src = Image.FromFile(fileName) as Bitmap;
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);

using(Graphics g = Graphics.FromImage(target))
{
   g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), 
                    cropRect,                        
                    GraphicsUnit.Pixel);
}

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Don't worry! This problem occurs because of the annotation. Instead of Field based access, Property based access solves this problem. The code as follows:

package onetomanymapping;

import java.util.List;

import javax.persistence.*;

@Entity
public class College {
private int collegeId;
private String collegeName;
private List<Student> students;

@OneToMany(targetEntity = Student.class, mappedBy = "college", 
    cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<Student> getStudents() {
    return students;
}

public void setStudents(List<Student> students) {
    this.students = students;
}

@Id
@GeneratedValue
public int getCollegeId() {
    return collegeId;
}

public void setCollegeId(int collegeId) {
    this.collegeId = collegeId;
}

public String getCollegeName() {
    return collegeName;
}

public void setCollegeName(String collegeName) {
    this.collegeName = collegeName;
}

}

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

m2eclipse error

Just go to your user folder, inside it there's a ".m2" folder, open it and delete the folder "repository". Go to eclipse, clean your project, then right click->Maven->Update Project .. and you are ready to go.

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I found I was getting the same error because I had forgot to create referential constraint after creating an association between two entities.

"Line contains NULL byte" in CSV reader (Python)

I've solved a similar problem with an easier solution:

import codecs
csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16'))

The key was using the codecs module to open the file with the UTF-16 encoding, there are a lot more of encodings, check the documentation.

How to center images on a web page for all screen sizes

In your specific case, you can set the containing a element to be:

a {
    display: block;
    text-align: center;
}

JS Bin demo.

What is the correct JSON content type?

The right MIME type is application/json

BUT

I experienced many situations where the browser type or the framework user needed:

text/html

application/javascript

Is there a Google Chrome-only CSS hack?

To work only chrome or safari, try it:

@media screen and (-webkit-min-device-pixel-ratio:0) { 
/* Safari and Chrome */
.myClass {
 color:red;
}

/* Safari only override */
::i-block-chrome,.myClass {
 color:blue;
}}

Dilemma: when to use Fragments vs Activities:

An Activity is a user interface component that are mainly used to construct a single screen of application, and represents the main focus of attention on a screen.

In contrast, Fragments, introduced in Honeycomb(3.0) as tablets emerged with larger screens, are reusable components that are attached to and displayed within activities.

Fragments must be hosted by an activity and an activity can host one or more fragments at a time. And a fragment’s lifecycle is directly affected by its host activity’s lifecycle.

While it’s possible to develop a UI only using Activities, this is generally a bad idea since their code cannot later be reused within other Activities, and cannot support multiple screens. In contrast, these are advantages that come with the use of Fragments: optimized experiences based on device size and well-structured, reusable code.

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Be careful of following this answer's advice. While it solves the problem at hand, it might cause different problems at a later date.

I got the same problem. Apparently the .NET compiler was not loaded to the GAC. What I did to solve it was:

First, in the package manager console type:

PM> Install-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform

Now, for some reason the nice gentlemen in Microsoft have decided not to install it to the GAC for us. You can do it manually by opening the Developer Command Prompt and typing:

gacutil -i "C:\*PATH TO YOUR APP CODE*\bin\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll"

Conclusion

Microsoft try to encourage everyone to do everything with nugets which could be fine without the occasional bugs you run into with the nuget system. Try to use the same project on different solutions, accidentally (or not) update one of the many nugets it uses on one of them, and if you are unlucky you'll see what I mean when you try to build the other solution. On the other hand, putting files in the GAC can also cause future problems since people tend to forget what they put there and then when setting up new environments they forget to include these files. Another possible solution is to put the files in a central folder for 3rd party dlls (even though it's strange to call the compiler 3rd party), which creates problems of broken references when setting up new environments. If you decide to install the dll to the GAC, use caution and remember that you did so. If you don't, download the nuget for each project again and bear all the annoying bugs being caused by it (at least used to happen when I finally got sick of it and just placed the files in the GAC). Both approaches might give you headaches and create problems, it's just a question of which problems you prefer to deal with. Microsoft recommends to use the nuget system, and generally, it's better to listen to them than to an unknown programmer in SO, unless you are completely sick of the nuget system and used to deal with the GAC long enough for it to be a better alternative for you.

How can I remove the top and right axis in matplotlib?

Alternatively, this

def simpleaxis(ax):
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

seems to achieve the same effect on an axis without losing rotated label support.

(Matplotlib 1.0.1; solution inspired by this).

Spring Boot Remove Whitelabel Error Page

You can remove it completely by specifying:

import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
...
@Configuration
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public static MainApp { ... }

However, do note that doing so will probably cause servlet container's whitelabel pages to show up instead :)


EDIT: Another way to do this is via application.yaml. Just put in the value:

spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration

Documentation

For Spring Boot < 2.0, the class is located in package org.springframework.boot.autoconfigure.web.

React component initialize state from props

you could use key value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled read this https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

Line Break in XML formatting?

Take note: I have seen other posts that say &#xA; will give you a paragraph break, which oddly enough works in the Android xml String.xml file, but will NOT show up in a device when testing (no breaks at all show up). Therefore, the \n shows up on both.

how to use font awesome in own css?

Try this way. In your css file change font-family: FontAwesome into font-family: "FontAwesome"; or font-family: 'FontAwesome';. I've solved the same problem using this method.

What does jQuery.fn mean?

In jQuery, the fn property is just an alias to the prototype property.

The jQuery identifier (or $) is just a constructor function, and all instances created with it, inherit from the constructor's prototype.

A simple constructor function:

function Test() {
  this.a = 'a';
}
Test.prototype.b = 'b';

var test = new Test(); 
test.a; // "a", own property
test.b; // "b", inherited property

A simple structure that resembles the architecture of jQuery:

(function() {
  var foo = function(arg) { // core constructor
    // ensure to use the `new` operator
    if (!(this instanceof foo))
      return new foo(arg);
    // store an argument for this example
    this.myArg = arg;
    //..
  };

  // create `fn` alias to `prototype` property
  foo.fn = foo.prototype = {
    init: function () {/*...*/}
    //...
  };

  // expose the library
  window.foo = foo;
})();

// Extension:

foo.fn.myPlugin = function () {
  alert(this.myArg);
  return this; // return `this` for chainability
};

foo("bar").myPlugin(); // alerts "bar"

For homebrew mysql installs, where's my.cnf?

run

sudo find / -name my.cnf

Usually the first result is the correct one. Should be in

/usr/local/etc/

Excel: the Incredible Shrinking and Expanding Controls

Although there are clearly numerous reasons for this behavior, several answers point to issues with scaling and screen resolutions. One workaround is to use the following functions to resize and anchor the controls to a specific cell:

Sub ResizeCombo(ByRef cbo As Shape, ByVal rw As Long, ByVal cl As Long, ByVal wid As Long)        
    cbo.Height = Intake.Cells(rw, cl).Height - 1
    cbo.Top = Intake.Cells(rw, cl).Top + 1
    cbo.Left = Intake.Cells(rw, cl).Left + 1
    cbo.Width = wid    
End Sub

Sub ResizeCheckbox(ByRef cbo As Shape, ByVal rw As Long, ByVal cl As Long)
    cbo.Height = Intake.Cells(rw, cl).Height - 1
    cbo.Top = Intake.Cells(rw, cl).Top + 1
    cbo.Left = Intake.Cells(rw, cl).Left + 6
    cbo.Width = Intake.Cells(rw, cl).MergeArea.Width - 7        
End Sub

Sub ResizeCombos()
    ResizeCombo Intake.Shapes("School"), 11, 1, 144

    ResizeCheckbox Intake.Shapes("cbReading"), 70, 1

    ''ResizeCombo also works for option buttons
    ResizeCombo Intake.Shapes("obGenderMale"), 20, 8, 45
    ResizeCombo Intake.Shapes("obGenderFemale"), 20, 9,50

HOWEVER, recently this workaround stopped working. I've been banging against it for days until I discovered that the zoom level of the sheet had been adjusted to 105%! Resetting it to 100% resolved the problem. However what if the user needs a higher zoom level? I figured out that I can change the zoom after resizing and things stay where they were meant to. My calling function now looks like this:

Sub refresh()
    OldZoom = ActiveWindow.Zoom
    ActiveWindow.Zoom = 100
    Call ResizeCombos
    ActiveWindow.Zoom = OldZoom
End Sub

So far it is working!

How can I use "e" (Euler's number) and power operation in python 2.7

Python's power operator is ** and Euler's number is math.e, so:

 from math import e
 x.append(1-e**(-value1**2/2*value2**2))

Travel/Hotel API's?

You could probably trying using Yahoo or Google's APIs. They are generic, but by specifying the right set of parameters, you could probably narrow down the results to just hotels. Check out Yahoo's Local Search API and Google's Local Search API

How to generate components in a specific folder with Angular CLI?

The above options were not working for me because unlike creating a directory or file in the terminal, when the CLI generates a component, it adds the path src/app by default to the path you enter.

If I generate the component from my main app folder like so (WRONG WAY)

ng g c ./src/app/child/grandchild 

the component that was generated was this:

src/app/src/app/child/grandchild.component.ts

so I only had to type

ng g c child/grandchild 

Hopefully this helps someone

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

select development team in both project and target rest all things set to automatic then it will work

Get first day of week in PHP?

$today_day = date('D'); //Or add your own date
$start_of_week = date('Ymd');
$end_of_week = date('Ymd');

if($today_day != "Mon")
    $start_of_week = date('Ymd', strtotime("last monday"));

if($today_day != "Sun")
                    $end_of_week = date('Ymd', strtotime("next sunday"));

How to load up CSS files using Javascript?

There is a general jquery plugin that loads css and JS files synch and asych on demand. It also keeps track off what is already been loaded :) see: http://code.google.com/p/rloader/

How to parse JSON array in jQuery?

Do NOT eval. use a real parser, i.e., from json.org

How to execute a Windows command on a remote PC?

psexec \\RemoteComputer cmd.exe

or use ssh or TeamViewer or RemoteDesktop!

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

Ted, as you probably found out, you unfortunately can't do that on Android. Dialogs are modal, but asynchronous, and it will definitely disrupt the sequence you're trying to establish as you would have done on .NET (or Windows for that matter). You will have to twist your code around and break some logic that would have been very easy to follow based on your example.

Another very simple example is to save data in a file, only to find out that the file is already there and asking to overwrite it or not. Instead of displaying a dialog and having an if statement to act upon the result (Yes/No), you will have to use callbacks (called listeners in Java) and split your logic into several functions.

On Windows, when a dialog is shown, the message pump continues in the background (only the current message being processed is on hold), and that works just fine. That allows users to move your app and let is repaint while you're displaying a dialog box for example. WinMo supports synchronous modal dialogs, so does BlackBerry but just not Android.

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.

Android selector & text color

Here is the example of selector. If you use eclipse , it does not suggest something when you click ctrl and space both :/ you must type it.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_default_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/btn_default_selected"
    android:state_focused="true"
    android:state_enabled="true"
    android:state_window_focused="true"  />
<item android:drawable="@drawable/btn_default_normal" />

You can look at for reference;

http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

How to write and read a file with a HashMap?

The simplest solution that I can think of is using Properties class.

Saving the map:

Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();

for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
    properties.put(entry.getKey(), entry.getValue());
}

properties.store(new FileOutputStream("data.properties"), null);

Loading the map:

Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));

for (String key : properties.stringPropertyNames()) {
   ldapContent.put(key, properties.get(key).toString());
}

EDIT:

if your map contains plaintext values, they will be visible if you open file data via any text editor, which is not the case if you serialize the map:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();

EDIT2:

instead of for loop (as suggested by OldCurmudgeon) in saving example:

properties.putAll(ldapContent);

however, for the loading example this is the best that can be done:

ldapContent = new HashMap<Object, Object>(properties);

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

Solved the problem by upgrading the dependency to below version

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>

Case Function Equivalent in Excel

Recently I unfortunately had to work with Excel 2010 again for a while and I missed the SWITCH function a lot. I came up with the following to try to minimize my pain:

=CHOOSE(SUM((A1={"a";"b";"c"})*ROW(INDIRECT(1&":"&3))),1,2,3)
CTRL+SHIFT+ENTER

where A1 is where your condition lies (it could be a formula, whatever). The good thing is that we just have to provide the condition once (just like SWITCH) and the cases (in this example: a,b,c) and results (in this example: 1,2,3) are ordered, which makes it easy to reason about.

Here is how it works:

  • Cond={"c1";"c2";...;"cn"} returns a N-vector of TRUE or FALSE (with behaves like 1s and 0s)
  • ROW(INDIRECT(1&":"&n)) returns a N-vector of ordered numbers: 1;2;3;...;n
  • The multiplication of both vectors will return lots of zeros and a number (position) where the condition was matched
  • SUM just transforms this vector with zeros and a position into just a single number, which CHOOSE then can use
  • If you want to add another condition, just remember to increment the last number inside INDIRECT
  • If you want an ELSE case, just wrap it inside an IFERROR formula
  • The formula will not behave properly if you provide the same condition more than once, but I guess nobody would want to do that anyway

How to force Laravel Project to use HTTPS for all routes?

Add this to your .htaccess code

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]

Replace www.yourdomain.com with your domain name. This will force all the urls of your domain to use https. Make sure you have https certificate installed and configured on your domain. If you do not see https in green as secure, press f12 on chrome and fix all the mixed errors in the console tab.

Hope this helps!

Room persistance library. Delete all

Here is how I have done it in Kotlin.

  1. Inject room db in the activity using DI (Koin).

     private val appDB: AppDB by inject()
    
  2. Then you can simply call clearAllTables()

private fun clearRoomDB() {
    GlobalScope.launch {
        appDB.clearAllTables()
        preferences.put(PreferenceConstants.IS_UPLOADCATEGORIES_SAVED_TO_DB, false)
        preferences.put(PreferenceConstants.IS_MEMBERHANDBOOK_SAVED_TO_DB, false)
    }
}

How to change Java version used by TOMCAT?

You can change the JDK or JRE location using the following steps:

  1. open the terminal or cmd.
  2. go to the [tomcat-home]\bin directory.
    ex: c:\tomcat8\bin
  3. write the following command: Tomcat8W //ES//Tomcat8
  4. will open dialog, select the java tab(top pane).
  5. change the Java virtual Machine value.
  6. click OK.

note: in Apache TomEE same steps, but step (3) the command must be: TomEE //ES

how to call url of any other website in php

use curl php library: http://php.net/manual/en/book.curl.php

direct example: CURL_EXEC:

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

css absolute position won't work with margin-left:auto margin-right: auto

I already had this same issue and I've got the solution writing a container (.divtagABS-container, in your case) absolutely positioned and then relatively positioning the content inside it (.divtagABS, in your case).

Done! The margin-left and margin-right AUTO for your .divtagABS will now work.

How do I delete everything below row X in VBA/Excel?

Another option is Sheet1.Rows(x & ":" & Sheet1.Rows.Count).ClearContents (or .Clear). The reason you might want to use this method instead of .Delete is because any cells with dependencies in the deleted range (e.g. formulas that refer to those cells, even if empty) will end up showing #REF. This method will preserve formula references to the cleared cells.

Add and remove attribute with jquery

First you to add a class then remove id

<script type="text/javascript">
$(document).ready(function(){   
 $("#page_navigation1").addClass("page_navigation");        

 $("#add").click(function(){
        $(".page_navigation").attr("id","page_navigation1");
    });     
    $("#remove").click(function(){
        $(".page_navigation").removeAttr("id");
    });     
  });
</script>

C++ - How to append a char to char*?

Remove those char * ret declarations inside if blocks which hide outer ret. Therefor you have memory leak and on the other hand un-allocated memory for ret.

To compare a c-style string you should use strcmp(array,"") not array!="". Your final code should looks like below:

char* appendCharToCharArray(char* array, char a)
{
    size_t len = strlen(array);

    char* ret = new char[len+2];

    strcpy(ret, array);    
    ret[len] = a;
    ret[len+1] = '\0';

    return ret;
}

Note that, you must handle the allocated memory of returned ret somewhere by delete[] it.

 

Why you don't use std::string? it has .append method to append a character at the end of a string:

std::string str;

str.append('x');
// or
str += x;

How to get hostname from IP (Linux)?

To find a hostname in your local network by IP address you can use:

nmblookup -A <ip>

To find a hostname on the internet you could use the host program:

host <ip>

Or you can install nbtscan by running:

sudo apt-get install nbtscan

And use:

nbtscan <ip>

*Taken from https://askubuntu.com/questions/205063/command-to-get-the-hostname-of-remote-server-using-ip-address/205067#205067

Update 2018-05-13

You can query a name server with nslookup. It works both ways!

nslookup <IP>
nslookup <hostname>

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

I had the similar issue......to solve this what I did was to uninstall the ODP. Net and re-install in the same directory as oracle server......with server option you will notice that most of the products are already installed (while 12c database installation) so just select the other features and finally finish the installation....

Please note that this workaround works only if you have installed 12c on the same machine i.e. on your laptop............

If your database is located on the server machine other than your laptop then please select client option and not the server and then include TNS_ADMIN in your app.config and do not forget to specify the version...

since my installation is on my laptop so my App.config is as below:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>
</configuration>


 /////////the below code is a sample from oracle company////////////////


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;

///copy these lines in a button click event 
    string constr = "User Id=system; Password=manager; Data Source=orcl;";
// Click here and then press F9 to insert a breakpoint
        DbProviderFactory factory =
    DbProviderFactories.GetFactory("Oracle.ManagedDataAccess.Client");
            using (DbConnection conn = factory.CreateConnection())
            {
                conn.ConnectionString = constr;
                try
                {
                    conn.Open();
                    OracleCommand cmd = (OracleCommand)factory.CreateCommand();
                    cmd.Connection = (OracleConnection)conn;

//to gain access to ROWIDs of the table
//cmd.AddRowid = true;
                    cmd.CommandText = "select * from all_users";

                    OracleDataReader reader = cmd.ExecuteReader();

                    int visFC = reader.VisibleFieldCount; //Results in 2
                    int hidFC = reader.HiddenFieldCount;  // Results in 1

                    MessageBox.Show(" Visible field count: " + visFC);

                    MessageBox.Show(" Hidden field count: " + hidFC);


                    reader.Dispose();
                    cmd.Dispose();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                      MessageBox.Show(ex.StackTrace);
                }
            }

How to override !important?

The !important should only be used when you have selectors in your style sheet with conflicting specificity.

But even when you have conflicting specificity, it is better to create a more specific selector for the exception. In your case it's better to have a class in your HTML which you can use to create a more specific selector which doesn't need the !important rule.

td.a-semantic-class-name { height: 100px; }

I personally never use !important in my style sheets. Remember that the C in CSS is for cascading. Using !important will break this.

Simulate delayed and dropped packets on Linux

One of my colleagues uses tc to do this. Refer to the man page for more information. You can see an example of its usage here.

/etc/apt/sources.list" E212: Can't open file for writing

I got this error when my directory path is incorrect, ensure your directory names and path are correct

Swapping two variable value without using third variable

If you change a little the question to ask about 2 assembly registers instead of variables, you can use also the xchg operation as one option, and the stack operation as another one.

Private class declaration

To answer your question:

If we can have inner private class then why can't we have outer private class...?

You can, the distinction is that the inner class is at the "class" access level, whereas the "outer" class is at the "package" access level. From the Oracle Tutorials:

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

Thus, package-private (declaring no modifier) is the effect you would expect from declaring an "outer" class private, the syntax is just different.

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

If you want to return a format mm/dd/yyyy, then use 101 instead of 103: CONVERT(VARCHAR(10), [MyDate], 101)

Export to CSV via PHP

You can export the date using this command.

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

First you must load the data from the mysql server in to a array

Formatting code in Notepad++

If all you need is alignment, try the plugin called Code Alignment.

You can get it from the built-in plugin manager in Notepad++.

Writing unit tests in Python: How do I start?

The free Python book Dive Into Python has a chapter on unit testing that you might find useful.

If you follow modern practices you should probably write the tests while you are writing your project, and not wait until your project is nearly finished.

Bit late now, but now you know for next time. :)

How to print all key and values from HashMap in Android?

You can do it easier with Gson:

Log.i(TAG, "SomeText: " + new Gson().toJson(yourMap));

The result will look like:

I/YOURTAG: SomeText: {"key1":"value1","key2":"value2"}

PersistenceContext EntityManager injection NullPointerException

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

Pure Javascript listen to input value change

This is what events are for.

HTMLInputElementObject.addEventListener('input', function (evt) {
    something(this.value);
});

RegEx to match stuff between parentheses

If s is your string:

s.replace(/^[^(]*\(/, "") // trim everything before first parenthesis
 .replace(/\)[^(]*$/, "") // trim everything after last parenthesis
 .split(/\)[^(]*\(/);      // split between parenthesis

Android on-screen keyboard auto popping up

You can use either this in the onCreate() method of the activity

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 

or paste this code in the Activity tags in AndroidManifest.xml

android:windowSoftInputMode="stateVisible"

Delete a row from a table by id

From this post, try this javascript:

function removeRow(id) {
  var tr = document.getElementById(id);
  if (tr) {
    if (tr.nodeName == 'TR') {
      var tbl = tr; // Look up the hierarchy for TABLE
      while (tbl != document && tbl.nodeName != 'TABLE') {
        tbl = tbl.parentNode;
      }

      if (tbl && tbl.nodeName == 'TABLE') {
        while (tr.hasChildNodes()) {
          tr.removeChild( tr.lastChild );
        }
      tr.parentNode.removeChild( tr );
      }
    } else {
      alert( 'Specified document element is not a TR. id=' + id );
    }
  } else {
    alert( 'Specified document element is not found. id=' + id );
  }
}

I tried this javascript in a test page and it worked for me in Firefox.

Unity 2d jumping script

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly. Hope it helps

When to use dynamic vs. static libraries

A static library must be linked into the final executable; it becomes part of the executable and follows it wherever it goes. A dynamic library is loaded every time the executable is executed and remains separate from the executable as a DLL file.

You would use a DLL when you want to be able to change the functionality provided by the library without having to re-link the executable (just replace the DLL file, without having to replace the executable file).

You would use a static library whenever you don't have a reason to use a dynamic library.

How to install JQ on Mac by command-line?

For most it is a breeze, however like you I had a difficult time installing jq

The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/

However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system

What worked for me was removing all previous installs then pip install jq

Difference between document.addEventListener and window.addEventListener?

You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window and document both fit the bill (with just a few differences).

From mozilla dev network:

addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.

So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.

ETag vs Header Expires

ETag is used to determine whether a resource should use the copy one. and Expires Header like Cache-Control is told the client that before the cache decades, client should fetch the local resource.

In modern sites, There are often offer a file named hash, like app.98a3cf23.js, so that it's a good practice to use Expires Header. Besides this, it also reduce the cost of network.

Hope it helps ;)

Psql could not connect to server: No such file or directory, 5432 error?

I recommend you should clarify port that postgres. In my case I didn't know which port postgres was running on.

lsof -i | grep 'post'

then you can know which port is listening.

psql -U postgres -p "port_in_use"

with port option, might be answer. you can use psql.

Get the records of last month in SQL server

You can get the last month records with this query

SELECT * FROM dbo.member d 
WHERE  CONVERT(DATE, date_created,101)>=CONVERT(DATE,DATEADD(m, datediff(m, 0, current_timestamp)-1, 0)) 
and CONVERT(DATE, date_created,101) < CONVERT(DATE, DATEADD(m, datediff(m, 0, current_timestamp)-1, 0),101) 

How to tell which row number is clicked in a table?

$('tr').click(function(){
 alert( $('tr').index(this) );
});

For first tr, it alerts 0. If you want to alert 1, you can add 1 to index.

Is it possible to run an .exe or .bat file on 'onclick' in HTML

Here's what I did. I wanted a HTML page setup on our network so I wouldn't have to navigate to various folders to install or upgrade our apps. So what I did was setup a .bat file on our "shared" drive that everyone has access to, in that .bat file I had this code:

start /d "\\server\Software\" setup.exe

The HTML code was:

<input type="button" value="Launch Installer" onclick="window.open('file:///S:Test/Test.bat')" />

(make sure your slashes are correct, I had them the other way and it didn't work)

I preferred to launch the EXE directly but that wasn't possible, but the .bat file allowed me around that. Wish it worked in FF or Chrome, but only IE.

Get user location by IP address

Return country

static public string GetCountry()
{
    return new WebClient().DownloadString("http://api.hostip.info/country.php");
}

Usage:

Console.WriteLine(GetCountry()); // will return short code for your country

Return info

static public string GetInfo()
{
    return new WebClient().DownloadString("http://api.hostip.info/get_json.php");
}

Usage:

Console.WriteLine(GetInfo()); 
// Example:
// {
//    "country_name":"COUNTRY NAME",
//    "country_code":"COUNTRY CODE",
//    "city":"City",
//    "ip":"XX.XXX.XX.XXX"
// }

How to add images to README.md on GitHub?

You can link to images in your project from README.md (or externally) using the alternative github CDN link.

The URL will look like this:

https://cdn.rawgit.com/<USER>/<REPO>/<BRANCH>/<PATH>/<TO>/<FILE>

I have an SVG image in my project, and when I reference it in my Python project documentation, it does not render.

Project link

Here is the project link to the file (does not render as an image):

https://github.com/jongracecox/anybadge/blob/master/examples/awesomeness.svg

Example embedded image: image

Raw link

Here is the RAW link to the file (still does not render as an image):

https://raw.githubusercontent.com/jongracecox/anybadge/master/examples/awesomeness.svg

Example embedded image: image

CDN link

Using the CDN link, I can link to the file using (renders as an image):

https://cdn.rawgit.com/jongracecox/anybadge/master/examples/awesomeness.svg

Example embedded image: image

This is how I am able to use images from my project in both my README.md file, and in my PyPi project reStructredText doucmentation (here)

Difference Between Select and SelectMany

Here is a code example with an initialized small collection for testing:

class Program
{
    static void Main(string[] args)
    {
        List<Order> orders = new List<Order>
        {
            new Order
            {
                OrderID = "orderID1",
                OrderLines = new List<OrderLine>
                {
                    new OrderLine
                    {
                        ProductSKU = "SKU1",
                        Quantity = 1
                    },
                    new OrderLine
                    {
                        ProductSKU = "SKU2",
                        Quantity = 2
                    },
                    new OrderLine
                    {
                        ProductSKU = "SKU3",
                        Quantity = 3
                    }
                }
            },
            new Order
            {
                OrderID = "orderID2",
                OrderLines = new List<OrderLine>
                {
                    new OrderLine
                    {
                        ProductSKU = "SKU4",
                        Quantity = 4
                    },
                    new OrderLine
                    {
                        ProductSKU = "SKU5",
                        Quantity = 5
                    }
                }
            }
        };

        //required result is the list of all SKUs in orders
        List<string> allSKUs = new List<string>();

        //With Select case 2 foreach loops are required
        var flattenedOrdersLinesSelectCase = orders.Select(o => o.OrderLines);
        foreach (var flattenedOrderLine in flattenedOrdersLinesSelectCase)
        {
            foreach (OrderLine orderLine in flattenedOrderLine)
            {
                allSKUs.Add(orderLine.ProductSKU);
            }
        }

        //With SelectMany case only one foreach loop is required
        allSKUs = new List<string>();
        var flattenedOrdersLinesSelectManyCase = orders.SelectMany(o => o.OrderLines);
        foreach (var flattenedOrderLine in flattenedOrdersLinesSelectManyCase)
        {
            allSKUs.Add(flattenedOrderLine.ProductSKU);
        }

       //If the required result is flattened list which has OrderID, ProductSKU and Quantity,
       //SelectMany with selector is very helpful to get the required result
       //and allows avoiding own For loops what according to my experience do code faster when
       // hundreds of thousands of data rows must be operated
        List<OrderLineForReport> ordersLinesForReport = (List<OrderLineForReport>)orders.SelectMany(o => o.OrderLines,
            (o, ol) => new OrderLineForReport
            {
                OrderID = o.OrderID,
                ProductSKU = ol.ProductSKU,
                Quantity = ol.Quantity
            }).ToList();
    }
}
class Order
{
    public string OrderID { get; set; }
    public List<OrderLine> OrderLines { get; set; }
}
class OrderLine
{
    public string ProductSKU { get; set; }
    public int Quantity { get; set; }
}
class OrderLineForReport
{
    public string OrderID { get; set; }
    public string ProductSKU { get; set; }
    public int Quantity { get; set; }
}

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

Version 1.1.1 is the correct version for Yosemite. You need to download this directly from intel's site: https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.

The one downloaded by SDK Manager is the older version (1.1.0). If you still want to run with version 1.1.0 - refer to the solution here - http://www.csell.net/2014/09/03/VTNX_Not_Enabled/

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

Quiet Late though!.

This method is properly tested and it converts the excel to DataSet.

public DataSet Dtl()
        {
            //Instance reference for Excel Application
            Microsoft.Office.Interop.Excel.Application objXL = null;        
            //Workbook refrence
            Microsoft.Office.Interop.Excel.Workbook objWB = null;
            DataSet ds = new DataSet();
            try
            {
                objXL = new Microsoft.Office.Interop.Excel.Application();
                objWB = objXL.Workbooks.Open(@"Book1.xlsx");//Your path to excel file.
                foreach (Microsoft.Office.Interop.Excel.Worksheet objSHT in objWB.Worksheets)
                {
                    int rows = objSHT.UsedRange.Rows.Count;
                    int cols = objSHT.UsedRange.Columns.Count;
                    DataTable dt = new DataTable();
                    int noofrow = 1;
                    //If 1st Row Contains unique Headers for datatable include this part else remove it
                    //Start
                    for (int c = 1; c <= cols; c++)
                    {
                        string colname = objSHT.Cells[1, c].Text;
                        dt.Columns.Add(colname);
                        noofrow = 2;
                    }
                    //END
                    for (int r = noofrow; r <= rows; r++)
                    {
                        DataRow dr = dt.NewRow();
                        for (int c = 1; c <= cols; c++)
                        {
                            dr[c - 1] = objSHT.Cells[r, c].Text;
                        }
                        dt.Rows.Add(dr);
                    }
                   ds.Tables.Add(dt);
                }
                //Closing workbook
                objWB.Close();
                //Closing excel application
                objXL.Quit();
                return ds;
            }

            catch (Exception ex)
            {
               objWB.Saved = true;
                //Closing work book
                objWB.Close();
                //Closing excel application
                objXL.Quit();
                //Response.Write("Illegal permission");
                return ds;
            }
        }

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)

mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM tin3;
+----+------------+
| id | val        |
+----+------------+
|  1 | 0000000012 |
|  2 | 0000000007 |
|  4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)

mysql>

mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
|          10 |
+-------------+
1 row in set (0.01 sec)


mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
|     8 |
+-------+
1 row in set (0.00 sec)

What exactly does the .join() method do?

Look carefully at your output:

5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
^                 ^                 ^

I've highlighted the "5", "9", "5" of your original string. The Python join() method is a string method, and takes a list of things to join with the string. A simpler example might help explain:

>>> ",".join(["a", "b", "c"])
'a,b,c'

The "," is inserted between each element of the given list. In your case, your "list" is the string representation "595", which is treated as the list ["5", "9", "5"].

It appears that you're looking for + instead:

print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid

How to call function that takes an argument in a Django template?

if you have an object you can define it as @property so you can get results without a call, e.g.

class Item:
    @property
    def results(self):
        return something

then in the template:

<% for result in item.results %>
...
<% endfor %>

Bootstrap 3 Horizontal Divider (not in a dropdown)

Currently it only works for the .dropdown-menu:

.dropdown-menu .divider {
  height: 1px;
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

If you want it for other use, in your own css, following the bootstrap.css create another one:

.divider {
  height: 1px;
  width:100%;
  display:block; /* for use on default inline elements like span */
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

Can vue-router open a link in a new tab?

This works for me:

In HTML template: <a target="_blank" :href="url" @click.stop>your_name</a>

In mounted(): this.url = `${window.location.origin}/your_page_name`;

How do I set adaptive multiline UILabel text?

With Graphical User Interface (GUI) in Xcode, you can do the following:

  • Go to "Attribute Inspector" and set Lines value to 0. By default, it is set to 1.
  • The Label text can be written in multi-line by hitting option + return.

enter image description here

  • Now, go to "Size Inspector" and set the width, height, X & Y position of the Label.

enter image description here

That's all.

Simplest SOAP example

Has anyone tried this? https://github.com/doedje/jquery.soap

Seems very easy to implement.

Example:

$.soap({
url: 'http://my.server.com/soapservices/',
method: 'helloWorld',

data: {
    name: 'Remy Blom',
    msg: 'Hi!'
},

success: function (soapResponse) {
    // do stuff with soapResponse
    // if you want to have the response as JSON use soapResponse.toJSON();
    // or soapResponse.toString() to get XML string
    // or soapResponse.toXML() to get XML DOM
},
error: function (SOAPResponse) {
    // show error
}
});

will result in

<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <helloWorld>
        <name>Remy Blom</name>
        <msg>Hi!</msg>
    </helloWorld>
  </soap:Body>
</soap:Envelope>

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Above answers are excellent. You can look at the following full code example so that you could exactly know how to use

_x000D_
_x000D_
   var app = angular.module('hyperCrudApp', []);_x000D_
_x000D_
   app.controller('usersCtrl', function($scope, $http) {_x000D_
     $http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {_x000D_
        console.log(response.data)_x000D_
_x000D_
         $scope.users = response.data;_x000D_
          $scope.setKey = function (userId){_x000D_
              alert(userId)_x000D_
              if(localStorage){_x000D_
                localStorage.setItem("userId", userId)_x000D_
              } else {_x000D_
                alert("No support of localStorage")_x000D_
                return_x000D_
              }_x000D_
          }//function closed  _x000D_
     });_x000D_
   });
_x000D_
      #header{_x000D_
       color: green;_x000D_
       font-weight: bold;_x000D_
      }
_x000D_
  <!DOCTYPE html>_x000D_
  <html>_x000D_
  <head>_x000D_
    <title>HyperCrud</title>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
  </head>_x000D_
  <body>_x000D_
    <!-- NAVBAR STARTS -->_x000D_
      <nav class="navbar navbar-default navbar-fixed-top">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">HyperCrud</a>_x000D_
          </div>_x000D_
          <div id="navbar" class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="/">Home</a></li>_x000D_
              <li><a href="/about/">About</a></li>_x000D_
              <li><a href="/contact/">Contact</a></li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Apps<span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="/qAlarm/details/">qAlarm &raquo;</a></li>_x000D_
                  <li><a href="/YtEdit/details/">YtEdit &raquo;</a></li>_x000D_
                  <li><a href="/GWeather/details/">GWeather &raquo;</a></li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li><a href="/WadStore/details/">WadStore &raquo;</a></li>_x000D_
                  <li><a href="/chatsAll/details/">chatsAll</a></li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="/login/">Login</a></li>_x000D_
              <li><a href="/register/">Register</a></li>_x000D_
              <li><a href="/services/">Services<span class="sr-only">(current)</span></a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </nav>_x000D_
      <!--NAVBAR ENDS-->_x000D_
  <br>_x000D_
  <br>_x000D_
_x000D_
  <div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">_x000D_
    <div class="row">_x000D_
     <div class="col-sm-12 col-md-12">_x000D_
      <center>_x000D_
        <h1 id="header"> Users </h1>_x000D_
      </center>_x000D_
     </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="row" >_x000D_
        <!--ITERATING USERS LIST-->_x000D_
      <div class="col-sm-6 col-md-4" ng-repeat="user in users">_x000D_
        <div class="thumbnail">_x000D_
          <center>_x000D_
           <img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">_x000D_
           <hr>_x000D_
          </center>_x000D_
          <div class="caption">_x000D_
           <center>_x000D_
             <h3>{{user.name}}</h3>_x000D_
             <p>{{user.email}}</p>_x000D_
             <p>+91 {{user.phone}}</p>_x000D_
             <p>{{user.address.city}}</p>_x000D_
            </center>_x000D_
          </div>_x000D_
            <div class="caption">_x000D_
                <a href="/users/delete/{{user.id}}/" role="button" class="btn btn-danger btn-block" ng-click="setKey(user.id)">DELETE</a>_x000D_
                <a href="/users/update/{{user.id}}/" role="button" class="btn btn-success btn-block" ng-click="setKey(user.id)">UPDATE</a>_x000D_
            </div>_x000D_
        </div>_x000D_
      </div>_x000D_
_x000D_
        <div class="col-sm-6 col-md-4">_x000D_
          <div class="thumbnail">_x000D_
            <a href="/regiser/">_x000D_
             <img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">_x000D_
            </a>_x000D_
          </div>_x000D_
        </div>_x000D_
    </div>_x000D_
      <!--ROW ENDS-->_x000D_
  </div>_x000D_
_x000D_
_x000D_
  </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

What is the difference between a static and const variable?

Static Variables:

  • Initialized only once.
  • Static variables are for the class (not per object). i.e memory is allocated only once per class and every instance uses it. So if one object modifies its value then the modified value is visible to other objects as well. ( A simple thought.. To know the number of objects created for a class we can put a static variable and do ++ in constructor)
  • Value persists between different function calls

Const Variables:

  • Const variables are a promise that you are not going to change its value anywhere in the program. If you do it, it will complain.

How does Facebook disable the browser's integrated Developer Tools?

My simple way, but it can help for further variations on this subject. List all methods and alter them to useless.

  Object.getOwnPropertyNames(console).filter(function(property) {
     return typeof console[property] == 'function';
  }).forEach(function (verb) {
     console[verb] =function(){return 'Sorry, for security reasons...';};
  });

MD5 hashing in Android

This is a slight variation of Andranik and Den Delimarsky answers above, but its a bit more concise and doesn't require any bitwise logic. Instead it uses the built-in String.format method to convert the bytes to two character hexadecimal strings (doesn't strip 0's). Normally I would just comment on their answers, but I don't have the reputation to do so.

public static String md5(String input) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");

        StringBuilder hexString = new StringBuilder();
        for (byte digestByte : md.digest(input.getBytes()))
            hexString.append(String.format("%02X", digestByte));

        return hexString.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

If you'd like to return a lower case string instead, then just change %02X to %02x.

Edit: Using BigInteger like with wzbozon's answer, you can make the answer even more concise:

public static String md5(String input) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        BigInteger md5Data = new BigInteger(1, md.digest(input.getBytes()));
        return String.Format("%032X", md5Data);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

There are multiple right answers here. I don't see the VIM version of it so here it is. Open your file in VIM, check the bottom status line for example, execute set ff=dos (for CRLF) or set ff=unix (for LF).

How do I tell if .NET 3.5 SP1 is installed?

Assuming that the name is everywhere "Microsoft .NET Framework 3.5 SP1", you can use this:

string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))
{
    return rk.GetSubKeyNames().Contains("Microsoft .NET Framework 3.5 SP1");
}

What do the makefile symbols $@ and $< mean?

$@ is the name of the target being generated, and $< the first prerequisite (usually a source file). You can find a list of all these special variables in the GNU Make manual.

For example, consider the following declaration:

all: library.cpp main.cpp

In this case:

  • $@ evaluates to all
  • $< evaluates to library.cpp
  • $^ evaluates to library.cpp main.cpp

How can I echo HTML in PHP?

There are a few ways to echo HTML in PHP.

1. In between PHP tags

<?php if(condition){ ?>
     <!-- HTML here -->
<?php } ?>

2. In an echo

if(condition){
     echo "HTML here";
}

With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:

echo '<input type="text">';

Or you can escape them like so:

echo "<input type=\"text\">";

3. Heredocs

4. Nowdocs (as of PHP 5.3.0)

Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).

There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).

The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.

If you have any more questions feel free to leave a comment.

Further reading is available on these things in the PHP documentation.


NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.

Concatenating elements in an array to a string

Use the Arrays.toString() function. It keeps your code short and readable. It uses a string builder internally, thus, it's also efficient. To get rid of the extra characters, you might chose to eliminate them using the String.replace() function, which, admittedly, reduces readability again.

String str = Arrays.toString(arr).replaceAll(", |\\[|\\]", "");

This is similar to the answer of Tris Nefzger, but without the lengthy substring construction to get rid of the square brackets.

Explanation of the Regex: "|" means any of ", " and "[" and "]". The "\\" tells the Java String that we are not meaning some special character (like a new line "\n" or a tab "\t") but a real backslash "\". So instead of "\\[", the Regex interpreter reads "\[", which tells it that we mean a literal square bracket and do not want to use it as part of the Regex language (for instance, "[^3]*" denotes any number of characters, but none of them should be "3").

How can I set the Secure flag on an ASP.NET Session Cookie?

Building upon @Mark D's answer I would use web.config transforms to set all the various cookies to Secure. This includes setting anonymousIdentification cookieRequireSSL and httpCookies requireSSL.

To that end you'd setup your web.Release.config as:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
    <httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
    <anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" /> 
  </system.web>
</configuration>

If you're using Roles and Forms Authentication with the ASP.NET Membership Provider (I know, it's ancient) you'll also want to set the roleManager cookieRequireSSL and the forms requireSSL attributes as secure too. If so, your web.release.config might look like this (included above plus new tags for membership API):

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
    <httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
    <anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" /> 
    <roleManager xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
    <authentication>
        <forms xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
    </authentication>
  </system.web>
</configuration>

Background on web.config transforms here: http://go.microsoft.com/fwlink/?LinkId=125889

Obviously this goes beyond the original question of the OP but if you don't set them all to secure you can expect that a security scanning tool will notice and you'll see red flags appear on the report. Ask me how I know. :)

How to create a checkbox with a clickable label?

It works too :

<form>
    <label for="male"><input type="checkbox" name="male" id="male" />Male</label><br />
    <label for="female"><input type="checkbox" name="female" id="female" />Female</label>
</form>

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

To diagnose this issue, place the line of code causing the TargetInvocationException inside the try block.

To troubleshoot this type of error, get the inner exception. It could be due to a number of different issues.

try
{
    // code causing TargetInvocationException
}
catch (Exception e)
{
    if (e.InnerException != null)
    {
    string err = e.InnerException.Message;
    }
}

Rails 4 - Strong Parameters - Nested Objects

Permitting a nested object :

params.permit( {:school => [:id , :name]}, 
               {:student => [:id, 
                            :name, 
                            :address, 
                            :city]},
                {:records => [:marks, :subject]})

How to list the tables in a SQLite database file that was opened with ATTACH?

Use:

import sqlite3

TABLE_LIST_QUERY = "SELECT * FROM sqlite_master where type='table'"

Bigger Glyphicons

If you are using bootstrap 3, use tag, like this <small><span class="glyphicon glyphicon-send"></span></small> It works perfect for Bootstrap 3.
You can even use multiple <small> tags to set the size more smaller.
Code:
<small><small><span class="glyphicon glyphicon-send"></span></small></small>

How to "set a breakpoint in malloc_error_break to debug"

I solve it by close safari inspector. Refer to my post. I also found sound sometimes when I run my app for testing, then I open safari with auto inspector on, after this, I do some action in my app then this issue triggered.

enter image description here

Where should I put <script> tags in HTML markup?

Including scripts at the end is mainly used where the content/ styles of the website is to be shown first.

including the scripts in the head loads the scripts early and can be used before the loading of the whole web site.

if the scripts are entered at last the validation will happen only after the loading of the entire styles and design which is not appreciated for fast responsive websites.

How to always show scrollbar

android:scrollbarFadeDuration="0" sometimes does not work after I exit from the apps and start again. So I add gallery.setScrollbarFadingEnabled(false); to the activity and it works!

ADB No Devices Found

I had turned all settings in developer mode, but adb was still not showing any devices.

I was not using the cable that came with my phone. Once I switched to it, everything just worked.

Equivalent to 'app.config' for a library (DLL)

Unfortunately, you can only have one app.config file per executable, so if you have DLL’s linked into your application, they cannot have their own app.config files.

Solution is: You don't need to put the App.config file in the Class Library's project.
You put the App.config file in the application that is referencing your class library's dll.

For example, let's say we have a class library named MyClasses.dll which uses the app.config file like so:

string connect = 
ConfigurationSettings.AppSettings["MyClasses.ConnectionString"];

Now, let's say we have an Windows Application named MyApp.exe which references MyClasses.dll. It would contain an App.config with an entry such as:

<appSettings>
    <add key="MyClasses.ConnectionString"
         value="Connection string body goes here" />
</appSettings>

OR

An xml file is best equivalent for app.config. Use xml serialize/deserialize as needed. You can call it what every you want. If your config is "static" and does not need to change, your could also add it to the project as an embedded resource.

Hope it gives some Idea

What exactly is nullptr?

Well, other languages have reserved words that are instances of types. Python, for instance:

>>> None = 5
  File "<stdin>", line 1
SyntaxError: assignment to None
>>> type(None)
<type 'NoneType'>

This is actually a fairly close comparison because None is typically used for something that hasn't been intialized, but at the same time comparisons such as None == 0 are false.

On the other hand, in plain C, NULL == 0 would return true IIRC because NULL is just a macro returning 0, which is always an invalid address (AFAIK).

How to get the exact local time of client?

Try on this way

    function timenow(){
    var now= new Date(), 
    ampm= 'am', 
    h= now.getHours(), 
    m= now.getMinutes(), 
    s= now.getSeconds();
    if(h>= 12){
        if(h>12) h -= 12;
        ampm= 'pm';
    }

    if(m<10) m= '0'+m;
    if(s<10) s= '0'+s;
    return now.toLocaleDateString()+ ' ' + h + ':' + m + ':' + s + ' ' + ampm;
}

toLocaleDateString()

is a function to change the date time format like toLocaleDateString("en-us")

Is there possibility of sum of ArrayList without looping

This link shows three different ways how to sum in java, there is one option that is not in previous answers using Apache Commons Math..

Example:

public static void main(String args []){
    List<Double> NUMBERS_FOR_SUM = new ArrayList<Double>(){
         {
            add(5D);
            add(3.2D);
            add(7D);
         }
    };
    double[] arrayToSume = ArrayUtils.toPrimitive(NUMBERS_FOR_SUM
            .toArray(new Double[NUMBERS_FOR_SUM.size()]));    
    System.out.println(StatUtils.sum(arrayToSume));

}

See StatUtils api

CORS Access-Control-Allow-Headers wildcard being ignored?

here's the incantation for nginx, inside a

location / {
    # Simple requests
    if ($request_method ~* "(GET|POST)") {
      add_header "Access-Control-Allow-Origin"  *;
    }

    # Preflighted requests
    if ($request_method = OPTIONS ) {
      add_header "Access-Control-Allow-Origin"  *;
      add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }

}

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

For this case word boundary (\b) can also be used instead of start anchor (^) and end anchor ($):

\b\d{1,45}\b

\b is a position between \w and \W (non-word char), or at the beginning or end of a string.

How do emulators work and how are they written?

I've never done anything so fancy as to emulate a game console but I did take a course once where the assignment was to write an emulator for the machine described in Andrew Tanenbaums Structured Computer Organization. That was fun an gave me a lot of aha moments. You might want to pick that book up before diving in to writing a real emulator.

Import Excel Spreadsheet Data to an EXISTING sql table?

You can use import data with wizard and there you can choose destination table.

Run the wizard. In selecting source tables and views window you see two parts. Source and Destination.

Click on the field under Destination part to open the drop down and select you destination table and edit its mappings if needed.

EDIT

Merely typing the name of the table does not work. It appears that the name of the table must include the schema (dbo) and possibly brackets. Note the dropdown on the right hand side of the text field.

enter image description here

How to add reference to a method parameter in javadoc?

I guess you could write your own doclet or taglet to support this behaviour.

Taglet Overview

Doclet Overview

Hibernate: How to set NULL query-parameter value with HQL?

this seems to work as wel ->

@Override
public List<SomeObject> findAllForThisSpecificThing(String thing) {
    final Query query = entityManager.createQuery(
            "from " + getDomain().getSimpleName() + " t  where t.thing = " + ((thing == null) ? " null" : " :thing"));
    if (thing != null) {
        query.setParameter("thing", thing);
    }
    return query.getResultList();
}

Btw, I'm pretty new at this, so if for any reason this isn't a good idea, let me know. Thanks.