Programs & Examples On #Multithreading

Multi-threading is the ability of a computer or a program to perform work concurrently or asynchronously by utilizing multiple concurrent streams of execution (generally referred to as threads).

What does 'synchronized' mean?

Here is an explanation from The Java Tutorials.

Consider the following code:

public class SynchronizedCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}

if count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:

  • First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
  • Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

Create multiple threads and wait all of them to complete

Most proposed answers don't take into account a time-out interval, which is very important to prevent a possible deadlock. Next is my sample code. (Note that I'm primarily a Win32 developer, and that's how I'd do it there.)

//'arrRunningThreads' = List<Thread>

//Wait for all threads
const int knmsMaxWait = 3 * 1000;           //3 sec timeout
int nmsBeginTicks = Environment.TickCount;
foreach(Thread thrd in arrRunningThreads)
{
    //See time left
    int nmsElapsed = Environment.TickCount - nmsBeginTicks;
    int nmsRemain = knmsMaxWait - nmsElapsed;
    if(nmsRemain < 0)
        nmsRemain = 0;

    //Then wait for thread to exit
    if(!thrd.Join(nmsRemain))
    {
        //It didn't exit in time, terminate it
        thrd.Abort();

        //Issue a debugger warning
        Debug.Assert(false, "Terminated thread");
    }
}

Handling InterruptedException in Java

To me the key thing about this is: an InterruptedException is not anything going wrong, it is the thread doing what you told it to do. Therefore rethrowing it wrapped in a RuntimeException makes zero sense.

In many cases it makes sense to rethrow an exception wrapped in a RuntimeException when you say, I don't know what went wrong here and I can't do anything to fix it, I just want it to get out of the current processing flow and hit whatever application-wide exception handler I have so it can log it. That's not the case with an InterruptedException, it's just the thread responding to having interrupt() called on it, it's throwing the InterruptedException in order to help cancel the thread's processing in a timely way.

So propagate the InterruptedException, or eat it intelligently (meaning at a place where it will have accomplished what it was meant to do) and reset the interrupt flag. Note that the interrupt flag gets cleared when the InterruptedException gets thrown; the assumption the Jdk library developers make is that catching the exception amounts to handling it, so by default the flag is cleared.

So definitely the first way is better, the second posted example in the question is not useful unless you don't expect the thread to actually get interrupted, and interrupting it amounts to an error.

Here's an answer I wrote describing how interrupts work, with an example. You can see in the example code where it is using the InterruptedException to bail out of a while loop in the Runnable's run method.

Why is lock(this) {...} bad?

Please refer to the following link which explains why lock (this) is not a good idea.

https://docs.microsoft.com/en-us/dotnet/standard/threading/managed-threading-best-practices

So the solution is to add a private object, for example, lockObject to the class and place the code region inside the lock statement as shown below:

lock (lockObject)
{
...
}

The difference between the Runnable and Callable interfaces in Java

Difference between Callable and Runnable are following:

  1. Callable is introduced in JDK 5.0 but Runnable is introduced in JDK 1.0
  2. Callable has call() method but Runnable has run() method.
  3. Callable has call method which returns value but Runnable has run method which doesn't return any value.
  4. call method can throw checked exception but run method can't throw checked exception.
  5. Callable use submit() method to put in task queue but Runnable use execute() method to put in the task queue.

If statement with String comparison fails

You shouldn't do string comparisons with ==. That operator will only check to see if it is the same instance, not the same value. Use the .equals method to check for the same value.

Waiting on a list of Future

You can use an ExecutorCompletionService. The documentation even has an example for your exact use-case:

Suppose instead that you would like to use the first non-null result of the set of tasks, ignoring any that encounter exceptions, and cancelling all other tasks when the first one is ready:

void solve(Executor e, Collection<Callable<Result>> solvers) throws InterruptedException {
    CompletionService<Result> ecs = new ExecutorCompletionService<Result>(e);
    int n = solvers.size();
    List<Future<Result>> futures = new ArrayList<Future<Result>>(n);
    Result result = null;
    try {
        for (Callable<Result> s : solvers)
            futures.add(ecs.submit(s));
        for (int i = 0; i < n; ++i) {
            try {
                Result r = ecs.take().get();
                if (r != null) {
                    result = r;
                    break;
                }
            } catch (ExecutionException ignore) {
            }
        }
    } finally {
        for (Future<Result> f : futures)
            f.cancel(true);
    }

    if (result != null)
        use(result);
}

The important thing to notice here is that ecs.take() will get the first completed task, not just the first submitted one. Thus you should get them in the order of finishing the execution (or throwing an exception).

What is the volatile keyword useful for?

There are two different uses of volatile keyword.

  1. Prevents JVM from reading values from register (assume as cache), and forces its value to be read from memory.
  2. Reduces the risk of memory in-consistency errors.

Prevents JVM from reading values in register, and forces its value to be read from memory.

A busy flag is used to prevent a thread from continuing while the device is busy and the flag is not protected by a lock:

while (busy) {
    /* do something else */
}

The testing thread will continue when another thread turns off the busy flag:

busy = 0;

However, since busy is accessed frequently in the testing thread, the JVM may optimize the test by placing the value of busy in a register, then test the contents of the register without reading the value of busy in memory before every test. The testing thread would never see busy change and the other thread would only change the value of busy in memory, resulting in deadlock. Declaring the busy flag as volatile forces its value to be read before each test.

Reduces the risk of memory consistency errors.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a "happens-before" relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.

The technique of reading, writing without memory consistency errors is called atomic action.

An atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete.

Below are actions you can specify that are atomic:

  • Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
  • Reads and writes are atomic for all variables declared volatile (including long and double variables).

Cheers!

How to terminate a thread when main program ends?

If you spawn a Thread like so - myThread = Thread(target = function) - and then do myThread.start(); myThread.join(). When CTRL-C is initiated, the main thread doesn't exit because it is waiting on that blocking myThread.join() call. To fix this, simply put in a timeout on the .join() call. The timeout can be as long as you wish. If you want it to wait indefinitely, just put in a really long timeout, like 99999. It's also good practice to do myThread.daemon = True so all the threads exit when the main thread(non-daemon) exits.

What is thread safe or non-thread safe in PHP?

As per PHP Documentation,

What does thread safety mean when downloading PHP?

Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.

So what do I choose? If you choose to run PHP as a CGI binary, then you won't need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.

Following Libraries are not thread safe. They are not recommended for use in a multi-threaded environment.

  • SNMP (Unix)
  • mSQL (Unix)
  • IMAP (Win/Unix)
  • Sybase-CT (Linux, libc5)

Proper use of mutexes in Python

I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:

from threading import Thread, Lock

mutex = Lock()

def processData(data):
    mutex.acquire()
    try:
        print('Do some stuff')
    finally:
        mutex.release()

while True:
    t = Thread(target = processData, args = (some_data,))
    t.start()

But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.

An alternative, for Python 2.6 and later, is to use Python's multiprocessing package. It mirrors the threading package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:

from multiprocessing import Process, Lock

mutex = Lock()

def processData(data):
    with mutex:
        print('Do some stuff')

if __name__ == '__main__':
    while True:
        p = Process(target = processData, args = (some_data,))
        p.start()

Thread pooling in C++11

You can use C++ Thread Pool Library, https://github.com/vit-vit/ctpl.

Then the code your wrote can be replaced with the following

#include <ctpl.h>  // or <ctpl_stl.h> if ou do not have Boost library

int main (int argc, char *argv[]) {
    ctpl::thread_pool p(2 /* two threads in the pool */);
    int arr[4] = {0};
    std::vector<std::future<void>> results(4);
    for (int i = 0; i < 8; ++i) { // for 8 iterations,
        for (int j = 0; j < 4; ++j) {
            results[j] = p.push([&arr, j](int){ arr[j] +=2; });
        }
        for (int j = 0; j < 4; ++j) {
            results[j].get();
        }
        arr[4] = std::min_element(arr, arr + 4);
    }
}

You will get the desired number of threads and will not create and delete them over and over again on the iterations.

Automating the InvokeRequired code pattern

Here's an improved/combined version of Lee's, Oliver's and Stephan's answers.

public delegate void InvokeIfRequiredDelegate<T>(T obj)
    where T : ISynchronizeInvoke;

public static void InvokeIfRequired<T>(this T obj, InvokeIfRequiredDelegate<T> action)
    where T : ISynchronizeInvoke
{
    if (obj.InvokeRequired)
    {
        obj.Invoke(action, new object[] { obj });
    }
    else
    {
        action(obj);
    }
} 

The template allows for flexible and cast-less code which is much more readable while the dedicated delegate provides efficiency.

progressBar1.InvokeIfRequired(o => 
{
    o.Style = ProgressBarStyle.Marquee;
    o.MarqueeAnimationSpeed = 40;
});

Why doesn't JavaScript support multithreading?

It's the implementations that doesn't support multi-threading. Currently Google Gears is providing a way to use some form of concurrency by executing external processes but that's about it.

The new browser Google is supposed to release today (Google Chrome) executes some code in parallel by separating it in process.

The core language, of course can have the same support as, say Java, but support for something like Erlang's concurrency is nowhere near the horizon.

Locking pattern for proper use of .NET MemoryCache

There is an open source library [disclaimer: that I wrote]: LazyCache that IMO covers your requirement with two lines of code:

IAppCache cache = new CachingService();
var cachedResults = cache.GetOrAdd("CacheKey", 
  () => SomeHeavyAndExpensiveCalculation());

It has built in locking by default so the cacheable method will only execute once per cache miss, and it uses a lambda so you can do "get or add" in one go. It defaults to 20 minutes sliding expiration.

There's even a NuGet package ;)

The calling thread must be STA, because many UI components require this

Just mark your program with the [STAThread] attribute and the error goes away! it's magic :)

Printing Even and Odd using two Threads in Java

import java.util.concurrent.Semaphore;


public class PrintOddAndEven {

private static class OddThread extends Thread {
    private Semaphore semaphore;
    private Semaphore otherSemaphore;
    private int value = 1;

    public  OddThread(Semaphore semaphore, Semaphore otherSemaphore) {
        this.semaphore = semaphore;
        this.otherSemaphore = otherSemaphore;
    }

    public void run() {
        while (value <= 100) {
            try {
                // Acquire odd semaphore
                semaphore.acquire();
                System.out.println(" Odd Thread " + value + " " + Thread.currentThread().getName());

            } catch (InterruptedException excetion) {
                excetion.printStackTrace();
            }
            value = value + 2;
            // Release odd semaphore
            otherSemaphore.release();
        }
    }
}


private static class EvenThread extends Thread {
    private Semaphore semaphore;
    private Semaphore otherSemaphore;

    private int value = 2;

    public  EvenThread(Semaphore semaphore, Semaphore otherSemaphore) {
        this.semaphore = semaphore;
        this.otherSemaphore = otherSemaphore;
    }

    public void run() {
        while (value <= 100) {
            try {
                // Acquire even semaphore
                semaphore.acquire();
                System.out.println(" Even Thread " + value + " " + Thread.currentThread().getName());

            } catch (InterruptedException excetion) {
                excetion.printStackTrace();
            }
            value = value + 2;
            // Release odd semaphore
            otherSemaphore.release();
        }
    }
}


public static void main(String[] args) {
    //Initialize oddSemaphore with permit 1
    Semaphore oddSemaphore = new Semaphore(1);
    //Initialize evenSempahore with permit 0
    Semaphore evenSempahore = new Semaphore(0);
    OddThread oddThread = new OddThread(oddSemaphore, evenSempahore);
    EvenThread evenThread = new EvenThread(evenSempahore, oddSemaphore);
    oddThread.start();
    evenThread.start();
    }
}

What's the difference between Thread start() and Runnable run()

If you do run() in main method, the thread of main method will invoke the run method instead of the thread you require to run.

The start() method creates new thread and for which the run() method has to be done

How to create a thread?

Update The currently suggested way to start a Task is simply using Task.Run()

Task.Run(() => foo());

Note that this method is described as the best way to start a task see here

Previous answer

I like the Task Factory from System.Threading.Tasks. You can do something like this:

Task.Factory.StartNew(() => 
{
    // Whatever code you want in your thread
});

Note that the task factory gives you additional convenience options like ContinueWith:

Task.Factory.StartNew(() => {}).ContinueWith((result) => 
{
    // Whatever code should be executed after the newly started thread.
});

Also note that a task is a slightly different concept than threads. They nicely fit with the async/await keywords, see here.

Creating a blocking Queue<T> in .NET?

That looks very unsafe (very little synchronization); how about something like:

class SizeQueue<T>
{
    private readonly Queue<T> queue = new Queue<T>();
    private readonly int maxSize;
    public SizeQueue(int maxSize) { this.maxSize = maxSize; }

    public void Enqueue(T item)
    {
        lock (queue)
        {
            while (queue.Count >= maxSize)
            {
                Monitor.Wait(queue);
            }
            queue.Enqueue(item);
            if (queue.Count == 1)
            {
                // wake up any blocked dequeue
                Monitor.PulseAll(queue);
            }
        }
    }
    public T Dequeue()
    {
        lock (queue)
        {
            while (queue.Count == 0)
            {
                Monitor.Wait(queue);
            }
            T item = queue.Dequeue();
            if (queue.Count == maxSize - 1)
            {
                // wake up any blocked enqueue
                Monitor.PulseAll(queue);
            }
            return item;
        }
    }
}

(edit)

In reality, you'd want a way to close the queue so that readers start exiting cleanly - perhaps something like a bool flag - if set, an empty queue just returns (rather than blocking):

bool closing;
public void Close()
{
    lock(queue)
    {
        closing = true;
        Monitor.PulseAll(queue);
    }
}
public bool TryDequeue(out T value)
{
    lock (queue)
    {
        while (queue.Count == 0)
        {
            if (closing)
            {
                value = default(T);
                return false;
            }
            Monitor.Wait(queue);
        }
        value = queue.Dequeue();
        if (queue.Count == maxSize - 1)
        {
            // wake up any blocked enqueue
            Monitor.PulseAll(queue);
        }
        return true;
    }
}

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

How do I make my ArrayList Thread-Safe? Another approach to problem in Java?

CopyOnWriteArrayList

Use CopyOnWriteArrayList class. This is the thread safe version of ArrayList.

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();

Android basically works on two thread types namely UI thread and background thread. According to android documentation -

Do not access the Android UI toolkit from outside the UI thread to fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:

Activity.runOnUiThread(Runnable)  
View.post(Runnable)  
View.postDelayed(Runnable, long)

Now there are various methods to solve this problem. I will explain it by code sample

runOnUiThread

new Thread()
{
    public void run()
    {
        myactivity.this.runOnUiThread(new runnable()
        {
            public void run()
            {
                //Do your UI operations like dialog opening or Toast here
            }
        });
    }
}.start();

LOOPER

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };

        Looper.loop();
    }

AsyncTask

AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

public void onClick(View v) {
    new CustomTask().execute((Void[])null);
}


private class CustomTask extends AsyncTask<Void, Void, Void> {

    protected Void doInBackground(Void... param) {
        //Do some work
        return null;
    }

    protected void onPostExecute(Void param) {
        //Print Toast or open dialog
    }
}

Handler

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

Message msg = new Message();


    new Thread()
    {
        public void run()
        {
            msg.arg1=1;
            handler.sendMessage(msg);
        }
    }.start();



    Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if(msg.arg1==1)
            {
                //Print Toast or open dialog        
            }
            return false;
        }
    });

When should we use mutex and when should we use semaphore

A mutex is a mutual exclusion object, similar to a semaphore but that only allows one locker at a time and whose ownership restrictions may be more stringent than a semaphore.

It can be thought of as equivalent to a normal counting semaphore (with a count of one) and the requirement that it can only be released by the same thread that locked it(a).

A semaphore, on the other hand, has an arbitrary count and can be locked by that many lockers concurrently. And it may not have a requirement that it be released by the same thread that claimed it (but, if not, you have to carefully track who currently has responsibility for it, much like allocated memory).

So, if you have a number of instances of a resource (say three tape drives), you could use a semaphore with a count of 3. Note that this doesn't tell you which of those tape drives you have, just that you have a certain number.

Also with semaphores, it's possible for a single locker to lock multiple instances of a resource, such as for a tape-to-tape copy. If you have one resource (say a memory location that you don't want to corrupt), a mutex is more suitable.

Equivalent operations are:

Counting semaphore          Mutual exclusion semaphore
--------------------------  --------------------------
  Claim/decrease (P)                  Lock
  Release/increase (V)                Unlock

Aside: in case you've ever wondered at the bizarre letters used for claiming and releasing semaphores, it's because the inventor was Dutch. Probeer te verlagen means to try and decrease while verhogen means to increase.


(a) ... or it can be thought of as something totally distinct from a semaphore, which may be safer given their almost-always-different uses.

Handler vs AsyncTask vs Thread

Thread

Android supports standard Java Threads. You can use standard Threads and the tools from the package “java.util.concurrent” to put actions into the background. The only limitation is that you cannot directly update the UI from the a background process.

If you need to update the UI from a background task you need to use some Android specific classes. You can use the class “android.os.Handler” for this or the class “AsyncTask

Handler

The class “Handler” can update the UI. A handle provides methods for receiving messages and for runnables. To use a handler you have to subclass it and override handleMessage() to process messages. To process Runable, you can use the method post(); You only need one instance of a handler in your activity.

You thread can post messages via the method sendMessage(Message msg) or sendEmptyMessage.

AsyncTask

If you have an Activity which needs to download content or perform operations that can be done in the background AsyncTask allows you to maintain a responsive user interface and publish progress for those operations to the user.

For more information you can have a look at these links.

http://mobisys.in/blog/2012/01/android-threads-handlers-and-asynctask-tutorial/

http://www.slideshare.net/HoangNgoBuu/android-thread-handler-and-asynctask

Timeout on a function call

Here is a POSIX version that combines many of the previous answers to deliver following features:

  1. Subprocesses blocking the execution.
  2. Usage of the timeout function on class member functions.
  3. Strict requirement on time-to-terminate.

Here is the code and some test cases:

import threading
import signal
import os
import time

class TerminateExecution(Exception):
    """
    Exception to indicate that execution has exceeded the preset running time.
    """


def quit_function(pid):
    # Killing all subprocesses
    os.setpgrp()
    os.killpg(0, signal.SIGTERM)

    # Killing the main thread
    os.kill(pid, signal.SIGTERM)


def handle_term(signum, frame):
    raise TerminateExecution()


def invoke_with_timeout(timeout, fn, *args, **kwargs):
    # Setting a sigterm handler and initiating a timer
    old_handler = signal.signal(signal.SIGTERM, handle_term)
    timer = threading.Timer(timeout, quit_function, args=[os.getpid()])
    terminate = False

    # Executing the function
    timer.start()
    try:
        result = fn(*args, **kwargs)
    except TerminateExecution:
        terminate = True
    finally:
        # Restoring original handler and cancel timer
        signal.signal(signal.SIGTERM, old_handler)
        timer.cancel()

    if terminate:
        raise BaseException("xxx")

    return result

### Test cases
def countdown(n):
    print('countdown started', flush=True)
    for i in range(n, -1, -1):
        print(i, end=', ', flush=True)
        time.sleep(1)
    print('countdown finished')
    return 1337


def really_long_function():
    time.sleep(10)


def really_long_function2():
    os.system("sleep 787")


# Checking that we can run a function as expected.
assert invoke_with_timeout(3, countdown, 1) == 1337

# Testing various scenarios
t1 = time.time()
try:
    print(invoke_with_timeout(1, countdown, 3))
    assert(False)
except BaseException:
    assert(time.time() - t1 < 1.1)
    print("All good", time.time() - t1)

t1 = time.time()
try:
    print(invoke_with_timeout(1, really_long_function2))
    assert(False)
except BaseException:
    assert(time.time() - t1 < 1.1)
    print("All good", time.time() - t1)


t1 = time.time()
try:
    print(invoke_with_timeout(1, really_long_function))
    assert(False)
except BaseException:
    assert(time.time() - t1 < 1.1)
    print("All good", time.time() - t1)

# Checking that classes are referenced and not
# copied (as would be the case with multiprocessing)


class X:
    def __init__(self):
        self.value = 0

    def set(self, v):
        self.value = v


x = X()
invoke_with_timeout(2, x.set, 9)
assert x.value == 9

Start thread with member function

Some users have already given their answer and explained it very well.

I would like to add few more things related to thread.

  1. How to work with functor and thread. Please refer to below example.

  2. The thread will make its own copy of the object while passing the object.

    #include<thread>
    #include<Windows.h>
    #include<iostream>
    
    using namespace std;
    
    class CB
    {
    
    public:
        CB()
        {
            cout << "this=" << this << endl;
        }
        void operator()();
    };
    
    void CB::operator()()
    {
        cout << "this=" << this << endl;
        for (int i = 0; i < 5; i++)
        {
            cout << "CB()=" << i << endl;
            Sleep(1000);
        }
    }
    
    void main()
    {
        CB obj;     // please note the address of obj.
    
        thread t(obj); // here obj will be passed by value 
                       //i.e. thread will make it own local copy of it.
                        // we can confirm it by matching the address of
                        //object printed in the constructor
                        // and address of the obj printed in the function
    
        t.join();
    }
    

Another way of achieving the same thing is like:

void main()
{
    thread t((CB()));

    t.join();
}

But if you want to pass the object by reference then use the below syntax:

void main()
{
    CB obj;
    //thread t(obj);
    thread t(std::ref(obj));
    t.join();
}

Checking on a thread / remove from list

you need to call thread.isAlive()to find out if the thread is still running

Java Multithreading concept and join() method

I came across the join() while learning about race condition and I will clear the doubts I was having. So let us take this small example

Thread t2 = new Thread(
             new Runnable() {
                 public void run () {
                     //do something
                 }
              }
);
Thread t1 = new Thread(
             new Runnable() {
                 public void run () {
                     //do something
                 }
              }
);
t2.start(); //Line 11
t1.start(); //Line 12
t2.join();  //Line 13
t1.join();  //Line 14
System.out.print("<Want to print something that was being modified by t2 and t1>")

My AIM
Three threads are running namely t1, t2 and the main thread. I want to print something after the t1 and t2 has finished. The printing operation is on my main thread therefore for the expected answer I need to let t1 and t2 finish and then print my output.

So t1.join() just makes the main thread wait, till the t1 thread completes before going to the next line in program.

Here is the definition as per GeeksforGeeks:

java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution.

Here is one question that might solve your doubt

Q-> Will t1 thread get the time slice to run by the thread scheduler, when the program is processing the t2.join() at Line 13?

ANS-> Yes it will be eligible to get the time slice to run as we have already made it eligible by running the line t1.start() at Line 11.
t2.join() only applies the condition when the JVM will go to next line, that is Line 14.
It might be also possible that t1 might get finished processing at Line 13.

Why must wait() always be in synchronized block

directly from this java oracle tutorial:

When a thread invokes d.wait, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock.

What's the difference between Invoke() and BeginInvoke()

Do you mean Delegate.Invoke/BeginInvoke or Control.Invoke/BeginInvoke?

  • Delegate.Invoke: Executes synchronously, on the same thread.
  • Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

Tim's answer mentions when you might want to use BeginInvoke - although it was mostly geared towards Delegate.BeginInvoke, I suspect.

For Windows Forms apps, I would suggest that you should usually use BeginInvoke. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person with FirstName and LastName properties, and you did:

person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";

Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)

Unless you have this sort of issue, however, Control.BeginInvoke is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke in a "fire and forget" manner - i.e. without ever calling EndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.

What's the difference between deadlock and livelock?

Taken from http://en.wikipedia.org/wiki/Deadlock:

In concurrent computing, a deadlock is a state in which each member of a group of actions, is waiting for some other member to release a lock

A livelock is similar to a deadlock, except that the states of the processes involved in the livelock constantly change with regard to one another, none progressing. Livelock is a special case of resource starvation; the general definition only states that a specific process is not progressing.

A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time.

Livelock is a risk with some algorithms that detect and recover from deadlock. If more than one process takes action, the deadlock detection algorithm can be repeatedly triggered. This can be avoided by ensuring that only one process (chosen randomly or by priority) takes action.

How many threads is too many?

One thing you should keep in mind is that python (at least the C based version) uses what's called a global interpreter lock that can have a huge impact on performance on mult-core machines.

If you really need the most out of multithreaded python, you might want to consider using Jython or something.

Task continuation on UI thread

Call the continuation with TaskScheduler.FromCurrentSynchronizationContext():

    Task UITask= task.ContinueWith(() =>
    {
     this.TextBlock1.Text = "Complete"; 
    }, TaskScheduler.FromCurrentSynchronizationContext());

This is suitable only if the current execution context is on the UI thread.

Running multiple AsyncTasks at the same time -- not possible?

It is posible. My android device version is 4.0.4 and android.os.Build.VERSION.SDK_INT is 15

I have 3 spinners

Spinner c_fruit=(Spinner) findViewById(R.id.fruits);
Spinner c_vegetable=(Spinner) findViewById(R.id.vegetables);
Spinner c_beverage=(Spinner) findViewById(R.id.beverages);

And also I have a Async-Tack class.

Here is my spinner loading code

RequestSend reqs_fruit = new RequestSend(this);
reqs_fruit.where="Get_fruit_List";
reqs_fruit.title="Loading fruit";
reqs_fruit.execute();

RequestSend reqs_vegetable = new RequestSend(this);
reqs_vegetable.where="Get_vegetable_List";
reqs_vegetable.title="Loading vegetable";
reqs_vegetable.execute();

RequestSend reqs_beverage = new RequestSend(this);
reqs_beverage.where="Get_beverage_List";
reqs_beverage.title="Loading beverage";
reqs_beverage.execute();

This is working perfectly. One by one my spinners loaded. I didn't user executeOnExecutor.

Here is my Async-task class

public class RequestSend  extends AsyncTask<String, String, String > {

    private ProgressDialog dialog = null;
    public Spinner spin;
    public String where;
    public String title;
    Context con;
    Activity activity;      
    String[] items;

    public RequestSend(Context activityContext) {
        con = activityContext;
        dialog = new ProgressDialog(activityContext);
        this.activity = activityContext;
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            ArrayAdapter<String> adapter = new ArrayAdapter<String> (activity, android.R.layout.simple_spinner_item, items);       
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spin.setAdapter(adapter);
        } catch (NullPointerException e) {
            Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (Exception e)  {
            Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        super.onPostExecute(result);

        if (dialog != null)
            dialog.dismiss();   
    }

    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setTitle(title);
        dialog.setMessage("Wait...");
        dialog.setCancelable(false); 
        dialog.show();
    }

    @Override
    protected String doInBackground(String... Strings) {
        try {
            Send_Request();
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        return null;
    }

    public void Send_Request() throws JSONException {

        try {
            String DataSendingTo = "http://www.example.com/AppRequest/" + where;
            //HttpClient
            HttpClient httpClient = new DefaultHttpClient();
            //Post header
            HttpPost httpPost = new HttpPost(DataSendingTo);
            //Adding data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

            nameValuePairs.add(new BasicNameValuePair("authorized","001"));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);

            BufferedReader reader;
            try {
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    builder.append(line) ;
                }

                JSONTokener tokener = new JSONTokener(builder.toString());
                JSONArray finalResult = new JSONArray(tokener);
                items = new String[finalResult.length()]; 
                // looping through All details and store in public String array
                for(int i = 0; i < finalResult.length(); i++) {
                    JSONObject c = finalResult.getJSONObject(i);
                    items[i]=c.getString("data_name");
                }

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Service vs IntentService in the Android platform

Android IntentService vs Service

1.Service

  • A Service is invoked using startService().
  • A Service can be invoked from any thread.
  • A Service runs background operations on the Main Thread of the Application by default. Hence it can block your Application’s UI.
  • A Service invoked multiple times would create multiple instances.
  • A service needs to be stopped using stopSelf() or stopService().
  • Android service can run parallel operations.

2. IntentService

  • An IntentService is invoked using Intent.
  • An IntentService can in invoked from the Main thread only.
  • An IntentService creates a separate worker thread to run background operations.
  • An IntentService invoked multiple times won’t create multiple instances.
  • An IntentService automatically stops after the queue is completed. No need to trigger stopService() or stopSelf().
  • In an IntentService, multiple intent calls are automatically Queued and they would be executed sequentially.
  • An IntentService cannot run parallel operation like a Service.

Refer from Here

Java: How to stop thread?

The recommended way will be to build this into the thread. So no you can't (or rather shouldn't) kill the thread from outside.

Have the thread check infrequently if it is required to stop. (Instead of blocking on a socket until there is data. Use a timeout and every once in a while check if the user indicated wanting to stop)

Simple Deadlock Examples

Here's a simple example in C++11.

#include <mutex>    // mutex
#include <iostream> // cout 
#include <cstdio>   // getchar
#include <thread>   // this_thread, yield
#include <future>   // async
#include <chrono>   // seconds

using namespace std;
mutex _m1;
mutex _m2;

// Deadlock will occur because func12 and func21 acquires the two locks in reverse order

void func12()
{
    unique_lock<mutex> l1(_m1);
    this_thread::yield(); // hint to reschedule
    this_thread::sleep_for( chrono::seconds(1) );
    unique_lock<mutex> l2(_m2 );
}

void func21()
{
    unique_lock<mutex> l2(_m2);
    this_thread::yield(); // hint to reschedule
    this_thread::sleep_for( chrono::seconds(1) );
    unique_lock<mutex> l1(_m1);
}

int main( int argc, char* argv[] )
{
    async(func12);
    func21();
    cout << "All done!"; // this won't be executed because of deadlock
    getchar();
}

How to start anonymous thread class

Not exactly sure this is what you are asking but you can do something like:

new Thread() {
    public void run() {
        System.out.println("blah");
    }
}.start();

Notice the start() method at the end of the anonymous class. You create the thread object but you need to start it to actually get another running thread.

Better than creating an anonymous Thread class is to create an anonymous Runnable class:

new Thread(new Runnable() {
    public void run() {
        System.out.println("blah");
    }
}).start();

Instead overriding the run() method in the Thread you inject a target Runnable to be run by the new thread. This is a better pattern.

How to pass multiple parameters in thread in VB

Dim evaluator As New Thread(Sub() Me.testthread(goodList, 1))
With evaluator
.IsBackground = True ' not necessary...
.Start()
End With

Java - creating a new thread

If you want more Thread to be created, in above case you have to repeat the code inside run method or at least repeat calling some method inside.

Try this, which will help you to call as many times you needed. It will be helpful when you need to execute your run more then once and from many place.

class A extends Thread {
    public void run() {
             //Code you want to get executed seperately then main thread.       
    }
     }

Main class

A obj1 = new A();
obj1.start();

A obj2 = new A();
obj2.start();

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Add this before you call method invoke:

while (!this.IsHandleCreated) 
   System.Threading.Thread.Sleep(100)

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

What is the use of join() in Python threading?

A somewhat clumsy ascii-art to demonstrate the mechanism: The join() is presumably called by the main-thread. It could also be called by another thread, but would needlessly complicate the diagram.

join-calling should be placed in the track of the main-thread, but to express thread-relation and keep it as simple as possible, I choose to place it in the child-thread instead.

without join:
+---+---+------------------                     main-thread
    |   |
    |   +...........                            child-thread(short)
    +..................................         child-thread(long)

with join
+---+---+------------------***********+###      main-thread
    |   |                             |
    |   +...........join()            |         child-thread(short)
    +......................join()......         child-thread(long)

with join and daemon thread
+-+--+---+------------------***********+###     parent-thread
  |  |   |                             |
  |  |   +...........join()            |        child-thread(short)
  |  +......................join()......        child-thread(long)
  +,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,     child-thread(long + daemonized)

'-' main-thread/parent-thread/main-program execution
'.' child-thread execution
'#' optional parent-thread execution after join()-blocked parent-thread could 
    continue
'*' main-thread 'sleeping' in join-method, waiting for child-thread to finish
',' daemonized thread - 'ignores' lifetime of other threads;
    terminates when main-programs exits; is normally meant for 
    join-independent tasks

So the reason you don't see any changes is because your main-thread does nothing after your join. You could say join is (only) relevant for the execution-flow of the main-thread.

If, for example, you want to concurrently download a bunch of pages to concatenate them into a single large page, you may start concurrent downloads using threads, but need to wait until the last page/thread is finished before you start assembling a single page out of many. That's when you use join().

How is CountDownLatch used in Java Multithreading?

As mentioned in JavaDoc (https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html), CountDownLatch is a synchronization aid, introduced in Java 5. Here the synchronization does not mean restricting access to a critical section. But rather sequencing actions of different threads. The type of synchronization achieved through CountDownLatch is similar to that of Join. Assume that there is a thread "M" which needs to wait for other worker threads "T1", "T2", "T3" to complete its tasks Prior to Java 1.5, the way this can be done is, M running the following code

    T1.join();
    T2.join();
    T3.join();

The above code makes sure that thread M resumes its work after T1, T2, T3 completes its work. T1, T2, T3 can complete their work in any order. The same can be achieved through CountDownLatch, where T1,T2, T3 and thread M share same CountDownLatch object.
"M" requests : countDownLatch.await();
where as "T1","T2","T3" does countDownLatch.countdown();

One disadvantage with the join method is that M has to know about T1, T2, T3. If there is a new worker thread T4 added later, then M has to be aware of it too. This can be avoided with CountDownLatch. After implementation the sequence of action would be [T1,T2,T3](the order of T1,T2,T3 could be anyway) -> [M]

Waiting until the task finishes

Swift 4

You can use Async Function for these situations. When you use DispatchGroup(),Sometimes deadlock may be occures.

var a: Int?
@objc func myFunction(completion:@escaping (Bool) -> () ) {

    DispatchQueue.main.async {
        let b: Int = 3
        a = b
        completion(true)
    }

}

override func viewDidLoad() {
    super.viewDidLoad()

    myFunction { (status) in
        if status {
            print(self.a!)
        }
    }
}

Update UI from Thread in Android

Use the AsyncTask class (instead of Runnable). It has a method called onProgressUpdate which can affect the UI (it's invoked in the UI thread).

What is a thread exit code?

There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0 tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.

The closest link I could find to be useful for more information is this

Quote from above link:

What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.


From the Documentation for GetEXitCodeThread

Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.


My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.

How to check if a std::thread is still running?

An easy solution is to have a boolean variable that the thread sets to true on regular intervals, and that is checked and set to false by the thread wanting to know the status. If the variable is false for to long then the thread is no longer considered active.

A more thread-safe way is to have a counter that is increased by the child thread, and the main thread compares the counter to a stored value and if the same after too long time then the child thread is considered not active.

Note however, there is no way in C++11 to actually kill or remove a thread that has hanged.

Edit How to check if a thread has cleanly exited or not: Basically the same technique as described in the first paragraph; Have a boolean variable initialized to false. The last thing the child thread does is set it to true. The main thread can then check that variable, and if true do a join on the child thread without much (if any) blocking.

Edit2 If the thread exits due to an exception, then have two thread "main" functions: The first one have a try-catch inside which it calls the second "real" main thread function. This first main function sets the "have_exited" variable. Something like this:

bool thread_done = false;

void *thread_function(void *arg)
{
    void *res = nullptr;

    try
    {
        res = real_thread_function(arg);
    }
    catch (...)
    {
    }

    thread_done = true;

    return res;
}

How to wait for all threads to finish, using ExecutorService?

In Java8 you can do it with CompletableFuture:

ExecutorService es = Executors.newFixedThreadPool(4);
List<Runnable> tasks = getTasks();
CompletableFuture<?>[] futures = tasks.stream()
                               .map(task -> CompletableFuture.runAsync(task, es))
                               .toArray(CompletableFuture[]::new);
CompletableFuture.allOf(futures).join();    
es.shutdown();

Updating GUI (WPF) using a different thread

You may use a delegate to solve this issue. Here is an example that is showing how to update a textBox using diffrent thread

public delegate void UpdateTextCallback(string message);

private void TestThread()
{
    for (int i = 0; i <= 1000000000; i++)
    {
        Thread.Sleep(1000);                
        richTextBox1.Dispatcher.Invoke(
            new UpdateTextCallback(this.UpdateText),
            new object[] { i.ToString() }
        );
    }
}
private void UpdateText(string message)
{
    richTextBox1.AppendText(message + "\n");
}

private void button1_Click(object sender, RoutedEventArgs e)
{
   Thread test = new Thread(new ThreadStart(TestThread));
   test.Start();
}

TestThread method is used by thread named test to update textBox

is python capable of running on multiple cores?

example code taking all 4 cores on my ubuntu 14.04, python 2.7 64 bit.

import time
import threading


def t():
    with open('/dev/urandom') as f:
        for x in xrange(100):
            f.read(4 * 65535)

if __name__ == '__main__':
    start_time = time.time()
    t()
    t()
    t()
    t()
    print "Sequential run time: %.2f seconds" % (time.time() - start_time)

    start_time = time.time()
    t1 = threading.Thread(target=t)
    t2 = threading.Thread(target=t)
    t3 = threading.Thread(target=t)
    t4 = threading.Thread(target=t)
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
    print "Parallel run time: %.2f seconds" % (time.time() - start_time)

result:

$ python 1.py
Sequential run time: 3.69 seconds
Parallel run time: 4.82 seconds

How to Multi-thread an Operation Within a Loop in Python

You can split the processing into a specified number of threads using an approach like this:

import threading                                                                

def process(items, start, end):                                                 
    for item in items[start:end]:                                               
        try:                                                                    
            api.my_operation(item)                                              
        except Exception:                                                       
            print('error with item')                                            


def split_processing(items, num_splits=4):                                      
    split_size = len(items) // num_splits                                       
    threads = []                                                                
    for i in range(num_splits):                                                 
        # determine the indices of the list this thread will handle             
        start = i * split_size                                                  
        # special case on the last chunk to account for uneven splits           
        end = None if i+1 == num_splits else (i+1) * split_size                 
        # create the thread                                                     
        threads.append(                                                         
            threading.Thread(target=process, args=(items, start, end)))         
        threads[-1].start() # start the thread we just created                  

    # wait for all threads to finish                                            
    for t in threads:                                                           
        t.join()                                                                



split_processing(items)

Pass multiple arguments into std::thread

If you're getting this, you may have forgotten to put #include <thread> at the beginning of your file. OP's signature seems like it should work.

C#: Waiting for all threads to complete

Off the top of my head, why don't you just Thread.Join(timeout) and remove the time it took to join from the total timeout?

// pseudo-c#:

TimeSpan timeout = timeoutPerThread * threads.Count();

foreach (Thread thread in threads)
{
    DateTime start = DateTime.Now;

    if (!thread.Join(timeout))
        throw new TimeoutException();

    timeout -= (DateTime.Now - start);
}

Edit: code is now less pseudo. don't understand why you would mod an answer -2 when the answer you modded +4 is exactly the same, only less detailed.

Java: notify() vs. notifyAll() all over again

While there are some solid answers above, I am surprised by the number of confusions and misunderstandings I have read. This probably proves the idea that one should use java.util.concurrent as much as possible instead of trying to write their own broken concurrent code.

Back to the question: to summarize, the best practice today is to AVOID notify() in ALL situations due to the lost wakeup problem. Anyone who doesn't understand this should not be allowed to write mission critical concurrency code. If you are worried about the herding problem, one safe way to achieve waking one thread up at a time is to:

  1. Build an explicit waiting queue for the waiting threads;
  2. Have each of the thread in the queue wait for its predecessor;
  3. Have each thread call notifyAll() when done.

Or you can use Java.util.concurrent.*, which have already implemented this.

WAITING at sun.misc.Unsafe.park(Native Method)

I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.

In my case, that just fix my progressive increase of similar blocked threads:

  • I've used ExecutorService::awaitTermination(x, TimeUnit) and ExecutorService::shutdownNow() (if necessary) in my finally clause.
  • For information, I've used the following commands to detect thread count & list locked threads:

    ps -u javaAppuser -L|wc -l

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log

    cat threadPrint*.log |grep "pool-"|wc -l

C++ terminate called without an active exception

How to reproduce that error:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() { 
  std::thread t1(task1, "hello"); 
  return 0;
}

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
terminate called without an active exception
Aborted (core dumped)

You get that error because you didn't join or detach your thread.

One way to fix it, join the thread like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() { 
  std::thread t1(task1, "hello"); 
  t1.join();
  return 0;
}

Then compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

The other way to fix it, detach it like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() 
{ 
     {

        std::thread t1(task1, "hello"); 
        t1.detach();

     } //thread handle is destroyed here, as goes out of scope!

     usleep(1000000); //wait so that hello can be printed.
}

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

Read up on detaching C++ threads and joining C++ threads.

How to get the number of threads in a Java process

java.lang.Thread.activeCount()

It will return the number of active threads in the current thread's thread group.

docs: http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#activeCount()

Accessing UI (Main) Thread safely in WPF

Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.

Step 1. Use the following namespaces

using System.Windows;
using System.Threading;
using System.Windows.Threading;

Step 2. Put the following line where you need to update UI

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
    //Update UI here
}));

Syntax

[BrowsableAttribute(false)]
public object Invoke(
  DispatcherPriority priority,
  Delegate method
)

Parameters

priority

Type: System.Windows.Threading.DispatcherPriority

The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.

method

Type: System.Delegate

A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.

Return Value

Type: System.Object

The return value from the delegate being invoked or null if the delegate has no return value.

Version Information

Available since .NET Framework 3.0

Platform.runLater and Task in JavaFX

It can now be changed to lambda version

@Override
public void actionPerformed(ActionEvent e) {
    Platform.runLater(() -> {
        try {
            //an event with a button maybe
            System.out.println("button is clicked");
        } catch (IOException | COSVisitorException ex) {
            Exceptions.printStackTrace(ex);
        }
    });
}

How to check if Thread finished execution

Use Thread.Join(TimeSpan.Zero) It will not block the caller and returns a value indicating whether the thread has completed its work. By the way, that is the standard way of testing all WaitHandle classes as well.

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

If you use mutexes to protect all your data, you really shouldn't need to worry. Mutexes have always provided sufficient ordering and visibility guarantees.

Now, if you used atomics, or lock-free algorithms, you need to think about the memory model. The memory model describes precisely when atomics provide ordering and visibility guarantees, and provides portable fences for hand-coded guarantees.

Previously, atomics would be done using compiler intrinsics, or some higher level library. Fences would have been done using CPU-specific instructions (memory barriers).

Why is Thread.Sleep so harmful

It is the 1).spinning and 2).polling loop of your examples that people caution against, not the Thread.Sleep() part. I think Thread.Sleep() is usually added to easily improve code that is spinning or in a polling loop, so it is just associated with "bad" code.

In addition people do stuff like:

while(inWait)Thread.Sleep(5000); 

where the variable inWait is not accessed in a thread-safe manner, which also causes problems.

What programmers want to see is the threads controlled by Events and Signaling and Locking constructs, and when you do that you won't have need for Thread.Sleep(), and the concerns about thread-safe variable access are also eliminated. As an example, could you create an event handler associated with the FileSystemWatcher class and use an event to trigger your 2nd example instead of looping?

As Andreas N. mentioned, read Threading in C#, by Joe Albahari, it is really really good.

How to obtain a Thread id in Python?

threading.get_ident() works, or threading.current_thread().ident (or threading.currentThread().ident for Python < 2.6).

How can I pass a parameter to a Java Thread?

via constructor of a Runnable or Thread class

class MyThread extends Thread {

    private String to;

    public MyThread(String to) {
        this.to = to;
    }

    @Override
    public void run() {
        System.out.println("hello " + to);
    }
}

public static void main(String[] args) {
    new MyThread("world!").start();
}

When does Java's Thread.sleep throw InterruptedException?

A solid and easy way to handle it in single threaded code would be to catch it and retrow it in a RuntimeException, to avoid the need to declare it for every method.

Producer/Consumer threads using a Queue

This is a very simple code.

import java.util.*;

// @author : rootTraveller, June 2017

class ProducerConsumer {
    public static void main(String[] args) throws Exception {
        Queue<Integer> queue = new LinkedList<>();
        Integer buffer = new Integer(10);  //Important buffer or queue size, change as per need.

        Producer producerThread = new Producer(queue, buffer, "PRODUCER");
        Consumer consumerThread = new Consumer(queue, buffer, "CONSUMER");

        producerThread.start();  
        consumerThread.start();
    }   
}

class Producer extends Thread {
    private Queue<Integer> queue;
    private int queueSize ;

    public Producer (Queue<Integer> queueIn, int queueSizeIn, String ThreadName){
        super(ThreadName);
        this.queue = queueIn;
        this.queueSize = queueSizeIn;
    }

    public void run() {
        while(true){
            synchronized (queue) {
                while(queue.size() == queueSize){
                    System.out.println(Thread.currentThread().getName() + " FULL         : waiting...\n");
                    try{
                        queue.wait();   //Important
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                //queue empty then produce one, add and notify  
                int randomInt = new Random().nextInt(); 
                System.out.println(Thread.currentThread().getName() + " producing... : " + randomInt); 
                queue.add(randomInt); 
                queue.notifyAll();  //Important
            } //synchronized ends here : NOTE
        }
    }
}

class Consumer extends Thread {
    private Queue<Integer> queue;
    private int queueSize;

    public Consumer(Queue<Integer> queueIn, int queueSizeIn, String ThreadName){
        super (ThreadName);
        this.queue = queueIn;
        this.queueSize = queueSizeIn;
    }

    public void run() {
        while(true){
            synchronized (queue) {
                while(queue.isEmpty()){
                    System.out.println(Thread.currentThread().getName() + " Empty        : waiting...\n");
                    try {
                        queue.wait();  //Important
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                //queue not empty then consume one and notify
                System.out.println(Thread.currentThread().getName() + " consuming... : " + queue.remove());
                queue.notifyAll();
            } //synchronized ends here : NOTE
        }
    }
}

How to use the CancellationToken property?

You can create a Task with cancellation token, when you app goto background you can cancel this token.

You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle

var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
    await Task.Delay(10000);
    // call web API
}, cancelToken.Token);

//this stops the Task:
cancelToken.Cancel(false);

Anther solution is user Timer in Xamarin.Forms, stop timer when app goto background https://xamarinhelp.com/xamarin-forms-timer/

Display progress bar while doing some work in C#?

For me the easiest way is definitely to use a BackgroundWorker, which is specifically designed for this kind of task. The ProgressChanged event is perfectly fitted to update a progress bar, without worrying about cross-thread calls

Creating threads - Task.Factory.StartNew vs new Thread()

There is a big difference. Tasks are scheduled on the ThreadPool and could even be executed synchronous if appropiate.

If you have a long running background work you should specify this by using the correct Task Option.

You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.

What is a deadlock?

Let me explain a real world (not actually real) example for a deadlock situation from the crime movies. Imagine a criminal holds an hostage and against that, a cop also holds an hostage who is a friend of the criminal. In this case, criminal is not going to let the hostage go if cop won't let his friend to let go. Also the cop is not going to let the friend of criminal let go, unless the criminal releases the hostage. This is an endless untrustworthy situation, because both sides are insisting the first step from each other.

Criminal & Cop Scene

enter image description here

So simply, when two threads needs two different resources and each of them has the lock of the resource that the other need, it is a deadlock.

Another High Level Explanation of Deadlock : Broken Hearts

You are dating with a girl and one day after an argument, both sides are heart-broken to each other and waiting for an I-am-sorry-and-I-missed-you call. In this situation, both sides want to communicate each other if and only if one of them receives an I-am-sorry call from the other. Because that neither of each is going to start communication and waiting in a passive state, both will wait for the other to start communication which ends up in a deadlock situation.

Can I get Unix's pthread.h to compile in Windows?

There are, as i recall, two distributions of the gnu toolchain for windows: mingw and cygwin.

I'd expect cygwin work - a lot of effort has been made to make that a "stadard" posix environment.

The mingw toolchain uses msvcrt.dll for its runtime and thus will probably expose msvcrt's "thread" api: _beginthread which is defined in <process.h>

Maximum number of threads per process in Linux?

Linux doesn't have a separate threads per process limit, just a limit on the total number of processes on the system (threads are essentially just processes with a shared address space on Linux) which you can view like this:

cat /proc/sys/kernel/threads-max

The default is the number of memory pages/4. You can increase this like:

echo 100000 > /proc/sys/kernel/threads-max

There is also a limit on the number of processes (and hence threads) that a single user may create, see ulimit/getrlimit for details regarding these limits.

How to sleep the thread in node.js without affecting other threads?

If you are referring to the npm module sleep, it notes in the readme that sleep will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:

setTimeout(function() {
  console.log('hello world!');
}, 5000);

For anyone looking to do this using es7 async/await, this example should help:

const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));

const example = async () => {
  console.log('About to snooze without halting the event loop...');
  await snooze(1000);
  console.log('done!');
};

example();

How to use background thread in swift?

Grand Central Dispatch is used to handle multitasking in our iOS apps.

You can use this code

// Using time interval

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
    print("Hello World")
}

// Background thread
queue.sync {
     for i in 0..<10 {
          print("Hello", i)
     }
}

// Main thread
for i in 20..<30 {
     print("Hello", i)
}

More information use this link : https://www.programminghub.us/2018/07/integrate-dispatcher-in-swift.html

C# version of java's synchronized keyword?

Take note, with full paths the line: [MethodImpl(MethodImplOptions.Synchronized)] should look like

[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]

How can I use threading in Python?

With borrowing from this post we know about choosing between the multithreading, multiprocessing, and async/asyncio and their usage.

Python 3 has a new built-in library in order to make concurrency and parallelism: concurrent.futures

So I'll demonstrate through an experiment to run four tasks (i.e. .sleep() method) by Threading-Pool:

from concurrent.futures import ThreadPoolExecutor, as_completed
from time import sleep, time

def concurrent(max_worker):
    futures = []
    tic = time()
    with ThreadPoolExecutor(max_workers=max_worker) as executor:
        futures.append(executor.submit(sleep, 2))  # Two seconds sleep
        futures.append(executor.submit(sleep, 1))
        futures.append(executor.submit(sleep, 7))
        futures.append(executor.submit(sleep, 3))
        for future in as_completed(futures):
            if future.result() is not None:
                print(future.result())
    print(f'Total elapsed time by {max_worker} workers:', time()-tic)

concurrent(5)
concurrent(4)
concurrent(3)
concurrent(2)
concurrent(1)

Output:

Total elapsed time by 5 workers: 7.007831811904907
Total elapsed time by 4 workers: 7.007944107055664
Total elapsed time by 3 workers: 7.003149509429932
Total elapsed time by 2 workers: 8.004627466201782
Total elapsed time by 1 workers: 13.013478994369507

[NOTE]:

  • As you can see in the above results, the best case was 3 workers for those four tasks.
  • If you have a process task instead of I/O bound or blocking (multiprocessing instead of threading) you can change the ThreadPoolExecutor to ProcessPoolExecutor.

iOS - Ensure execution on main thread

This will do it:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   //Your code goes in here
   NSLog(@"Main Thread Code");

}];

Hope this helps!

Do C# Timers elapse on a separate thread?

For System.Timers.Timer:

See Brian Gideon's answer below

For System.Threading.Timer:

MSDN Documentation on Timers states:

The System.Threading.Timer class makes callbacks on a ThreadPool thread and does not use the event model at all.

So indeed the timer elapses on a different thread.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
  // Do some computation here.

  // Update UI after computation.
  dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
  });
});

What is the meaning of the term "thread-safe"?

A more informative question is what makes code not thread safe- and the answer is that there are four conditions that must be true... Imagine the following code (and it's machine language translation)

totalRequests = totalRequests + 1
MOV EAX, [totalRequests]   // load memory for tot Requests into register
INC EAX                    // update register
MOV [totalRequests], EAX   // store updated value back to memory
  1. The first condition is that there are memory locations that are accessible from more than one thread. Typically, these locations are global/static variables or are heap memory reachable from global/static variables. Each thread gets it's own stack frame for function/method scoped local variables, so these local function/method variables, otoh, (which are on the stack) are accessible only from the one thread that owns that stack.
  2. The second condition is that there is a property (often called an invariant), which is associated with these shared memory locations, that must be true, or valid, for the program to function correctly. In the above example, the property is that “totalRequests must accurately represent the total number of times any thread has executed any part of the increment statement”. Typically, this invariant property needs to hold true (in this case, totalRequests must hold an accurate count) before an update occurs for the update to be correct.
  3. The third condition is that the invariant property does NOT hold during some part of the actual update. (It is transiently invalid or false during some portion of the processing). In this particular case, from the time totalRequests is fetched until the time the updated value is stored, totalRequests does not satisfy the invariant.
  4. The fourth and final condition that must occur for a race to happen (and for the code to therefore NOT be "thread-safe") is that another thread must be able to access the shared memory while the invariant is broken, thereby causing inconsistent or incorrect behavior.

Run certain code every n seconds

Save yourself a schizophrenic episode and use the Advanced Python scheduler: http://pythonhosted.org/APScheduler

The code is so simple:

from apscheduler.scheduler import Scheduler

sched = Scheduler()
sched.start()

def some_job():
    print "Every 10 seconds"

sched.add_interval_job(some_job, seconds = 10)

....
sched.shutdown()

How to run a Runnable thread in Android at defined intervals?

I think can improve first solution of Alex2k8 for update correct each second

1.Original code:

public void run() {
    tv.append("Hello World");
    handler.postDelayed(this, 1000);
}

2.Analysis

  • In above cost, assume tv.append("Hello Word") cost T milliseconds, after display 500 times delayed time is 500*T milliseconds
  • It will increase delayed when run long time

3. Solution

To avoid that Just change order of postDelayed(), to avoid delayed:

public void run() {
    handler.postDelayed(this, 1000);
    tv.append("Hello World");
}

Are lists thread-safe?

Here's a comprehensive yet non-exhaustive list of examples of list operations and whether or not they are thread safe. Hoping to get an answer regarding the obj in a_list language construct here.

How do servlets work? Instantiation, sessions, shared variables and multithreading

No. Servlets are not Thread safe

This is allows accessing more than one threads at a time

if u want to make it Servlet as Thread safe ., U can go for

Implement SingleThreadInterface(i) which is a blank Interface there is no

methods

or we can go for synchronize methods

we can make whole service method as synchronized by using synchronized

keyword in front of method

Example::

public Synchronized class service(ServletRequest request,ServletResponse response)throws ServletException,IOException

or we can the put block of the code in the Synchronized block

Example::

Synchronized(Object)

{

----Instructions-----

}

I feel that Synchronized block is better than making the whole method

Synchronized

How can I convert this foreach code to Parallel.ForEach?

These lines Worked for me.

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(lines , options, (item) =>
{
 //My Stuff
});

Example for boost shared_mutex (multiple reads/one write)?

Great response by Jim Morris, I stumbled upon this and it took me a while to figure. Here is some simple code that shows that after submitting a "request" for a unique_lock boost (version 1.54) blocks all shared_lock requests. This is very interesting as it seems to me that choosing between unique_lock and upgradeable_lock allows if we want write priority or no priority.

Also (1) in Jim Morris's post seems to contradict this: Boost shared_lock. Read preferred?

#include <iostream>
#include <boost/thread.hpp>

using namespace std;

typedef boost::shared_mutex Lock;
typedef boost::unique_lock< Lock > UniqueLock;
typedef boost::shared_lock< Lock > SharedLock;

Lock tempLock;

void main2() {
    cout << "10" << endl;
    UniqueLock lock2(tempLock); // (2) queue for a unique lock
    cout << "11" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    lock2.unlock();
}

void main() {
    cout << "1" << endl;
    SharedLock lock1(tempLock); // (1) aquire a shared lock
    cout << "2" << endl;
    boost::thread tempThread(main2);
    cout << "3" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(3));
    cout << "4" << endl;
    SharedLock lock3(tempLock); // (3) try getting antoher shared lock, deadlock here
    cout << "5" << endl;
    lock1.unlock();
    lock3.unlock();
}

Why is setState in reactjs Async instead of Sync?

You can use the following wrap to make sync call

_x000D_
_x000D_
this.setState((state =>{_x000D_
  return{_x000D_
    something_x000D_
  }_x000D_
})
_x000D_
_x000D_
_x000D_

How can one use multi threading in PHP applications

You can use exec() to run a command line script (such as command line php), and if you pipe the output to a file then your script won't wait for the command to finish.

I can't quite remember the php CLI syntax, but you'd want something like:

exec("/path/to/php -f '/path/to/file.php' | '/path/to/output.txt'");

I think quite a few shared hosting servers have exec() disabled by default for security reasons, but might be worth a try.

Which concurrent Queue implementation should I use in Java?

Your question title mentions Blocking Queues. However, ConcurrentLinkedQueue is not a blocking queue.

The BlockingQueues are ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, and SynchronousQueue.

Some of these are clearly not fit for your purpose (DelayQueue, PriorityBlockingQueue, and SynchronousQueue). LinkedBlockingQueue and LinkedBlockingDeque are identical, except that the latter is a double-ended Queue (it implements the Deque interface).

Since ArrayBlockingQueue is only useful if you want to limit the number of elements, I'd stick to LinkedBlockingQueue.

High CPU Utilization in java application - why?

Your first approach should be to find all references to Thread.sleep and check that:

  1. Sleeping is the right thing to do - you should use some sort of wait mechanism if possible - perhaps careful use of a BlockingQueue would help.

  2. If sleeping is the right thing to do, are you sleeping for the right amount of time - this is often a very difficult question to answer.

The most common mistake in multi-threaded design is to believe that all you need to do when waiting for something to happen is to check for it and sleep for a while in a tight loop. This is rarely an effective solution - you should always try to wait for the occurrence.

The second most common issue is to loop without sleeping. This is even worse and is a little less easy to track down.

new Runnable() but no new thread?

A thread is something like some branch. Multi-branched means when there are at least two branches. If the branches are reduced, then the minimum remains one. This one is although like the branches removed, but in general we do not consider it branch.

Similarly when there are at least two threads we call it multi-threaded program. If the threads are reduced, the minimum remains one. Hello program is a single threaded program, but no one needs to know multi-threading to write or run it.

In simple words when a program is not said to be having threads, it means that the program is not a multi-threaded program, more over in true sense it is a single threaded program, in which YOU CAN put your code as if it is multi-threaded.

Below a useless code is given, but it will suffice to do away with your some confusions about Runnable. It will print "Hello World".

class NamedRunnable implements Runnable {

    public void run() { // The run method prints a message to standard output.
        System.out.println("Hello World");
    }

    public static void main(String[]arg){ 
        NamedRunnable namedRunnable = new NamedRunnable( );
        namedRunnable.run();
    } 
}

Is there a way of setting culture for a whole application? All current threads and new threads?

If you are using resources, you can manually force it by:

Resource1.Culture = new System.Globalization.CultureInfo("fr"); 

In the resource manager, there is an auto generated code that is as follows:

/// <summary>
///   Overrides the current thread's CurrentUICulture property for all
///   resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
    get {
        return resourceCulture;
    }
    set {
        resourceCulture = value;
    }
}

Now every time you refer to your individual string within this resource, it overrides the culture (thread or process) with the specified resourceCulture.

You can either specify language as in "fr", "de" etc. or put the language code as in 0x0409 for en-US or 0x0410 for it-IT. For a full list of language codes please refer to: Language Identifiers and Locales

How do I terminate a thread in C++11?

  1. You could call std::terminate() from any thread and the thread you're referring to will forcefully end.

  2. You could arrange for ~thread() to be executed on the object of the target thread, without a intervening join() nor detach() on that object. This will have the same effect as option 1.

  3. You could design an exception which has a destructor which throws an exception. And then arrange for the target thread to throw this exception when it is to be forcefully terminated. The tricky part on this one is getting the target thread to throw this exception.

Options 1 and 2 don't leak intra-process resources, but they terminate every thread.

Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.

There is no portable way in C++11 (that I'm aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads). There was no motivation to design such a feature.

A std::thread may have this member function:

native_handle_type native_handle();

You might be able to use this to call an OS-dependent function to do what you want. For example on Apple's OS's, this function exists and native_handle_type is a pthread_t. If you are successful, you are likely to leak resources.

Programmatically find the number of cores on a machine

you can use WMI in .net too but you're then dependent on the wmi service running etc. Sometimes it works locally, but then fail when the same code is run on servers. I believe that's a namespace issue, related to the "names" whose values you're reading.

When and how should I use a ThreadLocal variable?

Two use cases where threadlocal variable can be used -
1- When we have a requirement to associate state with a thread (e.g., a user ID or Transaction ID). That usually happens with a web application that every request going to a servlet has a unique transactionID associated with it.

// This class will provide a thread local variable which
// will provide a unique ID for each thread
class ThreadId {
    // Atomic integer containing the next thread ID to be assigned
    private static final AtomicInteger nextId = new AtomicInteger(0);

    // Thread local variable containing each thread's ID
    private static final ThreadLocal<Integer> threadId =
        ThreadLocal.<Integer>withInitial(()-> {return nextId.getAndIncrement();});

    // Returns the current thread's unique ID, assigning it if necessary
    public static int get() {
        return threadId.get();
    }
}

Note that here the method withInitial is implemented using lambda expression.
2- Another use case is when we want to have a thread safe instance and we don't want to use synchronization as the performance cost with synchronization is more. One such case is when SimpleDateFormat is used. Since SimpleDateFormat is not thread safe so we have to provide mechanism to make it thread safe.

public class ThreadLocalDemo1 implements Runnable {
    // threadlocal variable is created
    private static final ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected SimpleDateFormat initialValue(){
            System.out.println("Initializing SimpleDateFormat for - " + Thread.currentThread().getName() );
            return new SimpleDateFormat("dd/MM/yyyy");
        }
    };

    public static void main(String[] args) {
        ThreadLocalDemo1 td = new ThreadLocalDemo1();
        // Two threads are created
        Thread t1 = new Thread(td, "Thread-1");
        Thread t2 = new Thread(td, "Thread-2");
        t1.start();
        t2.start();
    }

    @Override
    public void run() {
        System.out.println("Thread run execution started for " + Thread.currentThread().getName());
        System.out.println("Date formatter pattern is  " + dateFormat.get().toPattern());
        System.out.println("Formatted date is " + dateFormat.get().format(new Date()));
    } 

}

Avoid synchronized(this) in Java?

While you are using synchronized(this) you are using the class instance as a lock itself. This means that while lock is acquired by thread 1, the thread 2 should wait.

Suppose the following code:

public void method1() {
    // do something ...
    synchronized(this) {
        a ++;      
    }
    // ................
}


public void method2() {
    // do something ...
    synchronized(this) {
        b ++;      
    }
    // ................
}

Method 1 modifying the variable a and method 2 modifying the variable b, the concurrent modification of the same variable by two threads should be avoided and it is. BUT while thread1 modifying a and thread2 modifying b it can be performed without any race condition.

Unfortunately, the above code will not allow this since we are using the same reference for a lock; This means that threads even if they are not in a race condition should wait and obviously the code sacrifices concurrency of the program.

The solution is to use 2 different locks for two different variables:

public class Test {

    private Object lockA = new Object();
    private Object lockB = new Object();

    public void method1() {
        // do something ...
        synchronized(lockA) {
            a ++;      
        }
        // ................
    }


    public void method2() {
        // do something ...
        synchronized(lockB) {
            b ++;      
        }
        // ................
    }

}

The above example uses more fine grained locks (2 locks instead one (lockA and lockB for variables a and b respectively) and as a result allows better concurrency, on the other hand it became more complex than the first example ...

How do I update the GUI from another thread?

just use synchronization context of ui

using System.Threading;

// ...

public partial class MyForm : Form
{
    private readonly SynchronizationContext uiContext;

    public MyForm()
    {
        InitializeComponent();
        uiContext = SynchronizationContext.Current; // get ui thread context
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(() =>
            {// set ui thread context to new thread context                            
             // for operations with ui elements to be performed in proper thread
             SynchronizationContext
                 .SetSynchronizationContext(uiContext);
             label1.Text = "some text";
            });
        t.Start();
    }
}

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

Look at HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5\. One of these must be true:

  • The Version value in that key should be 3.5.30729.01
  • Or the SP value in the same key should be 1

In C# (taken from the first comment), you could do something along these lines:

const string name = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
RegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);
var version = subKey.GetValue("Version").ToString();
var servicePack = subKey.GetValue("SP").ToString();

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

Note: I had the same problem, and it was because the referenced field was in a different collation in the 2 different tables (they had exact same type).

Make sure all your referenced fields have the same type AND the same collation!

How to send multiple data fields via Ajax?

I am new to AJAX and I have tried this and it works well.

function q1mrks(country,m) {
  // alert("hellow");
  if (country.length==0) {
    //alert("hellow");
    document.getElementById("q1mrks").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("q1mrks").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","../location/cal_marks.php?q1mrks="+country+"&marks="+m,true);
  //mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
  xmlhttp.send();
}

Left-pad printf with spaces

If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.

char *ptr = "Hello";
printf("%40s\n", ptr);

That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).

If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf statements like the one above, or do it in a loop, changing the value of ptr each time.

Notepad++: Multiple words search in a file (may be in different lines)?

<shameless-plug>

Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here

Feel free to post any issues/suggestions here.

</shameless-plug>

How do I write stderr to a file while using "tee" with a pipe?

This may be useful for people finding this via google. Simply uncomment the example you want to try out. Of course, feel free to rename the output files.

#!/bin/bash

STATUSFILE=x.out
LOGFILE=x.log

### All output to screen
### Do nothing, this is the default


### All Output to one file, nothing to the screen
#exec > ${LOGFILE} 2>&1


### All output to one file and all output to the screen
#exec > >(tee ${LOGFILE}) 2>&1


### All output to one file, STDOUT to the screen
#exec > >(tee -a ${LOGFILE}) 2> >(tee -a ${LOGFILE} >/dev/null)


### All output to one file, STDERR to the screen
### Note you need both of these lines for this to work
#exec 3>&1
#exec > >(tee -a ${LOGFILE} >/dev/null) 2> >(tee -a ${LOGFILE} >&3)


### STDOUT to STATUSFILE, stderr to LOGFILE, nothing to the screen
#exec > ${STATUSFILE} 2>${LOGFILE}


### STDOUT to STATUSFILE, stderr to LOGFILE and all output to the screen
#exec > >(tee ${STATUSFILE}) 2> >(tee ${LOGFILE} >&2)


### STDOUT to STATUSFILE and screen, STDERR to LOGFILE
#exec > >(tee ${STATUSFILE}) 2>${LOGFILE}


### STDOUT to STATUSFILE, STDERR to LOGFILE and screen
#exec > ${STATUSFILE} 2> >(tee ${LOGFILE} >&2)


echo "This is a test"
ls -l sdgshgswogswghthb_this_file_will_not_exist_so_we_get_output_to_stderr_aronkjegralhfaff
ls -l ${0}

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

you can covert domain to IP address because every Domain have specific IP address, then you will solve that issue. I hope this will help you.

How to avoid Python/Pandas creating an index in a saved csv?

If you want no index, read file using:

import pandas as pd
df = pd.read_csv('file.csv', index_col=0)

save it using

df.to_csv('file.csv', index=False)

Root element is missing

If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.

I wrote a quick console app to run your code and parse the file and it works fine for me.

Mac OS X - EnvironmentError: mysql_config not found

brew install mysql added mysql to /usr/local/Cellar/..., so I needed to add :/usr/local/Cellar/ to my $PATH and then which mysql_config worked!

jQuery - Follow the cursor with a DIV

You don't need jQuery for this. Here's a simple working example:

<!DOCTYPE html>
<html>
    <head>
        <title>box-shadow-experiment</title>
        <style type="text/css">
            #box-shadow-div{
                position: fixed;
                width: 1px;
                height: 1px;
                border-radius: 100%;
                background-color:black;
                box-shadow: 0 0 10px 10px black;
                top: 49%;
                left: 48.85%;
            }
        </style>
        <script type="text/javascript">
            window.onload = function(){
                var bsDiv = document.getElementById("box-shadow-div");
                var x, y;
    // On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
                window.addEventListener('mousemove', function(event){
                    x = event.clientX;
                    y = event.clientY;                    
                    if ( typeof x !== 'undefined' ){
                        bsDiv.style.left = x + "px";
                        bsDiv.style.top = y + "px";
                    }
                }, false);
            }
        </script>
    </head>
    <body>
        <div id="box-shadow-div"></div>
    </body>
</html>

I chose position: fixed; so scrolling wouldn't be an issue.

Using Caps Lock as Esc in Mac OS X

Edit: As described in this answer, newer versions of MacOS now have native support for rebinding Caps Lock to Escape. Thus it is no longer necessary to install third-party software to achieve this.


Here's my attempt at a comprehensive, visual walk-through answer (with links) of how to achieve this using Seil (formerly known as PCKeyboardHack).

  1. First, go into the System Preferences, choose Keyboard, then the Keyboard Tab (first tab), and click Modifier Keys:

Step 1

In the popup dialog set Caps Lock Key to No Action:

choose no action

2) Now, click here to download Seil and install it:

3) After the installation you will have a new Application installed ( Mountain Lion and newer ) and if you are on an older OS you may have to check for a new System Preferences pane:

open seil or the preference pane

4) Check the box that says "Change Caps Lock" and enter "53" as the code for the escape key:

set the keyboard code

And you're done! If it doesn't work immediately, you may need to restart your machine.

Impressed? Want More Control?

You may also want to check out KeyRemap4MacBook which is actually the flagship keyboard remapping tool from pqrs.org - it's also free.

If you like these tools you can make a donation. I have no affiliation with them but I've been using these tools for a long time and have to say the guys over there have been doing an excellent job maintaining these, adding features and fixing bugs.

Here's a screenshot to show a few of the (hundreds of) pre-selectable options:

Picture 1.png

PQRS also has a great utility called NoEjectDelay that you can use in combination with KeyRemap4MacBook for reprogramming the Eject key. After a little tweaking I have mine set to toggle the AirPort Wifi.

These utilities offer unlimited flexibility when remapping the Mac keyboard. Have fun!

Error when deploying an artifact in Nexus

This can also happen if you have a naming policy around version, prohibiting the version# you are trying to deploy. In my case I was trying to upload a version (to release repo) 2.0.1 but later found out that our nexus configuration doesn't allow anything other than whole number for releases.

I tried later with version 2 and deployed it successfully.

The error message definitely dosen't help:

Return code is: 400, ReasonPhrase: Repository does not allow updating assets: maven-releases-xxx. -> [Help 1]

A better message could have been version 2.0.1 violates naming policy

How to replace DOM element in place using Javascript?

This question is very old, but I found myself studying for a Microsoft Certification, and in the study book it was suggested to use:

oldElement.replaceNode(newElement)

I looked it up and it seems to only be supported in IE. Doh..

I thought I'd just add it here as a funny side note ;)

Why can't I push to this bare repository?

This related question's answer provided the solution for me... it was just a dumb mistake:

Remember to commit first!

https://stackoverflow.com/a/7572252

If you have not yet committed to your local repo, there is nothing to push, but the Git error message you get back doesn't help you too much.

'Access denied for user 'root'@'localhost' (using password: NO)'

when trying to run this command i got the same error

sudo mysqladmin create asteriskcdrdba

i simply add a few lines to the code

-u root -p

and pressed the enter key. i then typed my password and hit enter. Linux liked my command as nothing more was displayed

so maybe try

sudo <your command here> -u <username> -p

after that hit enter and enter your password

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

For iOS<10

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    //-- Set Notification
    if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) 
    {
           // iOS 8 Notifications
           [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

           [application registerForRemoteNotifications];
    }
    else
    {
          // iOS < 8 Notifications
          [application registerForRemoteNotificationTypes:
                     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
    }

     //--- your custom code
     return YES;
}

For iOS10

https://stackoverflow.com/a/39383027/3560390

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Take a look at the DateDiff() function.

-- Syntax
-- DATEDIFF ( datepart , startdate , enddate )

-- Example usage
SELECT DATEDIFF(DAY, GETDATE(), GETDATE() + 1) AS DayDiff
SELECT DATEDIFF(MINUTE, GETDATE(), GETDATE() + 1) AS MinuteDiff
SELECT DATEDIFF(SECOND, GETDATE(), GETDATE() + 1) AS SecondDiff
SELECT DATEDIFF(WEEK, GETDATE(), GETDATE() + 1) AS WeekDiff
SELECT DATEDIFF(HOUR, GETDATE(), GETDATE() + 1) AS HourDiff
...

You can see it in action / play with it here

Setting up redirect in web.config file

In case that you need to add the http redirect in many sites, you could use it as a c# console program:

   class Program
{
    static int Main(string[] args)
    {
        if (args.Length < 3)
        {
            Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com");
            return 1;
        }

        if (args.Length == 3)
        {
            if (args[0].ToLower() == "-insert-redirect")
            {
                var path = args[1];
                var value = args[2];

                if (InsertRedirect(path, value))
                    Console.WriteLine("Redirect added.");
                return 0;
            }
        }

        Console.WriteLine("Wrong parameters.");
        return 1;

    }

    static bool InsertRedirect(string path, string value)
    {
        try
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(path);

            // This should find the appSettings node (should be only one):
            XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer");

            var existNode = nodeAppSettings.SelectSingleNode("httpRedirect");
            if (existNode != null)
                return false;

            // Create new <add> node
            XmlNode nodeNewKey = doc.CreateElement("httpRedirect");

            XmlAttribute attributeEnable = doc.CreateAttribute("enabled");
            XmlAttribute attributeDestination = doc.CreateAttribute("destination");
            //XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus");

            // Assign values to both - the key and the value attributes:

            attributeEnable.Value = "true";
            attributeDestination.Value = value;
            //attributeResponseStatus.Value = "Permanent";

            // Add both attributes to the newly created node:
            nodeNewKey.Attributes.Append(attributeEnable);
            nodeNewKey.Attributes.Append(attributeDestination);
            //nodeNewKey.Attributes.Append(attributeResponseStatus);

            // Add the node under the 
            nodeAppSettings.AppendChild(nodeNewKey);
            doc.Save(path);

            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine($"Exception adding redirect: {e.Message}");
            return false;
        }
    }
}

How prevent CPU usage 100% because of worker process in iis

I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.

Solution:

First of all find the application which is causing heavy memory usage.

You can find this in the Details section of the Task Manager.

Next.

  1. Open the IIS manager.
  2. Click on Application Pools. You'll find many application pools which your system is using.
  3. Now from the task manager you've found which application is causing the heavy memory consumption. There would be multiple options for that and you need to select the one which is having '1' in it's Application column of your web application.
  4. When you click on the application pool on the right hand side you'll see an option Advance settings under Edit Application pools. Go to Advanced Settings. 5.Now under General category set the Enable 32-bit Applications to True
  5. Restart the IIS server or you can see the consumption goes down in performance section of your Task Manager.

If this solution works for you please add a comment so that I can know.

How to convert a char to a String?

  char vIn = 'A';
  String vOut = Character.toString(vIn);

For these types of conversion, I have site bookmarked called https://www.converttypes.com/ It helps me quickly get the conversion code for most of the languages I use.

How to grep a string in a directory and all its subdirectories?

grep -r -e string directory

-r is for recursive; -e is optional but its argument specifies the regex to search for. Interestingly, POSIX grep is not required to support -r (or -R), but I'm practically certain that System V grep did, so in practice they (almost) all do. Some versions of grep support -R as well as (or conceivably instead of) -r; AFAICT, it means the same thing.

How do I use a third-party DLL file in Visual Studio C++?

In order to use Qt with dynamic linking you have to specify the lib files (usually qtmaind.lib, QtCored4.lib and QtGuid4.lib for the "Debug" configration) in
Properties » Linker » Input » Additional Dependencies.

You also have to specify the path where the libs are, namely in
Properties » Linker » General » Additional Library Directories.

And you need to make the corresponding .dlls are accessible at runtime, by either storing them in the same folder as your .exe or in a folder that is on your path.

Select tableview row programmatically

Like Jaanus told:

Calling this (-selectRowAtIndexPath:animated:scrollPosition:) method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor will it send UITableViewSelectionDidChangeNotification notifications to observers.

So you just have to call the delegate method yourself.

For example:

Swift 3 version:

let indexPath = IndexPath(row: 0, section: 0);
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
self.tableView(self.tableView, didSelectRowAt: indexPath)

ObjectiveC version:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath 
                            animated:YES 
                      scrollPosition:UITableViewScrollPositionNone];
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];

Swift 2.3 version:

 let indexPath = NSIndexPath(forRow: 0, inSection: 0);
 self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
 self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)

Should Jquery code go in header or footer?

All scripts should be loaded last

In just about every case, it's best to place all your script references at the end of the page, just before </body>.

If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer attribute so that the browser knows to download your scripts after the HTML has been downloaded:

<script src="my.js" type="text/javascript" defer="defer"></script>

Edge cases

There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head> tag without the defer attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.


Further caveats

There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

One thing that is missed in the responses....

If there are multiple results, FirstOrDefault without an order by can bring back different results based on which ever index strategy happened to be used by the server.

Personally I cannot stand seeing FirstOrDefault in code because to me it says the developer didn't care about the results. With an order by though it can be useful as a way of enforcing the latest/earliest. I've had to correct a lot of issues caused by careless developers using FirstOrDefault.

Adding timestamp to a filename with mv in BASH

First, thanks for the answers above! They lead to my solution.

I added this alias to my .bashrc file:

alias now='date +%Y-%m-%d-%H.%M.%S'

Now when I want to put a time stamp on a file such as a build log I can do this:

mvn clean install | tee build-$(now).log

and I get a file name like:

build-2021-02-04-03.12.12.log

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

in my case, I had a line Class.forName("com.mysql.jdbc.Driver"); after removing this line code works fine if you have any line for loading "com.mysql.jdbc.Driver" remove it, it doesn't require any more

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

<?php header("Access-Control-Allow-Origin: http://example.com"); ?>

This command disables only first console warning info

console

Result: console result

VBA equivalent to Excel's mod function

Function Remainder(Dividend As Variant, Divisor As Variant) As Variant
    Remainder = Dividend - Divisor * Int(Dividend / Divisor)
End Function

This function always works and is the exact copy of the Excel function.

fatal: could not create work tree dir 'kivy'

Your current directory does not has the write/create permission to create kivy directory, thats why occuring this problem.

Your current directory give 777 rights and try it.

sudo chmod 777 DIR_NAME
cd DIR_NAME
git clone https://github.com/mygitusername/kivy.git

How to set Highcharts chart maximum yAxis value

Alternatively one can use the setExtremes method also,

yAxis.setExtremes(0, 100);

Or if only one value is needed to be set, just leave other as null

yAxis.setExtremes(null, 100);

"std::endl" vs "\n"

I've always had a habit of just using std::endl because it is easy for me to see.

Creating and returning Observable from Angular 2 Service

In the service.ts file -

a. import 'of' from observable/of
b. create a json list
c. return json object using Observable.of()
Ex. -

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

@Injectable()
export class ClientListService {
    private clientList;

    constructor() {
        this.clientList = [
            {name: 'abc', address: 'Railpar'},
            {name: 'def', address: 'Railpar 2'},
            {name: 'ghi', address: 'Panagarh'},
            {name: 'jkl', address: 'Panagarh 2'},
        ];
    }

    getClientList () {
        return Observable.of(this.clientList);
    }
};

In the component where we are calling the get function of the service -

this.clientListService.getClientList().subscribe(res => this.clientList = res);

Linux command line howto accept pairing for bluetooth device without pin

Entering a PIN is actually an outdated method of pairing, now called Legacy Pairing. Secure Simple Pairing Mode is available in Bluetooth v2.1 and later, which comprises most modern Bluetooth devices. SSPMode authentication is handled by the Bluetooth protocol stack and thus works without user interaction.

Here is how one might go about connecting to a device:

# hciconfig hci0 sspmode 1
# hciconfig hci0 sspmode
hci0:   Type: BR/EDR  Bus: USB
BD Address: AA:BB:CC:DD:EE:FF  ACL MTU: 1021:8  SCO MTU: 64:1
Simple Pairing mode: Enabled
# hciconfig hci0 piscan
# sdptool add SP
# hcitool scan
    00:11:22:33:44:55    My_Device
# rfcomm connect /dev/rfcomm0 00:11:22:33:44:55 1 &
Connected /dev/rfcomm0 to 00:11:22:33:44:55 on channel 1
Press CTRL-C for hangup

This would establish a serial connection to the device.

How do I remove trailing whitespace using a regular expression?

To remove trailing whitespace while also preserving whitespace-only lines, you want the regex to only remove trailing whitespace after non-whitespace characters. So you need to first check for a non-whitespace character. This means that the non-whitespace character will be included in the match, so you need to include it in the replacement.

Regex: ([^ \t\r\n])[ \t]+$

Replacement: \1 or $1, depending on the IDE

How to find MySQL process list and to kill those processes?

You can do something like this to check if any mysql process is running or not:

ps aux | grep mysqld
ps aux | grep mysql

Then if it is running you can killall by using(depending on what all processes are running currently):

killall -9 mysql
killall -9 mysqld
killall -9 mysqld_safe    

force Maven to copy dependencies into target/lib

If you make your project a war or ear type maven will copy the dependencies.

How to access the contents of a vector from a pointer to the vector in C++?

There are a lot of solutions. For example you can use at() method.

*I assumed that you a looking for equivalent to [] operator.

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

spring.jackson.serialization-inclusion=non_null used to work for us

But when we upgraded spring boot version to 1.4.2.RELEASE or higher, it stopped working.

Now, another property spring.jackson.default-property-inclusion=non_null is doing the magic.

in fact, serialization-inclusion is deprecated. This is what my intellij throws at me.

Deprecated: ObjectMapper.setSerializationInclusion was deprecated in Jackson 2.7

So, start using spring.jackson.default-property-inclusion=non_null instead

How to enable CORS in AngularJs

You don't. The server you are making the request to has to implement CORS to grant JavaScript from your website access. Your JavaScript can't grant itself permission to access another website.

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

PHP json_decode() returns NULL with valid JSON?

I've solved this issue by printing the JSON, and then checking the page source (CTRL/CMD + U):

print_r(file_get_contents($url));

Turned out there was a trailing <pre> tag.

Finding moving average from data points in Python

As numpy.convolve is pretty slow, those who need a fast performing solution might prefer an easier to understand cumsum approach. Here is the code:

cumsum_vec = numpy.cumsum(numpy.insert(data, 0, 0)) 
ma_vec = (cumsum_vec[window_width:] - cumsum_vec[:-window_width]) / window_width

where data contains your data, and ma_vec will contain moving averages of window_width length.

On average, cumsum is about 30-40 times faster than convolve.

Node.js spawn child process and get terminal output live

I had a little trouble getting logging output from the "npm install" command when I spawned npm in a child process. The realtime logging of dependencies did not show in the parent console.

The simplest way to do what the original poster wants seems to be this (spawn npm on windows and log everything to parent console):

var args = ['install'];

var options = {
    stdio: 'inherit' //feed all child process logging into parent process
};

var childProcess = spawn('npm.cmd', args, options);
childProcess.on('close', function(code) {
    process.stdout.write('"npm install" finished with code ' + code + '\n');
});

iOS - Ensure execution on main thread

When you're using iOS >= 4

dispatch_async(dispatch_get_main_queue(), ^{
  //Your main thread code goes in here
  NSLog(@"Im on the main thread");       
});

Node.js connect only works on localhost

Most probably your server socket is bound to the loopback IP address 127.0.0.1 instead of the "all IP addresses" symbolic IP 0.0.0.0 (note this is NOT a netmask). To confirm this, run sudo netstat -ntlp (If you are on linux) or netstat -an -f inet -p tcp | grep LISTEN (OSX) and check which IP your process is bound to (look for the line with ":3000"). If you see "127.0.0.1", that's the problem. Fix it by passing "0.0.0.0" to the listen call:

var app = connect().use(connect.static('public')).listen(3000, "0.0.0.0");

The correct way to read a data file into an array

Just reading the file into an array, one line per element, is trivial:

open my $handle, '<', $path_to_file;
chomp(my @lines = <$handle>);
close $handle;

Now the lines of the file are in the array @lines.

If you want to make sure there is error handling for open and close, do something like this (in the snipped below, we open the file in UTF-8 mode, too):

my $handle;
unless (open $handle, "<:encoding(utf8)", $path_to_file) {
   print STDERR "Could not open file '$path_to_file': $!\n";
   # we return 'undefined', we could also 'die' or 'croak'
   return undef
}
chomp(my @lines = <$handle>);
unless (close $handle) {
   # what does it mean if close yields an error and you are just reading?
   print STDERR "Don't care error while closing '$path_to_file': $!\n";
} 

SQL Query Multiple Columns Using Distinct on One Column Only

I suppose the easiest and the best solution is using OUTER APPLY. You only use one field with DISTINCT but to retrieve more data about that record, you utilize OUTER APPLY.

To test the solution, execute following query which firstly creates a temp table then retrieves data:

 DECLARE @tblFruit TABLE (tblFruit_ID int, tblFruit_FruitType varchar(10), tblFruit_FruitName varchar(50))
 SET NOCOUNT ON
 INSERT @tblFruit VALUES (1,'Citrus ','Orange')
 INSERT @tblFruit VALUES (2,'Citrus','Lime')
 INSERT @tblFruit VALUES (3,'Citrus','Lemon')
 INSERT @tblFruit VALUES (4,'Seed','Cherry')
 INSERT @tblFruit VALUES (5,'Seed','Banana')
   
SELECT DISTINCT (f.tblFruit_FruitType), outter_f.tblFruit_ID
FROM @tblFruit AS f
OUTER APPLY (
    SELECT TOP(1) *
    FROM @tblFruit AS inner_f
    WHERE inner_f.tblFruit_FruitType = f.tblFruit_FruitType
) AS outter_f

The result will be:

Citrus 1

Seed 4

How to set host_key_checking=false in ansible inventory file?

I could not use:

ansible_ssh_common_args='-o StrictHostKeyChecking=no'

in inventory file. It seems ansible does not consider this option in my case (ansible 2.0.1.0 from pip in ubuntu 14.04)

I decided to use:

server ansible_host=192.168.1.1 ansible_ssh_common_args= '-o UserKnownHostsFile=/dev/null'

It helped me.

Also you could set this variable in group instead for each host:

[servers_group:vars]
ansible_ssh_common_args='-o UserKnownHostsFile=/dev/null'

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

If you are using jsvc to run tomcat as tomcat (run /etc/init.d/tomcat as root), edit /etc/init.d/tomcat and add $CATALINA_HOME/bin/tomcat-juli.jar to CLASSPATH.

How to escape % in String.Format?

This is a stronger regex replace that won't replace %% that are already doubled in the input.

str = str.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%");

Fill background color left to right CSS

If you are like me and need to change color of text itself also while in the same time filling the background color check my solution.

Steps to create:

  1. Have two text, one is static colored in color on hover, and the other one in default state color which you will be moving on hover
  2. On hover move wrapper of the not static one text while in the same time move inner text of that wrapper to the opposite direction.
  3. Make sure to add overflow hidden where needed

Good thing about this solution:

  • Support IE9, uses only transform
  • Button (or element you are applying animation) is fluid in width, so no fixed values are being used here

Not so good thing about this solution:

  • A really messy markup, could be solved by using pseudo elements and att(data)?
  • There is some small glitch in animation when having more then one button next to each other, maybe it could be easily solved but I didn't take much time to investigate yet.

Check the pen ---> https://codepen.io/nikolamitic/pen/vpNoNq

<button class="btn btn--animation-from-right">
  <span class="btn__text-static">Cover left</span>
  <div class="btn__text-dynamic">
    <span class="btn__text-dynamic-inner">Cover left</span>
  </div>
</button>

.btn {
  padding: 10px 20px;
  position: relative;

  border: 2px solid #222;
  color: #fff;
  background-color: #222;
  position: relative;

  overflow: hidden;
  cursor: pointer;

  text-transform: uppercase;
  font-family: monospace;
  letter-spacing: -1px;

  [class^="btn__text"] {
    font-size: 24px;
  }

  .btn__text-dynamic,
  .btn__text-dynamic-inner {    
    display: flex;
    justify-content: center;
    align-items: center;

    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    z-index: 2;

    transition: all ease 0.5s;
  }

  .btn__text-dynamic {
    background-color: #fff;
    color: #222;

    overflow: hidden;
  }

  &:hover {
    .btn__text-dynamic {
      transform: translateX(-100%);
    }
    .btn__text-dynamic-inner {
      transform: translateX(100%);
    }
  }
}

.btn--animation-from-right {
    &:hover {
    .btn__text-dynamic {
      transform: translateX(100%);
    }
    .btn__text-dynamic-inner {
      transform: translateX(-100%);
    }
  }
}

You can remove .btn--animation-from-right modifier if you want to animate to the left.

Can someone post a well formed crossdomain.xml sample?

If you're using webservices, you'll also need the 'allow-http-request-headers-from' element. Here's our default, development, 'allow everything' policy.

<?xml version="1.0" ?>
<cross-domain-policy>
  <site-control permitted-cross-domain-policies="master-only"/>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>

JQuery .hasClass for multiple values in an if statement

var classes = $('html')[0].className;

if (classes.indexOf('m320') != -1 || classes.indexOf('m768') != -1) {
    //do something
}

Debugging with command-line parameters in Visual Studio

Yes, it's in the Debugging section of the properties page of the project.

In Visual Studio since 2008: right-click the project, choose Properties, go to the Debugging section -- there is a box for "Command Arguments". (Tip: not solution, but project).

A tool to convert MATLAB code to Python

There are several tools for converting Matlab to Python code.

The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).

Other options include:

  • LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
  • OMPC: Matlab to Python (a bit outdated).

Also, for those interested in an interface between the two languages and not conversion:

  • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
  • Python-Matlab wormholes: both directions of interaction supported.
  • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
  • PyMat: Control Matlab session from Python.
  • pymat2: continuation of the seemingly abandoned PyMat.
  • mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
  • oct2py: run GNU Octave commands from within Python.
  • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange.
  • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
  • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.

Btw might be helpful to look here for other migration tips:

On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

How do I set the selected item in a drop down box

This is the solution that I came up with...

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">   
    <select name="select_month">
        <?php
            if (isset($_POST['select_month'])) {
                if($_POST["select_month"] == "January"){
                    echo '<option value="January" selected="selected">January</option><option value="February">February</option>';
                }
                elseif($_POST["select_month"] == "February"){
                    echo '<option value="January">January</option><option value="February" selected="selected">February</option>';
                }
            }
            else{
                echo '<option value="January">January</option><option value="February">February</option>';
            }
        ?>
    </select>
    <input name="submit_button" type="submit" value="Search Month">
</form>

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

FWIW, here's a lightweight bitmap-cache I coded and have used for a few months. It's not all-the-bells-and-whistles, so read the code before you use it.

/**
 * Lightweight cache for Bitmap objects. 
 * 
 * There is no thread-safety built into this class. 
 * 
 * Note: you may wish to create bitmaps using the application-context, rather than the activity-context. 
 * I believe the activity-context has a reference to the Activity object. 
 * So for as long as the bitmap exists, it will have an indirect link to the activity, 
 * and prevent the garbaage collector from disposing the activity object, leading to memory leaks. 
 */
public class BitmapCache { 

    private Hashtable<String,ArrayList<Bitmap>> hashtable = new Hashtable<String, ArrayList<Bitmap>>();  

    private StringBuilder sb = new StringBuilder(); 

    public BitmapCache() { 
    } 

    /**
     * A Bitmap with the given width and height will be returned. 
     * It is removed from the cache. 
     * 
     * An attempt is made to return the correct config, but for unusual configs (as at 30may13) this might not happen.  
     * 
     * Note that thread-safety is the caller's responsibility. 
     */
    public Bitmap get(int width, int height, Bitmap.Config config) { 
        String key = getKey(width, height, config); 
        ArrayList<Bitmap> list = getList(key); 
        int listSize = list.size();
        if (listSize>0) { 
            return list.remove(listSize-1); 
        } else { 
            try { 
                return Bitmap.createBitmap(width, height, config);
            } catch (RuntimeException e) { 
                // TODO: Test appendHockeyApp() works. 
                App.appendHockeyApp("BitmapCache has "+hashtable.size()+":"+listSize+" request "+width+"x"+height); 
                throw e ; 
            }
        }
    }

    /**
     * Puts a Bitmap object into the cache. 
     * 
     * Note that thread-safety is the caller's responsibility. 
     */
    public void put(Bitmap bitmap) { 
        if (bitmap==null) return ; 
        String key = getKey(bitmap); 
        ArrayList<Bitmap> list = getList(key); 
        list.add(bitmap); 
    }

    private ArrayList<Bitmap> getList(String key) {
        ArrayList<Bitmap> list = hashtable.get(key);
        if (list==null) { 
            list = new ArrayList<Bitmap>(); 
            hashtable.put(key, list); 
        }
        return list;
    } 

    private String getKey(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Config config = bitmap.getConfig();
        return getKey(width, height, config);
    }

    private String getKey(int width, int height, Config config) {
        sb.setLength(0); 
        sb.append(width); 
        sb.append("x"); 
        sb.append(height); 
        sb.append(" "); 
        switch (config) {
        case ALPHA_8:
            sb.append("ALPHA_8"); 
            break;
        case ARGB_4444:
            sb.append("ARGB_4444"); 
            break;
        case ARGB_8888:
            sb.append("ARGB_8888"); 
            break;
        case RGB_565:
            sb.append("RGB_565"); 
            break;
        default:
            sb.append("unknown"); 
            break; 
        }
        return sb.toString();
    }

}

Dialog with transparent background in Android

I've faced the simpler problem and the solution i came up with was applying a transparent bachground THEME. Write these lines in your styles

    <item name="android:windowBackground">@drawable/blue_searchbuttonpopupbackground</item>
</style>
<style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
</style>

And then add

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

in your main manifest file , inside the block of the dialog activity.

Plus in your dialog activity XML set

 android:background= "#00000000"

How to get the size of a varchar[n] field in one SQL statement?

I was looking for the TOTAL size of the column and hit this article, my solution is based off of MarcE's.

SELECT sum(DATALENGTH(your_field)) AS FIELDSIZE FROM your_table

How do I check for null values in JavaScript?

Actually I think you may need to use if (value !== null || value !== undefined) because if you use if (value) you may also filter 0 or false values.

Consider these two functions:

const firstTest = value => {
    if (value) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}
const secondTest = value => {
    if (value !== null && value !== undefined) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}

firstTest(0);            // result: failed
secondTest(0);           // result: passed

firstTest(false);        // result: failed
secondTest(false);       // result: passed

firstTest('');           // result: failed
secondTest('');          // result: passed

firstTest(null);         // result: failed
secondTest(null);        // result: failed

firstTest(undefined);    // result: failed
secondTest(undefined);   // result: failed

In my situation, I just needed to check if the value is null and undefined and I did not want to filter 0 or false or '' values. so I used the second test, but you may need to filter them too which may cause you to use first test.

URL to load resources from the classpath in Java

An extension to Dilums's answer:

Without changing code, you likely need pursue custom implementations of URL related interfaces as Dilum recommends. To simplify things for you, I can recommend looking at the source for Spring Framework's Resources. While the code is not in the form of a stream handler, it has been designed to do exactly what you are looking to do and is under the ASL 2.0 license, making it friendly enough for re-use in your code with due credit.

How to import .py file from another directory?

Python3:

import importlib.machinery

loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')

handle.mainFunction(parameter)

This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).

There's also the more normal way of importing a python module in Python3,

import importlib
module = importlib.load_module('folder.filename')
module.function()

Kudos to Sebastian for spplying a similar answer for Python2:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

SELECT session_id as SPID, command, a.text AS Query, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time 
FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a 
WHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE')

How to add System.Windows.Interactivity to project?

The official package for behaviors is Microsoft.Xaml.Behaviors.Wpf.

It used to be in the Blend SDK (deprecated).
See Jan's answer for more details if you need to migrate.

How to use jQuery to call an ASP.NET web service?

I don't know about that specific SharePoint web service, but you can decorate a page method or a web service with <WebMethod()> (in VB.NET) to ensure that it serializes to JSON. You can probably just wrap the method that webservice.asmx uses internally, in your own web service.

Dave Ward has a nice walkthrough on this.

jQuery changing font family and font size

In some browsers, fonts are set explicit for textareas and inputs, so they don’t inherit the fonts from higher elements. So, I think you need to apply the font styles for each textarea and input in the document as well (not just the body).

One idea might be to add clases to the body, then use CSS to style the document accordingly.

How to test Spring Data repositories?

I solved this by using this way -

    @RunWith(SpringRunner.class)
    @EnableJpaRepositories(basePackages={"com.path.repositories"})
    @EntityScan(basePackages={"com.model"})
    @TestPropertySource("classpath:application.properties")
    @ContextConfiguration(classes = {ApiTestConfig.class,SaveActionsServiceImpl.class})
    public class SaveCriticalProcedureTest {

        @Autowired
        private SaveActionsService saveActionsService;
        .......
        .......
}

Access Control Request Headers, is added to header in AJAX request with jQuery

What you saw in Firefox was not the actual request; note that the HTTP method is OPTIONS, not POST. It was actually the 'pre-flight' request that the browser makes to determine whether a cross-domain AJAX request should be allowed:

http://www.w3.org/TR/cors/

The Access-Control-Request-Headers header in the pre-flight request includes the list of headers in the actual request. The server is then expected to report back whether these headers are supported in this context or not, before the browser submits the actual request.

Why am I getting string does not name a type Error?

Just use the std:: qualifier in front of string in your header files.

In fact, you should use it for istream and ostream also - and then you will need #include <iostream> at the top of your header file to make it more self contained.

How to create dispatch queue in Swift 3

Update for swift 5

Serial Queue

let serialQueue = DispatchQueue.init(label: "serialQueue")
serialQueue.async {
    // code to execute
}

Concurrent Queue

let concurrentQueue = DispatchQueue.init(label: "concurrentQueue", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil)

concurrentQueue.async {
// code to execute
}

From Apple documentation:

Parameters

label

A string label to attach to the queue to uniquely identify it in debugging tools such as Instruments, sample, stackshots, and crash reports. Because applications, libraries, and frameworks can all create their own dispatch queues, a reverse-DNS naming style (com.example.myqueue) is recommended. This parameter is optional and can be NULL.

qos

The quality-of-service level to associate with the queue. This value determines the priority at which the system schedules tasks for execution. For a list of possible values, see DispatchQoS.QoSClass.

attributes

The attributes to associate with the queue. Include the concurrent attribute to create a dispatch queue that executes tasks concurrently. If you omit that attribute, the dispatch queue executes tasks serially.

autoreleaseFrequency

The frequency with which to autorelease objects created by the blocks that the queue schedules. For a list of possible values, see DispatchQueue.AutoreleaseFrequency.

target

The target queue on which to execute blocks. Specify DISPATCH_TARGET_QUEUE_DEFAULT if you want the system to provide a queue that is appropriate for the current object.

What is cURL in PHP?

cURL is a way you can hit a URL from your code to get a HTML response from it. It's used for command line cURL from the PHP language.

<?php
// Step 1
$cSession = curl_init(); 
// Step 2
curl_setopt($cSession,CURLOPT_URL,"http://www.google.com/search?q=curl");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false); 
// Step 3
$result=curl_exec($cSession);
// Step 4
curl_close($cSession);
// Step 5
echo $result;
?> 

Step 1: Initialize a curl session using curl_init().

Step 2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to. Append a search term curl using parameter q=. Set option for CURLOPT_RETURNTRANSFER. True will tell curl to return the string instead of print it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.

Step 3: Execute the curl session using curl_exec().

Step 4: Close the curl session we have created.

Step 5: Output the return string.

public function curlCall($apiurl, $auth, $rflag)
{
    $ch = curl_init($apiurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    if($auth == 'auth') { 
        curl_setopt($ch, CURLOPT_USERPWD, "passw:passw");
    } else {
        curl_setopt($ch, CURLOPT_USERPWD, "ss:ss1");
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $dt = curl_exec($ch);        
    curl_close($ch);
    if($rflag != 1) {
        $dt = json_decode($dt,true);        
    }
    return $dt;
}

This is also used for authentication. We can also set the username and password for authentication.

For more functionality, see the user manual or the following tutorial:

http://php.net/manual/en/ref.curl.php
http://www.startutorial.com/articles/view/php-curl

Postgres "psql not recognized as an internal or external command"

Always better to install a previous version or in the installation make sure you specify the '/data' in a separate directory folder "C:\data"

Change type of varchar field to integer: "cannot be cast automatically to type integer"

I got the same problem. Than I realized I had a default string value for the column I was trying to alter. Removing the default value made the error go away :)

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

How to pause javascript code execution for 2 seconds

There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:

for (var i = 1; i <= 5; i++) {
    var tick = function(i) {
        return function() {
            console.log(i);
        }
    };
    setTimeout(tick(i), 500 * i);
}

Demo here: http://jsfiddle.net/hW7Ch/

how to add script inside a php code?

You mean JavaScript? Just output it like anything else in the page:

<script type="text/javascript">
  <?php echo "alert('message');"; ?>
</script>

If want PHP to generate a custom message for the alert dialog, then basically you want to write your JavaScript as usual in the HTML, but insert PHP echo statements in the middle of your JavaScript where you want the messages, like:

<script type="text/javascript">
  alert('<?php echo $custom_message; ?>');
</script>

Or you could even do something like this:

<script type="text/javascript">
  var alertMsg = '<?php echo $custom_message; ?>';
  alert(alertMsg);
</script>

Basically, think about where in your JavaScript you want PHP to generate dynamic output and just put an echo statement there.

Comparing user-inputted characters in C

For a start, your answer variable should be of type char, not char*.

As for the if statement:

if (answer == ('Y' || 'y'))

This is first evaluating 'Y' || 'y' which, in Boolean logic (and for ASCII) is true since both of them are "true" (non-zero). In other words, you'd only get the if statement to fire if you'd somehow entered CTRLA (again, for ASCII, and where a true values equates to 1)*a.

You could use the more correct:

if ((answer == 'Y') || (answer == 'y'))

but you really should be using:

if (toupper(answer) == 'Y')

since that's the more portable way to achieve the same end.


*a You may be wondering why I'm putting in all sorts of conditionals for my statements. While the vast majority of C implementations use ASCII and certain known values, it's not necessarily mandated by the ISO standards. I know for a fact that at least one compiler still uses EBCDIC so I don't like making unwarranted assumptions.

How to go from one page to another page using javascript?

Try this:

window.location.href = "http://PlaceYourUrl.com";

how to break the _.each function in underscore.js

Update:

You can actually "break" by throwing an error inside and catching it outside: something like this:

try{
  _([1,2,3]).each(function(v){
    if (v==2) throw new Error('break');
  });
}catch(e){
  if(e.message === 'break'){
    //break successful
  }
}

This obviously has some implications regarding any other exceptions that your code trigger in the loop, so use with caution!

How to sort strings in JavaScript

Use sort() straight forward without any - or <

_x000D_
_x000D_
const areas = ['hill', 'beach', 'desert', 'mountain']
console.log(areas.sort())

// To print in descending way
console.log(areas.sort().reverse())
_x000D_
_x000D_
_x000D_

Improve INSERT-per-second performance of SQLite

Bulk imports seems to perform best if you can chunk your INSERT/UPDATE statements. A value of 10,000 or so has worked well for me on a table with only a few rows, YMMV...

How to apply border radius in IE8 and below IE8 browsers?

As the answer said above, CSS PIE makes things like border-radius and box-shadow work in IE6-IE8: http://css3pie.com/

That said I have still found things to be somewhat flaky when using PIE and now just accept that people using older browsers aren't going to see rounded corners and dropshadows.

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

var str = "How are you doing today?";

var res = str.split(" ");

Here the variable "res" is kind of array.

You can also take this explicity by declaring it as

var res[]= str.split(" ");

Now you can access the individual words of the array. Suppose you want to access the third element of the array you can use it by indexing array elements.

var FirstElement= res[0];

Now the variable FirstElement contains the value 'How'

Accessing session from TWIG template

A simple trick is to define the $_SESSION array as a global variable. For that, edit the core.php file in the extension folder by adding this function :

public function getGlobals() {
    return array(
        'session'   => $_SESSION,
    ) ;
}

Then, you'll be able to acces any session variable as :

{{ session.username }}

if you want to access to

$_SESSION['username']

JavaScript OOP in NodeJS: how?

In the Javascript community, lots of people argue that OOP should not be used because the prototype model does not allow to do a strict and robust OOP natively. However, I don't think that OOP is a matter of langage but rather a matter of architecture.

If you want to use a real strong OOP in Javascript/Node, you can have a look at the full-stack open source framework Danf. It provides all needed features for a strong OOP code (classes, interfaces, inheritance, dependency-injection, ...). It also allows you to use the same classes on both the server (node) and client (browser) sides. Moreover, you can code your own danf modules and share them with anybody thanks to Npm.

using scp in terminal

You can download in the current directory with a . :

cd # by default, goes to $HOME
scp me@host:/path/to/file .

or in you HOME directly with :

scp me@host:/path/to/file ~

Can Powershell Run Commands in Parallel?

http://gallery.technet.microsoft.com/scriptcenter/Invoke-Async-Allows-you-to-83b0c9f0

i created an invoke-async which allows you do run multiple script blocks/cmdlets/functions at the same time. this is great for small jobs (subnet scan or wmi query against 100's of machines) because the overhead for creating a runspace vs the startup time of start-job is pretty drastic. It can be used like so.

with scriptblock,

$sb = [scriptblock] {param($system) gwmi win32_operatingsystem -ComputerName $system | select csname,caption} 

$servers = Get-Content servers.txt 

$rtn = Invoke-Async -Set $server -SetParam system  -ScriptBlock $sb

just cmdlet/function

$servers = Get-Content servers.txt 

$rtn = Invoke-Async -Set $servers -SetParam computername -Params @{count=1} -Cmdlet Test-Connection -ThreadCount 50

Removing first x characters from string?

Use del.

Example:

>>> text = 'lipsum'
>>> l = list(text)
>>> del l[3:]
>>> ''.join(l)
'sum'

How to fill in proxy information in cntlm config file?

The solution takes two steps!

First, complete the user, domain, and proxy fields in cntlm.ini. The username and domain should probably be whatever you use to log in to Windows at your office, eg.

Username            employee1730
Domain              corporate
Proxy               proxy.infosys.corp:8080

Then test cntlm with a command such as

cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk

It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini, eg:

Auth            NTLM
PassNT          A2A7104B1CE00000000000000007E1E1
PassLM          C66000000000000000000000008060C8

Finally, set the http_proxy environment variable in Windows (assuming you didn't change with the Listen field which by default is set to 3128) to the following

http://localhost:3128

Give column name when read csv file pandas

we can do it with a single line of code.

 user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)

Execute CMD command from code

Are you asking how to bring up a command windows? If so, you can use the Process object ...

Process.Start("cmd");

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

Truncate Two decimal places without rounding

Would ((long)(3.4679 * 100)) / 100.0 give what you want?

Right way to reverse a pandas DataFrame?

None of the existing answers resets the index after reversing the dataframe.

For this, do the following:

 data[::-1].reset_index()

Here's a utility function that also removes the old index column, as per @Tim's comment:

def reset_my_index(df):
  res = df[::-1].reset_index(drop=True)
  return(res)

Simply pass your dataframe into the function

Gitignore not working

In my case it was a blank space at the beginning of the file which showed up clearly when I opened the file in Notepad, wasn't obvious in Visual Studio Code.

Change Active Menu Item on Page Scroll?

It's done by binding to the scroll event of the container (usually window).

Quick example:

// Cache selectors
var topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";
   // Set/remove active class
   menuItems
     .parent().removeClass("active")
     .end().filter("[href='#"+id+"']").parent().addClass("active");
});?

See the above in action at jsFiddle including scroll animation.

Setting the value of checkbox to true or false with jQuery

You can do (jQuery 1.6 onwards):

$('#idCheckbox').prop('checked', true);
$('#idCheckbox').prop('checked', false);

to remove you can also use:

$('#idCheckbox').removeProp('checked');

with jQuery < 1.6 you must do

$('#idCheckbox').attr('checked', true);
$('#idCheckbox').removeAttr('checked');

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

So, @Vivek has got the solution to the problem through a dialogue in the Comments rather than through an actual answer.

"The file is being created by user oracle just noticed this in our development database. i'm getting this error because, the directory where i try to create the file doesn't have write access for others and user oracle comes under others category. "

Who says SO is a Q&A site not a forum? Er, me, amongst others. Anyway, in the absence of an accepted answer to this question I proffer a link to an answer of mine on the topic of UTL_FILE.FOPEN(). Find it here.

P.S. I'm marking this answer Community Wiki, because it's not a proper answer to this question, just a redirect to somewhere else.

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

How to extract the decimal part from a floating point number in C?

Here is another way:

#include <stdlib.h>
int main()
{
    char* inStr = "123.4567";         //the number we want to convert
    char* endptr;                     //unused char ptr for strtod

    char* loc = strchr(inStr, '.');
    long mantissa = strtod(loc+1, endptr);
    long whole = strtod(inStr, endptr);

    printf("whole: %d \n", whole);     //whole number portion
    printf("mantissa: %d", mantissa);  //decimal portion

}

http://codepad.org/jyHoBALU

Output:

whole: 123 
mantissa: 4567

How to make python Requests work via socks proxy

The modern way:

pip install -U requests[socks]

then

import requests

resp = requests.get('http://go.to', 
                    proxies=dict(http='socks5://user:pass@host:port',
                                 https='socks5://user:pass@host:port'))

In which case do you use the JPA @JoinTable annotation?

@ManyToMany associations

Most often, you will need to use @JoinTable annotation to specify the mapping of a many-to-many table relationship:

  • the name of the link table and
  • the two Foreign Key columns

So, assuming you have the following database tables:

Many-to-many table relationship

In the Post entity, you would map this relationship, like this:

@ManyToMany(cascade = {
    CascadeType.PERSIST,
    CascadeType.MERGE
})
@JoinTable(
    name = "post_tag",
    joinColumns = @JoinColumn(name = "post_id"),
    inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private List<Tag> tags = new ArrayList<>();

The @JoinTable annotation is used to specify the table name via the name attribute, as well as the Foreign Key column that references the post table (e.g., joinColumns) and the Foreign Key column in the post_tag link table that references the Tag entity via the inverseJoinColumns attribute.

Notice that the cascade attribute of the @ManyToMany annotation is set to PERSIST and MERGE only because cascading REMOVE is a bad idea since we the DELETE statement will be issued for the other parent record, tag in our case, not to the post_tag record.

Unidirectional @OneToMany associations

The unidirectional @OneToMany associations, that lack a @JoinColumn mapping, behave like many-to-many table relationships, rather than one-to-many.

So, assuming you have the following entity mappings:

@Entity(name = "Post")
@Table(name = "post")
public class Post {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String title;
 
    @OneToMany(
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();
 
    //Constructors, getters and setters removed for brevity
}
 
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String review;
 
    //Constructors, getters and setters removed for brevity
}

Hibernate will assume the following database schema for the above entity mapping:

Unidirectional @OneToMany JPA association database tables

As already explained, the unidirectional @OneToMany JPA mapping behaves like a many-to-many association.

To customize the link table, you can also use the @JoinTable annotation:

@OneToMany(
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
@JoinTable(
    name = "post_comment_ref",
    joinColumns = @JoinColumn(name = "post_id"),
    inverseJoinColumns = @JoinColumn(name = "post_comment_id")
)
private List<PostComment> comments = new ArrayList<>();

And now, the link table is going to be called post_comment_ref and the Foreign Key columns will be post_id, for the post table, and post_comment_id, for the post_comment table.

Unidirectional @OneToMany associations are not efficient, so you are better off using bidirectional @OneToMany associations or just the @ManyToOne side.

Make a dictionary with duplicate keys in Python

I just posted an answer to a question that was subequently closed as a duplicate of this one (for good reasons I think), but I'm surprised to see that my proposed solution is not included in any of the answers here.

Rather than using a defaultdict or messing around with membership tests or manual exception handling, you can easily append values onto lists within a dictionary using the setdefault method:

results = {}                              # use a normal dictionary for our output
for k, v in some_data:                    # the keys may be duplicates
    results.setdefault(k, []).append(v)   # magic happens here!

This is a lot like using a defaultdict, but you don't need a special data type. When you call setdefault, it checks to see if the first argument (the key) is already in the dictionary. If doesn't find anything, it assigns the second argument (the default value, an empty list in this case) as a new value for the key. If the key does exist, nothing special is done (the default goes unused). In either case though, the value (whether old or new) gets returned, so we can unconditionally call append on it, knowing it should always be a list.

Meaning of $? (dollar question mark) in shell scripts

It has the last status code (exit value) of a command.

Screenshot sizes for publishing android app on Google Play

It has to be any one of the given sizes and a minimum of 2 but up to 8 screenshots are accepted in Google Playstore.

What is a web service endpoint?

Updated answer, from Peter in comments :

This is de "old terminology", use directally the WSDL2 "endepoint" definition (WSDL2 translated "port" to "endpoint").


Maybe you find an answer in this document : http://www.w3.org/TR/wsdl.html

A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:

  • Types– a container for data type definitions using some type system (such as XSD).
  • Message– an abstract, typed definition of the data being communicated.
  • Operation– an abstract description of an action supported by the service.
  • Port Type–an abstract set of operations supported by one or more endpoints.
  • Binding– a concrete protocol and data format specification for a particular port type.
  • Port– a single endpoint defined as a combination of a binding and a network address.
  • Service– a collection of related endpoints.

http://www.ehow.com/info_12212371_definition-service-endpoint.html

The endpoint is a connection point where HTML files or active server pages are exposed. Endpoints provide information needed to address a Web service endpoint. The endpoint provides a reference or specification that is used to define a group or family of message addressing properties and give end-to-end message characteristics, such as references for the source and destination of endpoints, and the identity of messages to allow for uniform addressing of "independent" messages. The endpoint can be a PC, PDA, or point-of-sale terminal.

Get a file name from a path

A slow but straight forward regex solution:

    std::string file = std::regex_replace(path, std::regex("(.*\\/)|(\\..*)"), "");

How do I update Node.js?

All you need to version update of Node.js:

$ brew install node

If you don't have Homebrew; please go http://brew.sh/.

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

I am Using this

String timeStamp = new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp);

How to filter object array based on attributes?

I prefer the Underscore framework. It suggests many useful operations with objects. Your task:

var newArray = homes.filter(
    price <= 1000 & 
    sqft >= 500 &
    num_of_beds >=2 & 
    num_of_baths >= 2.5);

can be overwriten like:

var newArray = _.filter (homes, function(home) {
    return home.price<=1000 && sqft>=500 && num_of_beds>=2 && num_of_baths>=2.5;
});

Hope it will be useful for you!

Pan & Zoom Image

One addition to the superb solution provided by @Wieslaw Šoltés answer above

The existing code resets the image position using right click, but I am more accustomed to doing that with a double click. Just replace the existing child_MouseLeftButtonDown handler:

private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (child != null)
        {
            var tt = GetTranslateTransform(child);
            start = e.GetPosition(this);
            origin = new Point(tt.X, tt.Y);
            this.Cursor = Cursors.Hand;
            child.CaptureMouse();
        }
    }

With this:

private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 1))
        {
            if (child != null)
            {
                var tt = GetTranslateTransform(child);
                start = e.GetPosition(this);
                origin = new Point(tt.X, tt.Y);
                this.Cursor = Cursors.Hand;
                child.CaptureMouse();
            }
        }

        if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 2))
        {
            this.Reset();
        }
    }

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

It's because you're calling doGet() without actually implementing doGet(). It's the default implementation of doGet() that throws the error saying the method is not supported.

Firebase Permission Denied

Go to database, next to title there are 2 options:

Cloud Firestore, Realtime database

Select Realtime database and go to rules

Change rules to true.

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

Checking session if empty or not

If It is simple Session you can apply NULL Check directly Session["emp_num"] != null

But if it's a session of a list Item then You need to apply any one of the following option

Option 1:

if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
 {
 //Your Logic here
 }

Option 2:

List<int> val= Session["emp_num"] as List<int>;  //Get the value from Session.

if (val.FirstOrDefault() != null)
 {
 //Your Logic here
 }

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

Why doesn't file_get_contents work?

Check file_get_contents PHP Manual return value. If the value is FALSE then it could not read the file. If the value is NULL then the function itself is disabled.

To learn more what might gone wrong with the file_get_contents operation you must enable error reporting and the display of errors to actually read them.

# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);

You can get more details about the why the call is failing by checking the INI values on your server. One value the directly effects the file_get_contents function is allow_url_fopen. You can do this by running the following code. You should note, that if it reports that fopen is not allowed, then you'll have to ask your provider to change this setting on your server in order for any code that require this function to work with URLs.

<html>
    <head>        
        <title>Test File</title>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
        </script>
    </head>
    <body>
<?php

# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);

$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';

$jsonData = file_get_contents($url);

print '<p>', var_dump($jsonData), '</p>';

# Output information about allow_url_fopen:
if (ini_get('allow_url_fopen') == 1) {
    echo '<p style="color: #0A0;">fopen is allowed on this host.</p>';
} else {
    echo '<p style="color: #A00;">fopen is not allowed on this host.</p>';
}


# Decide what to do based on return value:
if ($jsonData === FALSE) {
    echo "Failed to open the URL ", htmlspecialchars($url);
} elseif ($jsonData === NULL) {
    echo "Function is disabled.";
} else {
   echo $jsonData;
}

?>
    </body>
</html>

If all of this fails, it might be due to the use of short open tags, <?. The example code in this answer has been therefore changed to make use of <?php to work correctly as this is guaranteed to work on in all version of PHP, no matter what configuration options are set. To do so for your own script, just replace <? or <?php.

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I had the same error for quite a while, and here what fixed it for me.

I simply declared in service that i use what follows:

Description= Your node service description
After=network.target

[Service]
Type=forking
PIDFile=/tmp/node_pid_name.pid
Restart=on-failure
KillSignal=SIGQUIT
WorkingDirectory=/path/to/node/app/root/directory
ExecStart=/path/to/node /path/to/server.js

[Install]
WantedBy=multi-user.target

What should catch your attention here is "After=network.target". I spent days and days looking for fixes on nginx side, while the problem was just that. To be sure, stop running the node service you have, launch the ExecStart command directly and try to reproduce the bug. If it doesn't pop, it just means that your service has a problem. At least this is how i found my answer.

For everybody else, good luck!

Counting the number of occurences of characters in a string

I don't want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.

Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don't use the same string as your input. That's confusing.

Remember, making things simple counts. Life for developers is hard enough looking at complex code.

Have fun!

Tommy "I should be a Teacher" Kwee

Can I use a binary literal in C or C++?

You can also use inline assembly like this:

int i;

__asm {
    mov eax, 00000000000000000000000000000000b
    mov i,   eax
}

std::cout << i;

Okay, it might be somewhat overkill, but it works.

What is the meaning of {...this.props} in Reactjs

It is ES-6 feature. It means you extract all the properties of props in div.{... }

operator is used to extract properties of an object.

Telnet is not recognized as internal or external command

You can try using Putty (freeware). It is mainly known as a SSH client, but you can use for Telnet login as well

How to set scope property with ng-init?

I had some trouble with $scope.$watch but after a lot of testing I found out that my data-ng-model="User.UserName" was badly named and after I changed it to data-ng-model="UserName" everything worked fine. I expect it to be the . in the name causing the issue.

Have a variable in images path in Sass?

Adding something to the above correct answers. I am using netbeans IDE and it shows error while using url(#{$assetPath}/site/background.jpg) this method. It was just netbeans error and no error in sass compiling. But this error break code formatting in netbeans and code become ugly. But when I use it inside quotes like below, it show wonder!

url("#{$assetPath}/site/background.jpg")

Set textbox to readonly and background color to grey in jquery

Why don't you place the account number in a div. Style it as you please and then have a hidden input in the form that also contains the account number. Then when the form gets submitted, the value should come through and not be null.

AngularJS : ng-click not working

Have a look at this plunker

HTML:

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="[email protected]" data-semver="1.3.0-beta.16" src="https://code.angularjs.org/1.3.0-beta.16/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="FollowsController">
    <div class="row" ng:repeat="follower in myform.all_followers">
      <ons-col class="views-row" size="50" ng-repeat="data in follower">
        <img ng-src="http://dealsscanner.com/obaidtnc/plugmug/uploads/{{data.token}}/thumbnail/{{data.Path}}" alt="{{data.fname}}" ng-click="showDetail2(data.token)" />
        <h3 class="title" ng-click="showDetail2('ss')">{{data.fname}}</h3>
      </ons-col>
    </div>
  </body>

</html>

Javascript:

var app = angular.module('app', []);
//Follows Controller
app.controller('FollowsController', function($scope, $http) {
    var ukey = window.localStorage.ukey;
    //alert(dataFromServer);
    $scope.showDetail = function(index) {
        profileusertoken =  index;
        $scope.ons.navigator.pushPage('profile.html'); 
    }

    function showDetail2(index) {
        alert("here");
    }

    $scope.showDetail2 = showDetail2;
    $scope.myform ={};
    $scope.myform.reports ="";
    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    var dataObject = "usertoken="+ukey;
    //var responsePromise = $http.post("follows/", dataObject,{});
    //responsePromise.success(function(dataFromServer, status,    headers, config) {

    $scope.myform.all_followers = [[{fname: "blah"}, {fname: "blah"}, {fname: "blah"}, {fname: "blah"}]];
});

Run Jquery function on window events: load, resize, and scroll?

just call your function inside the events.

load:

$(document).ready(function(){  // or  $(window).load(function(){
    topInViewport($(mydivname));
});

resize:

$(window).resize(function () {
    topInViewport($(mydivname));
});

scroll:

$(window).scroll(function () {
    topInViewport($(mydivname));
});

or bind all event in one function

$(window).on("load scroll resize",function(e){

CocoaPods Errors on Project Build

If you have a watchOS target: I found that suddenly, having pods in the watch extension but not in the watch target itself broke things with this same error. The solution was to add the pods to the watch target also.

How do I check out a remote Git branch?

Simply run git checkout with the name of the remote branch. Git will automatically create a local branch that tracks the remote one:

git fetch
git checkout test

However, if that branch name is found in more than one remote, this won't work as Git doesn't know which to use. In that case you can use either:

git checkout --track origin/test

or

git checkout -b test origin/test

In 2.19, Git learned the checkout.defaultRemote configuration, which specifies a remote to default to when resolving such an ambiguity.

add string to String array

Since Java arrays hold a fixed number of values, you need to create a new array with a length of 5 in this case. A better solution would be to use an ArrayList and simply add strings to the array.

Example:

ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test3");
scripts.add("test4");
scripts.add("test5");

// Then later you can add more Strings to the ArrayList
scripts.add("test1");
scripts.add("test2");

NOW() function in PHP

With PHP version >= 5.4 DateTime can do this:-

echo (new \DateTime())->format('Y-m-d H:i:s');

See it working.

.NET Events - What are object sender & EventArgs e?

Manually cast the sender to the type of your custom control, and then use it to delete or disable etc. Eg, something like this:

private void myCustomControl_Click(object sender, EventArgs e)
{
  ((MyCustomControl)sender).DoWhatever();
}

The 'sender' is just the object that was actioned (eg clicked).

The event args is subclassed for more complex controls, eg a treeview, so that you can know more details about the event, eg exactly where they clicked.

Easiest way to convert month name to month number in JS ? (Jan = 01)

One more way to do the same

month1 = month1.toLowerCase();
var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
month1 = months.indexOf(month1);

Deleting rows with MySQL LEFT JOIN

Try this:

DELETE `deadline`
FROM `deadline`
INNER JOIN `job` ON `deadline`.`job_id` = `job`.`id`
WHERE `job`.`id` = 123

Is there a limit to the length of a GET request?

As Requested By User Erickson, I Post My comment As Answer:

I have done some more testing with IE8, IE9, FF14, Opera11, Chrome20 and Tomcat 6.0.32 (fresh installation), Jersey 1.13 on the server side. I used the jQuery function $.getJson and JSONP. Results: All Browsers allowed up to around 5400 chars. FF and IE9 did up to around 6200 chars. Everything above returned "400 Bad request". I did not further investigate what was responsible for the 400. I was fine with the maximum I found, because I needed around 2000 chars in my case.

Javascript - How to show escape characters in a string?

JavaScript uses the \ (backslash) as an escape characters for:

  • \' single quote
  • \" double quote
  • \ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.)
  • \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)

Note that the \v and \0 escapes are not allowed in JSON strings.

android TextView: setting the background color dynamically doesn't work

Here are the steps to do it correctly:

  1. First of all, declare an instance of TextView in your MainActivity.java as follows:

    TextView mTextView;
    
  2. Set some text DYNAMICALLY(if you want) as follows:

    mTextView.setText("some_text");
    
  3. Now, to set the background color, you need to define your own color in the res->values->colors.xml file as follows:

    <resources>
        <color name="my_color">#000000</color>
    </resources>
    
  4. You can now use "my_color" color in your java file to set the background dynamically as follows:

    mTextView.setBackgroundResource(R.color.my_color);
    

Batch script: how to check for admin rights

two more ways - fast and backward compatible .

fltmc >nul 2>&1 && (
  echo has admin permissions
) || (
  echo has NOT admin permissions
)

fltmc command is available on every windows system since XP so this should be pretty portable.


One more really fast solution tested on XP,8.1,7 - there's one specific variable =:: which is presented only if the console session has no admin privileges.As it is not so easy to create variable that contains = in it's name this is comparatively reliable way to check for admin permission (it does not call external executables so it performs well)

setlocal enableDelayedExpansion
set "dv==::"
if defined !dv! ( 
   echo has NOT admin permissions
) else (
   echo has admin permissions
)

If you want use this directly through command line ,but not from a batch file you can use:

set ^"|find "::"||echo has admin permissions

"cannot resolve symbol R" in Android Studio

I'm working on a multi-module projects. And this happened to me when I moved all of the ui code to a new module.

Here is how I solve the problem: I find out that when I create the new ui module, in the /res/values, it creates a new strings.xml with nothing useful in it. I delete that strings.xml file, rebuild the project, and it works.

Change values of select box of "show 10 entries" of jquery datatable

if you click some button,then change the datatables the displaylenght,you can try this :

 $('.something').click( function () {
var oSettings = oTable.fnSettings();
oSettings._iDisplayLength = 50;
oTable.fnDraw();
});

oTable = $('#example').dataTable();

Compare two files report difference in python

The difflib library is useful for this, and comes in the standard library. I like the unified diff format.

http://docs.python.org/2/library/difflib.html#difflib.unified_diff

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
        )
        for line in diff:
            sys.stdout.write(line)

Outputs:

--- hosts0
+++ hosts1
@@ -1,5 +1,4 @@
 one
 two
-dogs
 three

And here is a dodgy version that ignores certain lines. There might be edge cases that don't work, and there are surely better ways to do this, but maybe it will be good enough for your purposes.

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
            n=0,
        )
        for line in diff:
            for prefix in ('---', '+++', '@@'):
                if line.startswith(prefix):
                    break
            else:
                sys.stdout.write(line[1:])

Using margin:auto to vertically-align a div

_x000D_
_x000D_
.black {_x000D_
    display:flex;_x000D_
    flex-direction: column;_x000D_
    height: 200px;_x000D_
    background:grey_x000D_
}_x000D_
.message {_x000D_
    background:yellow;_x000D_
    width:200px;_x000D_
    padding:10px;_x000D_
    margin: auto auto;_x000D_
}
_x000D_
<div class="black">_x000D_
    <div class="message">_x000D_
        This is a popup message._x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check Network port access and display useful message?

Great answer by mshutov & Salselvaprabu. I needed something a little bit more robust, and that checked all IPAddresses that was provided instead of checking only the first one.

I also wanted to replicate some of the parameter names and functionality than the Test-Connection function.

This new function allows you to set a Count for the number of retries, and the Delay between each try. Enjoy!

function Test-Port {

    [CmdletBinding()]
    Param (
        [string] $ComputerName,
        [int] $Port,
        [int] $Delay = 1,
        [int] $Count = 3
    )

    function Test-TcpClient ($IPAddress, $Port) {

        $TcpClient = New-Object Net.Sockets.TcpClient
        Try { $TcpClient.Connect($IPAddress, $Port) } Catch {}

        If ($TcpClient.Connected) { $TcpClient.Close(); Return $True }
        Return $False

    }

    function Invoke-Test ($ComputerName, $Port) {

        Try   { [array]$IPAddress = [System.Net.Dns]::GetHostAddresses($ComputerName) | Select-Object -Expand IPAddressToString } 
        Catch { Return $False }

        [array]$Results = $IPAddress | % { Test-TcpClient -IPAddress $_ -Port $Port }
        If ($Results -contains $True) { Return $True } Else { Return $False }

    }

    for ($i = 1; ((Invoke-Test -ComputerName $ComputerName -Port $Port) -ne $True); $i++)
    {
        if ($i -ge $Count) {
            Write-Warning "Timed out while waiting for port $Port to be open on $ComputerName!"
            Return $false
        }

        Write-Warning "Port $Port not open, retrying..."
        Sleep $Delay
    }

    Return $true

}

How to check whether a int is not null or empty?

if your int variable is declared as a class level variable (instance variable) it would be defaulted to 0. But that does not indicate if the value sent from the client was 0 or a null. may be you could have a setter method which could be called to initialize/set the value sent by the client. then you can define your indicator value , may be a some negative value to indicate the null..

PHP - check if variable is undefined

To check is variable is set you need to use isset function.

$lorem = 'potato';

if(isset($lorem)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

if(isset($ipsum)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

this code will print:

isset true
isset false

read more in https://php.net/manual/en/function.isset.php

The program can't start because MSVCR110.dll is missing from your computer

Weird, just had simmilar issue, went here http://www.microsoft.com/en-us/download/confirmation.aspx?id=30679 downloaded and installed vcredist_x86 (i'm using 32bit apache) and it works like a charm.

Match two strings in one line with grep

git grep

Here is the syntax using git grep with multiple patterns:

git grep --all-match --no-index -l -e string1 -e string2 -e string3 file

You may also combine patterns with Boolean expressions such as --and, --or and --not.

Check man git-grep for help.


--all-match When giving multiple pattern expressions, this flag is specified to limit the match to files that have lines to match all of them.

--no-index Search files in the current directory that is not managed by Git.

-l/--files-with-matches/--name-only Show only the names of files.

-e The next parameter is the pattern. Default is to use basic regexp.

Other params to consider:

--threads Number of grep worker threads to use.

-q/--quiet/--silent Do not output matched lines; exit with status 0 when there is a match.

To change the pattern type, you may also use -G/--basic-regexp (default), -F/--fixed-strings, -E/--extended-regexp, -P/--perl-regexp, -f file, and other.

Related:

For OR operation, see:

How do I change the background color with JavaScript?

You don't need AJAX for this, just some plain java script setting the background-color property of the body element, like this:

document.body.style.backgroundColor = "#AA0000";

If you want to do it as if it was initiated by the server, you would have to poll the server and then change the color accordingly.

Make Adobe fonts work with CSS3 @font-face in IE9

I tried the ttfpatch tool and it didn't work form me. Internet Exploder 9 and 10 still complained.

I found this nice Git gist and it solved my issues. https://gist.github.com/stefanmaric/a5043c0998d9fc35483d

Just copy and paste the code in your css.

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"

why I can't get value of label with jquery and javascript?

You need text() or html() for label not val() The function should not be called for label instead it is used to get values of input like text or checkbox etc.

Change

value = $("#telefon").val(); 

To

value = $("#telefon").text(); 

moment.js 24h format

moment("01:15:00 PM", "h:mm:ss A").format("HH:mm:ss")
**o/p: 13:15:00 **

it will give convert 24 hrs format to 12 hrs format.

How do I undo a checkout in git?

To undo git checkout do git checkout -, similarly to cd and cd - in shell.

CSS selector based on element text?

It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:

<li><span class="foo">some text</span></li>
<li>some other text</li>

Then refer to it the usual way:

li > span.foo {...}

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

(The following is a very artificial example cooked up to illustrate.) One major use of packed structs is where you have a stream of data (say 256 bytes) to which you wish to supply meaning. If I take a smaller example, suppose I have a program running on my Arduino which sends via serial a packet of 16 bytes which have the following meaning:

0: message type (1 byte)
1: target address, MSB
2: target address, LSB
3: data (chars)
...
F: checksum (1 byte)

Then I can declare something like

typedef struct {
  uint8_t msgType;
  uint16_t targetAddr; // may have to bswap
  uint8_t data[12];
  uint8_t checksum;
} __attribute__((packed)) myStruct;

and then I can refer to the targetAddr bytes via aStruct.targetAddr rather than fiddling with pointer arithmetic.

Now with alignment stuff happening, taking a void* pointer in memory to the received data and casting it to a myStruct* will not work unless the compiler treats the struct as packed (that is, it stores data in the order specified and uses exactly 16 bytes for this example). There are performance penalties for unaligned reads, so using packed structs for data your program is actively working with is not necessarily a good idea. But when your program is supplied with a list of bytes, packed structs make it easier to write programs which access the contents.

Otherwise you end up using C++ and writing a class with accessor methods and stuff that does pointer arithmetic behind the scenes. In short, packed structs are for dealing efficiently with packed data, and packed data may be what your program is given to work with. For the most part, you code should read values out of the structure, work with them, and write them back when done. All else should be done outside the packed structure. Part of the problem is the low level stuff that C tries to hide from the programmer, and the hoop jumping that is needed if such things really do matter to the programmer. (You almost need a different 'data layout' construct in the language so that you can say 'this thing is 48 bytes long, foo refers to the data 13 bytes in, and should be interpreted thus'; and a separate structured data construct, where you say 'I want a structure containing two ints, called alice and bob, and a float called carol, and I don't care how you implement it' -- in C both these use cases are shoehorned into the struct construct.)

Formatting floats in a numpy array

In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:

In [1]: float_formatter = "{:.2f}".format

The f here means fixed-point format (not 'scientific'), and the .2 means two decimal places (you can read more about string formatting here).

Let's test it out with a float value:

In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'

To make numpy print all float arrays this way, you can pass the formatter= argument to np.set_printoptions:

In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})

Now numpy will print all float arrays this way:

In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]

Note that this only affects numpy arrays, not scalars:

In [5]: np.pi
Out[5]: 3.141592653589793

It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.

You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.

For example:

In [6]: a = np.array([1E-9])

In [7]: a
Out[7]: array([0.00])

In [8]: a == 0
Out[8]: array([False], dtype=bool)

numpy prints a as if it were equal to 0, but it is not - it still equals 1E-9.

If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round, as others have already pointed out.

How to directly initialize a HashMap (in a literal way)?

If you allow 3rd party libs, you can use Guava's ImmutableMap to achieve literal-like brevity:

Map<String, String> test = ImmutableMap.of("k1", "v1", "k2", "v2");

This works for up to 5 key/value pairs, otherwise you can use its builder:

Map<String, String> test = ImmutableMap.<String, String>builder()
    .put("k1", "v1")
    .put("k2", "v2")
    ...
    .build();


  • note that Guava's ImmutableMap implementation differs from Java's HashMap implementation (most notably it is immutable and does not permit null keys/values)
  • for more info, see Guava's user guide article on its immutable collection types

How to Rotate a UIImage 90 degrees?

Check out the simple and awesome code of Hardy Macia at: cutting-scaling-and-rotating-uiimages

Just call

UIImage *rotatedImage = [originalImage imageRotatedByDegrees:90.0];

Thanks Hardy Macia!

Header:

  • (UIImage *)imageAtRect:(CGRect)rect;
  • (UIImage *)imageByScalingProportionallyToMinimumSize:(CGSize)targetSize;
  • (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
  • (UIImage *)imageByScalingToSize:(CGSize)targetSize;
  • (UIImage *)imageRotatedByRadians:(CGFloat)radians;
  • (UIImage *)imageRotatedByDegrees:(CGFloat)degrees;

Since the link may die, here's the complete code

//
//  UIImage-Extensions.h
//
//  Created by Hardy Macia on 7/1/09.
//  Copyright 2009 Catamount Software. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface UIImage (CS_Extensions)
- (UIImage *)imageAtRect:(CGRect)rect;
- (UIImage *)imageByScalingProportionallyToMinimumSize:(CGSize)targetSize;
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
- (UIImage *)imageByScalingToSize:(CGSize)targetSize;
- (UIImage *)imageRotatedByRadians:(CGFloat)radians;
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees;

@end;

//
//  UIImage-Extensions.m
//
//  Created by Hardy Macia on 7/1/09.
//  Copyright 2009 Catamount Software. All rights reserved.
//

#import "UIImage-Extensions.h"

CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
CGFloat RadiansToDegrees(CGFloat radians) {return radians * 180/M_PI;};

@implementation UIImage (CS_Extensions)

-(UIImage *)imageAtRect:(CGRect)rect
{

   CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
   UIImage* subImage = [UIImage imageWithCGImage: imageRef];
   CGImageRelease(imageRef);

   return subImage;

}

- (UIImage *)imageByScalingProportionallyToMinimumSize:(CGSize)targetSize {

   UIImage *sourceImage = self;
   UIImage *newImage = nil;

   CGSize imageSize = sourceImage.size;
   CGFloat width = imageSize.width;
   CGFloat height = imageSize.height;

   CGFloat targetWidth = targetSize.width;
   CGFloat targetHeight = targetSize.height;

   CGFloat scaleFactor = 0.0;
   CGFloat scaledWidth = targetWidth;
   CGFloat scaledHeight = targetHeight;

   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

   if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

      CGFloat widthFactor = targetWidth / width;
      CGFloat heightFactor = targetHeight / height;

      if (widthFactor > heightFactor) 
         scaleFactor = widthFactor;
      else
         scaleFactor = heightFactor;

      scaledWidth  = width * scaleFactor;
      scaledHeight = height * scaleFactor;

      // center the image

      if (widthFactor > heightFactor) {
         thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
      } else if (widthFactor < heightFactor) {
         thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
      }
   }


   // this is actually the interesting part:

   UIGraphicsBeginImageContext(targetSize);

   CGRect thumbnailRect = CGRectZero;
   thumbnailRect.origin = thumbnailPoint;
   thumbnailRect.size.width  = scaledWidth;
   thumbnailRect.size.height = scaledHeight;

   [sourceImage drawInRect:thumbnailRect];

   newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if(newImage == nil) NSLog(@"could not scale image");


   return newImage ;
}


- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

   UIImage *sourceImage = self;
   UIImage *newImage = nil;

   CGSize imageSize = sourceImage.size;
   CGFloat width = imageSize.width;
   CGFloat height = imageSize.height;

   CGFloat targetWidth = targetSize.width;
   CGFloat targetHeight = targetSize.height;

   CGFloat scaleFactor = 0.0;
   CGFloat scaledWidth = targetWidth;
   CGFloat scaledHeight = targetHeight;

   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

   if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

      CGFloat widthFactor = targetWidth / width;
      CGFloat heightFactor = targetHeight / height;

      if (widthFactor < heightFactor) 
         scaleFactor = widthFactor;
      else
         scaleFactor = heightFactor;

      scaledWidth  = width * scaleFactor;
      scaledHeight = height * scaleFactor;

      // center the image

      if (widthFactor < heightFactor) {
         thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
      } else if (widthFactor > heightFactor) {
         thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
      }
   }


   // this is actually the interesting part:

   UIGraphicsBeginImageContext(targetSize);

   CGRect thumbnailRect = CGRectZero;
   thumbnailRect.origin = thumbnailPoint;
   thumbnailRect.size.width  = scaledWidth;
   thumbnailRect.size.height = scaledHeight;

   [sourceImage drawInRect:thumbnailRect];

   newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if(newImage == nil) NSLog(@"could not scale image");


   return newImage ;
}


- (UIImage *)imageByScalingToSize:(CGSize)targetSize {

   UIImage *sourceImage = self;
   UIImage *newImage = nil;

   //   CGSize imageSize = sourceImage.size;
   //   CGFloat width = imageSize.width;
   //   CGFloat height = imageSize.height;

   CGFloat targetWidth = targetSize.width;
   CGFloat targetHeight = targetSize.height;

   //   CGFloat scaleFactor = 0.0;
   CGFloat scaledWidth = targetWidth;
   CGFloat scaledHeight = targetHeight;

   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

   // this is actually the interesting part:

   UIGraphicsBeginImageContext(targetSize);

   CGRect thumbnailRect = CGRectZero;
   thumbnailRect.origin = thumbnailPoint;
   thumbnailRect.size.width  = scaledWidth;
   thumbnailRect.size.height = scaledHeight;

   [sourceImage drawInRect:thumbnailRect];

   newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if(newImage == nil) NSLog(@"could not scale image");


   return newImage ;
}


- (UIImage *)imageRotatedByRadians:(CGFloat)radians
{
   return [self imageRotatedByDegrees:RadiansToDegrees(radians)];
}

- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees 
{   
   // calculate the size of the rotated view's containing box for our drawing space
   UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
   CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
   rotatedViewBox.transform = t;
   CGSize rotatedSize = rotatedViewBox.frame.size;
   [rotatedViewBox release];

   // Create the bitmap context
   UIGraphicsBeginImageContext(rotatedSize);
   CGContextRef bitmap = UIGraphicsGetCurrentContext();

   // Move the origin to the middle of the image so we will rotate and scale around the center.
   CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

   //   // Rotate the image context
   CGContextRotateCTM(bitmap, DegreesToRadians(degrees));

   // Now, draw the rotated/scaled image into the context
   CGContextScaleCTM(bitmap, 1.0, -1.0);
   CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);

   UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   return newImage;

}

@end;

Setting HttpContext.Current.Session in a unit test

The answer that worked with me is what @Anthony had written, but you have to add another line which is

    request.SetupGet(req => req.Headers).Returns(new NameValueCollection());

so you can use this:

HttpContextFactory.Current.Request.Headers.Add(key, value);

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

How do I change selected value of select2 dropdown with JqGrid?

if you want to set a selected item when you know the text from drop down list and don't know the value, here is an example:

Say you figured out a timezone and want to set it, but values has time_zone_id in them.

        var timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
        var $select2 = $('#time-zone');
        var selected = $select2.find("option:contains('"+timeZone+"')").val();
        $select2.val(selected).trigger('change.select2'); 

Html table tr inside td

You must add a full table inside the td

_x000D_
_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>_x000D_
          <table>_x000D_
            <tr>_x000D_
              <td>_x000D_
                ..._x000D_
              </td>_x000D_
            </tr>_x000D_
          </table>_x000D_
        </td>_x000D_
      </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

Plotting multiple curves same graph and same scale

I'm not sure what you want, but i'll use lattice.

x = rep(x,2)
y = c(y1,y2)
fac.data = as.factor(rep(1:2,each=5))
df = data.frame(x=x,y=y,z=fac.data)
# this create a data frame where I have a factor variable, z, that tells me which data I have (y1 or y2)

Then, just plot

xyplot(y ~x|z, df)
# or maybe
xyplot(x ~y|z, df)

Choice between vector::resize() and vector::reserve()

reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.

Is there any better choice in this kind of scenario?

it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.

fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?

Run script with rc.local: script works, but not at boot

I got my script to work by editing /etc/rc.local then issuing the following 3 commands.

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults

Now the script works at boot.

Bootstrap modal - close modal when "call to action" button is clicked

Use data-dismiss="modal". In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal" is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function

 <a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>

In some external script file, and in my doc ready there is of course a function for the click of that identifier ID

 $("#divExamListHeader").on('click', '#btnReleaseAll', function () {
               // Do DatabaseMagic Here for a call a MVC ActionResult

Comparing two NumPy arrays for equality, element-wise

If you want to check if two arrays have the same shape AND elements you should use np.array_equal as it is the method recommended in the documentation.

Performance-wise don't expect that any equality check will beat another, as there is not much room to optimize comparing two elements. Just for the sake, i still did some tests.

import numpy as np
import timeit

A = np.zeros((300, 300, 3))
B = np.zeros((300, 300, 3))
C = np.ones((300, 300, 3))

timeit.timeit(stmt='(A==B).all()', setup='from __main__ import A, B', number=10**5)
timeit.timeit(stmt='np.array_equal(A, B)', setup='from __main__ import A, B, np', number=10**5)
timeit.timeit(stmt='np.array_equiv(A, B)', setup='from __main__ import A, B, np', number=10**5)
> 51.5094
> 52.555
> 52.761

So pretty much equal, no need to talk about the speed.

The (A==B).all() behaves pretty much as the following code snippet:

x = [1,2,3]
y = [1,2,3]
print all([x[i]==y[i] for i in range(len(x))])
> True

what is the differences between sql server authentication and windows authentication..?

When granting a user access to a database there are a few considerations to be made with advantages and disadvantages in terms of usability and security. Here we have two options for authenticating and granting permission to users. The first is by giving everyone the sa (systems admin) account access and then restricting the permissions manually by retaining a list of the users in which you can grant or deny permissions as needed. This is also known as the SQL authentication method. There are major security flaws in this method, as listed below. The second and better option is to have the Active Directory (AD) handle all the necessary authentication and authorization, also known as Windows authentication. Once the user logs in to their computer the application will connect to the database using those Windows login credentials on the operating system.

The major security issue with using the SQL option is that it violates the principle of least privilege (POLP) which is to only give the user the absolutely necessary permissions they need and no more. By using the sa account you present serious security flaws. The POLP is violated because when the application uses the sa account they have access to the entire database server. Windows authentication on the other hand follows the POLP by only granting access to one database on the server.

The second issue is that there is no need for every instance of the application to have the admin password. This means any application is a potential attack point for the entire server. Windows only uses the Windows credentials to login to the SQL Server. The Windows passwords are stored in a repository as opposed to the SQL database instance itself and the authentication takes place internally within Windows without having to store sa passwords on the application.

A third security issue arises by using the SQL method involves passwords. As presented on the Microsoft website and various security forums, the SQL method doesn’t’ enforce password changing or encryption, rather they are sent as clear text over the network. And the SQL method doesn’t lockout after failing attempts thus allowing a prolonged attempt to break in. Active Directory however, uses Kerberos protocol to encrypt passwords while employing as well a password change system and lockout after failing attempts.

There are efficiency disadvantages as well. Since you will be requiring the user to enter the credentials every time they want to access the database users may forget their credentials.

If a user being removed you would have to remove his credentials from every instance of the application. If you have to update the sa admin password you would have to update every instance of the SQL server. This is time consuming and unsafe, it leaves open the possibility of a dismissed user retaining access to the SQL Server. With the Windows method none of these concerns arise. Everything is centralized and handled by the AD.

The only advantages of using the SQL method lie in its flexibility. You are able to access it from any operating system and network, even remotely. Some older legacy systems as well as some web-based applications may only support sa access.

The AD method also provides time-saving tools such as groups to make it easier to add and remove users, and user tracking ability.

Even if you manage to correct these security flaws in the SQL method, you would be reinventing the wheel. When considering the security advantages provided by Windows authentication, including password policies and following the POLP, it is a much better choice over the SQL authentication. Therefore it is highly recommended to use the Windows authentication option.

Storing JSON in database vs. having a new column for each key

As others have pointed out queries will be slower. I'd suggest to add at least an '_ID' column to query by that instead.

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

C# compiler have only lambda

arg => arg.MyProperty

for infer type of arg(TModel) an type of arg.MyProperty(TProperty). It's impossible.

ORA-06508: PL/SQL: could not find program unit being called

seems like opening a new session is the key.

see this answer.

and here is an awesome explanation about this error

rails generate model

The error shows you either didn't create the rails project yet or you're not in the rails project directory.

Suppose if you're working on myapp project. You've to move to that project directory on your command line and then generate the model. Here are some steps you can refer.

Example: Assuming you didn't create the Rails app yet:

$> rails new myapp
$> cd myapp

Now generate the model from your commandline.

$> rails generate model your_model_name 

How to find text in a column and saving the row number where it is first found - Excel VBA

A few comments:

  1. Since the search position is important you should specify where you start the search. I use ws.[a1] and xlNext below so my search starts in A2 of the specified sheet.
  2. Some of Finds arguments - including lookat use the prior search settings. So you should always specify xlWhole or xlPart to match all or part a string respectively.
  3. You can do all you want - including inserting a row, and prompting the user for a new value (my code will suggest 20 if the prior value was 19) without using Select or Activate

suggested code

Sub FindEm()
Dim Wb As Workbook
Dim ws As Worksheet
Dim rng1 As Range
Set Wb = ThisWorkbook
Set ws = Wb.Sheets("ECM Overview")
Set rng1 = ws.Range("A:A").Find("ProjTemp", ws.[a1], xlValues, xlWhole, , xlNext)
If Not rng1 Is Nothing Then
rng1.EntireRow.Insert
rng1.Offset(-1, 0).Value = Application.InputBox("Please enter data", "User Data Entry", rng1.Offset(-2, 0) + 1, , , , , 1)
Else
MsgBox "ProjTemp not found", vbCritical
End If
End Sub

How to unstash only certain files?

If you git stash pop (with no conflicts) it will remove the stash after it is applied. But if you git stash apply it will apply the patch without removing it from the stash list. Then you can revert the unwanted changes with git checkout -- files...

'POCO' definition

Whilst I'm sure POCO means Plain Old Class Object or Plain Old C Object to 99.9% of people here, POCO is also Animator Pro's (Autodesk) built in scripting language.

How to encode URL parameters?

Just try encodeURI() and encodeURIComponent() yourself...

_x000D_
_x000D_
console.log(encodeURIComponent('@#$%^&*'));
_x000D_
_x000D_
_x000D_

Input: @#$%^&*. Output: %40%23%24%25%5E%26*. So, wait, what happened to *? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent() and fixedEncodeURI(). Long-story...

You should not be using encodeURIComponent() or encodeURI(). You should use fixedEncodeURIComponent() and fixedEncodeURI(), according to the MDN Documentation.

Regarding encodeURI()...

If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:

function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }

Regarding encodeURIComponent()...

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }

So, what is the difference? fixedEncodeURI() and fixedEncodeURIComponent() convert the same set of values, but fixedEncodeURIComponent() also converts this set: +@?=:*#;,$&. This set is used in GET parameters (&, +, etc.), anchor tags (#), wildcard tags (*), email/username parts (@), etc..

For example -- If you use encodeURI(), [email protected]/?email=me@home will not properly send the second @ to the server, except for your browser handling the compatibility (as Chrome naturally does often).

How to add spacing between UITableViewCell

Based on Husam's answer: Using the cell layer instead of content view allows for adding a border around the entire cell and the accessory if need. This method requires careful adjustment of the bottom constraints of the cell as well as those insets otherwise the view will not proper.

@implementation TableViewCell

- (void)awakeFromNib { 
    ... 
}

- (void) layoutSubviews {
    [super layoutSubviews];

    CGRect newFrame = UIEdgeInsetsInsetRect(self.layer.frame, UIEdgeInsetsMake(4, 0, 4, 0));
    self.layer.frame = newFrame;
}

@end

git - Your branch is ahead of 'origin/master' by 1 commit

You cannot push anything that hasn't been committed yet. The order of operations is:

  1. Make your change.
  2. git add - this stages your changes for committing
  3. git commit - this commits your staged changes locally
  4. git push - this pushes your committed changes to a remote

If you push without committing, nothing gets pushed. If you commit without adding, nothing gets committed. If you add without committing, nothing at all happens, git merely remembers that the changes you added should be considered for the following commit.

The message you're seeing (your branch is ahead by 1 commit) means that your local repository has one commit that hasn't been pushed yet.

In other words: add and commit are local operations, push, pull and fetch are operations that interact with a remote.

Since there seems to be an official source control workflow in place where you work, you should ask internally how this should be handled.

Powershell script to check if service is started, if not then start it

Trying to do things as smooth as possible - I here suggest modifying GuyWhoLikesPowershell's suggestion slightly.

I replaced the if and until with one while - and I check for "Stopped", since I don't want to start if status is "starting" or " Stopping".

$Service = 'ServiceName'
while ((Get-Service $Service).Status -eq 'Stopped') 
{
    Start-Service $Service -ErrorAction SilentlyContinue
    Start-Sleep 10
} 
Return "$($Service) has STARTED"

Best way to remove the last character from a string built with stringbuilder

I prefer manipulating the length of the stringbuilder:

data.Length = data.Length - 1;

Changing the default icon in a Windows Forms application

Select your project properties from Project Tab Then Application->Resource->Icon And Manifest->change the default icon

This works in Visual studio 2019 finely Note:Only files with .ico format can be added as icon

How do I define and use an ENUM in Objective-C?

Your typedef needs to be in the header file (or some other file that's #imported into your header), because otherwise the compiler won't know what size to make the PlayerState ivar. Other than that, it looks ok to me.

Subprocess check_output returned non-zero exit status 1

The command yum that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum command to fix that.

Your code could show this error this way:

import subprocess
try:
    subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

How to read GET data from a URL using JavaScript?

The currently selected answer did not work well at all in my case, which I feel is a fairly typical one. I found the below function here and it works great!

function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i=0; i<arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // in case params look like: list[]=thing1&list[]=thing2
      var paramNum = undefined;
      var paramName = a[0].replace(/\[\d*\]/, function(v) {
        paramNum = v.slice(1,-1);
        return '';
      });

      // set parameter value (use 'true' if empty)
      var paramValue = typeof(a[1])==='undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      paramValue = paramValue.toLowerCase();

      // if parameter name already exists
      if (obj[paramName]) {
        // convert value to array (if still string)
        if (typeof obj[paramName] === 'string') {
          obj[paramName] = [obj[paramName]];
        }
        // if no array index number specified...
        if (typeof paramNum === 'undefined') {
          // put the value on the end of the array
          obj[paramName].push(paramValue);
        }
        // if array index number specified...
        else {
          // put the value at that index number
          obj[paramName][paramNum] = paramValue;
        }
      }
      // if param name doesn't exist yet, set it
      else {
        obj[paramName] = paramValue;
      }
    }
  }

  return obj;
}

How to use export with Python on Linux

I've had to do something similar on a CI system recently. My options were to do it entirely in bash (yikes) or use a language like python which would have made programming the logic much simpler.

My workaround was to do the programming in python and write the results to a file. Then use bash to export the results.

For example:

# do calculations in python
with open("./my_export", "w") as f:
    f.write(your_results)
# then in bash
export MY_DATA="$(cat ./my_export)"
rm ./my_export  # if no longer needed

Dynamically create an array of strings with malloc

Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:

char (*orderedIds)[ID_LEN+1]
    = malloc(variableNumberOfElements * sizeof(*orderedIds));

// Clear-up
free(orderedIds);

A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:

char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));
char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);

// Set each pointer to the start of its corresponding section of the raw buffer.
for (i = 0; i < variableNumberOfElements; i++)
{
    orderedIds[i] = &raw[i * (ID_LEN+1)];
}

...

// Clear-up pointer array
free(orderedIds);
// Clear-up raw array
free(raw);

Bluetooth pairing without user confirmation

Yes it is possible in theory as defined by the specification. However there is no practical implementation as yet that would allow this.

Refer: NFC Forum Connection Handover Technical Specification http://www.nfc-forum.org/specs/spec_list/

Quoting from the specification regarding the security - "The Handover Protocol requires transmission of network access data and credentials (the carrier configuration data) to allow one device to connect to a wireless network provided by another device. Because of the close proximity needed for communication between NFC Devices and Tags, eavesdropping of carrier configuration data is difficult, but not impossible, without recognition by the legitimate owner of the devices. Transmission of carrier configuration data to devices that can be brought to close proximity is deemed legitimate within the scope of this specification."

This page didn't load Google Maps correctly. See the JavaScript console for technical details

The fix is really simple: just replace YOUR_API_KEY on the last line of your code with your actual API key!

If you don't have one, you can get it for free on the Google Developers Website.

How can I parse a CSV string with JavaScript, which contains comma in data?

Regular expressions to the rescue! These few lines of code handle properly quoted fields with embedded commas, quotes, and newlines based on the RFC 4180 standard.

function parseCsv(data, fieldSep, newLine) {
    fieldSep = fieldSep || ',';
    newLine = newLine || '\n';
    var nSep = '\x1D';
    var qSep = '\x1E';
    var cSep = '\x1F';
    var nSepRe = new RegExp(nSep, 'g');
    var qSepRe = new RegExp(qSep, 'g');
    var cSepRe = new RegExp(cSep, 'g');
    var fieldRe = new RegExp('(?<=(^|[' + fieldSep + '\\n]))"(|[\\s\\S]+?(?<![^"]"))"(?=($|[' + fieldSep + '\\n]))', 'g');
    var grid = [];
    data.replace(/\r/g, '').replace(/\n+$/, '').replace(fieldRe, function(match, p1, p2) {
        return p2.replace(/\n/g, nSep).replace(/""/g, qSep).replace(/,/g, cSep);
    }).split(/\n/).forEach(function(line) {
        var row = line.split(fieldSep).map(function(cell) {
            return cell.replace(nSepRe, newLine).replace(qSepRe, '"').replace(cSepRe, ',');
        });
        grid.push(row);
    });
    return grid;
}

const csv = 'A1,B1,C1\n"A ""2""","B, 2","C\n2"';
const separator = ',';      // field separator, default: ','
const newline = ' <br /> '; // newline representation in case a field contains newlines, default: '\n' 
var grid = parseCsv(csv, separator, newline);
// expected: [ [ 'A1', 'B1', 'C1' ], [ 'A "2"', 'B, 2', 'C <br /> 2' ] ]

Unless stated elsewhere, you don't need a finite state machine. The regular expression handles RFC 4180 properly thanks to positive lookbehind, negative lookbehind, and positive lookahead.

Clone/download code at https://github.com/peterthoeny/parse-csv-js

How to input automatically when running a shell over SSH?

For general command-line automation, Expect is the classic tool. Or try pexpect if you're more comfortable with Python.

Here's a similar question that suggests using Expect: Use expect in bash script to provide password to SSH command

Count the number occurrences of a character in a string

"Without using count to find you want character in string" method.

import re

def count(s, ch):

   pass

def main():

   s = raw_input ("Enter strings what you like, for example, 'welcome': ")  

   ch = raw_input ("Enter you want count characters, but best result to find one character: " )

   print ( len (re.findall ( ch, s ) ) )

main()

cannot resolve symbol javafx.application in IntelliJ Idea IDE

Sample Java application:

I'm crossposting my answer from another question here since it is related and also seems to solve the problem in the question.

Here is my example project with OpenJDK 12, JavaFX 12 and Gradle 5.4

  • Opens a JavaFX window with the title "Hello World!"
  • Able to build a working runnable distribution zip file (Windows to be tested)
  • Able to open and run in IntelliJ without additional configuration
  • Able to run from the command line

I hope somebody finds the Github project useful.

Instructions for the Scala case:

Additionally below are instructions that work with the Gradle Scala plugin, but don't seem work with Java. I'm leaving this here in case somebody else is also using Scala, Gradle and JavaFX.

1) As mentioned in the question, the JavaFX Gradle plugin needs to be set up. Open JavaFX has detailed documentation on this

2) Additionally you need the the JavaFX SDK for your platform unzipped somewhere. NOTE: Be sure to scroll down to Latest releases section where JavaFX 12 is (LTS 11 is first for some reason.)

3) Then, in IntelliJ you go to the File -> Project Structure -> Libraries, hit the ?-button and add the lib folder from the unzipped JavaFX SDK.

For longer instructions with screenshots, check out the excellent Open JavaFX docs for IntelliJ I can't get a deep link working, so select JavaFX and IntelliJ and then Modular from IDE from the docs nav. Then scroll down to step 3. Create a library. Consider checking the other steps too if you are having trouble.

It is difficult to say if this is exactly the same situation as in the original question, but it looked similar enough that I landed here, so I'm adding my experience here to help others.

Python Pandas iterate over rows and access column names

for i in range(1,len(na_rm.columns)):
           print ("column name:", na_rm.columns[i])

Output :

column name: seretide_price
column name: symbicort_mkt_shr
column name: symbicort_price

EditText underline below text property

You can change the color of EditText programmatically just using this line of code easily:

edittext.setBackgroundTintList(ColorStateList.valueOf(yourcolor));

Postman: How to make multiple requests at the same time

I guess there's no such feature in postman as to run concurrent tests.

If i were you i would consider Apache jMeter which is used exactly for such scenarios.

Regarding Postman, the only thing that could more or less meet your needs is - Postman Runner. enter image description here There you can specify the details:

  • number of iterations,
  • upload csv file with data for different test runs, etc.

The runs won't be concurrent, only consecutive.

Hope that helps. But do consider jMeter (you'll love it).

What does InitializeComponent() do, and how does it work in WPF?

Looking at the code always helps too. That is, you can actually take a look at the generated partial class (that calls LoadComponent) by doing the following:

  1. Go to the Solution Explorer pane in the Visual Studio solution that you are interested in.
  2. There is a button in the tool bar of the Solution Explorer titled 'Show All Files'. Toggle that button.
  3. Now, expand the obj folder and then the Debug or Release folder (or whatever configuration you are building) and you will see a file titled YourClass.g.cs.

The YourClass.g.cs ... is the code for generated partial class. Again, if you open that up you can see the InitializeComponent method and how it calls LoadComponent ... and much more.

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");