Programs & Examples On #Concurrency

In computer science, concurrency is a property of systems in which multiple computations can be performed in overlapping time periods. The computations may be executing on multiple cores in the same chip, preemptively time-shared threads on the same processor, or executed on physically separated processors.

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

Instead of thinking of code or classes as thread safe or not, I think it is more helpful to think of actions as being thread-safe. Two actions are thread safe if they will be behave as specified when run from arbitrary threading contexts. In many cases, classes will support some combinations of actions in thread-safe fashion and others not.

For example, many collections like array-lists and hash sets will guarantee that if they are initially accessed exclusively with one thread, and they are never modified after a reference becomes visible to any other threads, they may be read in arbitrary fashion by any combination of threads without interference.

More interestingly, some hash-set collections such as the original non-generic one in .NET, may offer a guarantee that as long as no item is ever removed, and provided that only one thread ever writes to them, any thread that tries to read the collection will behave as though accessing a collection where updates might be delayed and occur in arbitrary order, but which will otherwise behave normally. If thread #1 adds X and then Y, and thread #2 looks for and sees Y and then X, it would be possible for thread #2 to see that Y exists but X doesn't; whether or not such behavior is "thread-safe" would depend upon whether thread #2 is prepared to deal with that possibility.

As a final note, some classes--especially blocking communications libraries--may have a "close" or "Dispose" method which is thread-safe with respect to all other methods, but no other methods that are thread-safe with respect to each other. If a thread performs a blocking read request and a user of the program clicks "cancel", there would be no way for a close request to be issued by the thread that's attempting to perform the read. The close/dispose request, however, may asynchronously set a flag which will cause the read request to be canceled as soon as possible. Once close is performed on any thread, the object would become useless, and all attempts at future actions would fail immediately, but being able to asynchronously terminate any attempted I/O operations is better than require that the close request be synchronized with the read (since if the read blocks forever, the synchronization request would be likewise blocked).

Why must wait() always be in synchronized block

We all know that wait(), notify() and notifyAll() methods are used for inter-threaded communications. To get rid of missed signal and spurious wake up problems, waiting thread always waits on some conditions. e.g.-

boolean wasNotified = false;
while(!wasNotified) {
    wait();
}

Then notifying thread sets wasNotified variable to true and notify.

Every thread has their local cache so all the changes first get written there and then promoted to main memory gradually.

Had these methods not invoked within synchronized block, the wasNotified variable would not be flushed into main memory and would be there in thread's local cache so the waiting thread will keep waiting for the signal although it was reset by notifying thread.

To fix these types of problems, these methods are always invoked inside synchronized block which assures that when synchronized block starts then everything will be read from main memory and will be flushed into main memory before exiting the synchronized block.

synchronized(monitor) {
    boolean wasNotified = false;
    while(!wasNotified) {
        wait();
    }
}

Thanks, hope it clarifies.

pthread_join() and pthread_exit()

It because every time

void pthread_exit(void *ret);

will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().

Now at

int pthread_join(pthread_t tid, void **ret);

will be always called from where thread is created so here to accept that returned pointer you need double pointer ..

i think this code will help you to understand this

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>

void* thread_function(void *ignoredInThisExample)
{
    char *a = malloc(10);
    strcpy(a,"hello world");
    pthread_exit((void*)a);
}
int main()
{
    pthread_t thread_id;
    char *b;

    pthread_create (&thread_id, NULL,&thread_function, NULL);

    pthread_join(thread_id,(void**)&b); //here we are reciving one pointer 
                                        value so to use that we need double pointer 
    printf("b is %s\n",b); 
    free(b); // lets free the memory

}

Volatile boolean vs AtomicBoolean

Volatile boolean vs AtomicBoolean

The Atomic* classes wrap a volatile primitive of the same type. From the source:

public class AtomicLong extends Number implements java.io.Serializable {
   ...
   private volatile long value;
   ...
   public final long get() {
       return value;
   }
   ...
   public final void set(long newValue) {
       value = newValue;
   }

So if all you are doing is getting and setting a Atomic* then you might as well just have a volatile field instead.

What does AtomicBoolean do that a volatile boolean cannot achieve?

Atomic* classes give you methods that provide more advanced functionality such as incrementAndGet() for numbers, compareAndSet() for booleans, and other methods that implement multiple operations (get/increment/set, test/set) without locking. That's why the Atomic* classes are so powerful.

For example, if multiple threads are using the following code using ++, there will be race conditions because ++ is actually: get, increment, and set.

private volatile value;
...
// race conditions here
value++;

However, the following code will work in a multi-threaded environment safely without locks:

private final AtomicLong value = new AtomicLong();
...
value.incrementAndGet();

It's also important to note that wrapping your volatile field using Atomic* class is a good way to encapsulate the critical shared resource from an object standpoint. This means that developers can't just deal with the field assuming it is not shared possibly injecting problems with a field++; or other code that introducing race conditions.

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/

What is a deadlock?

A lock occurs when multiple processes try to access the same resource at the same time.

One process loses out and must wait for the other to finish.

A deadlock occurs when the waiting process is still holding on to another resource that the first needs before it can finish.

So, an example:

Resource A and resource B are used by process X and process Y

  • X starts to use A.
  • X and Y try to start using B
  • Y 'wins' and gets B first
  • now Y needs to use A
  • A is locked by X, which is waiting for Y

The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to lock anything as much as you can.

In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and switch to optimistic/dirty/nolock reads as much as possible.

What is a database transaction?

Here's a simple explanation. You need to transfer 100 bucks from account A to account B. You can either do:

accountA -= 100;
accountB += 100;

or

accountB += 100;
accountA -= 100;

If something goes wrong between the first and the second operation in the pair you have a problem - either 100 bucks have disappeared, or they have appeared out of nowhere.

A transaction is a mechanism that allows you to mark a group of operations and execute them in such a way that either they all execute (commit), or the system state will be as if they have not started to execute at all (rollback).

beginTransaction;
accountB += 100;
accountA -= 100;
commitTransaction;

will either transfer 100 bucks or leave both accounts in the initial state.

What's the difference between a Future and a Promise?

Future and Promise are proxy object for unknown result

Promise completes a Future

  • Future - read/consumer of unknown result

  • Promise - write/producer of unknown result.

//Future has a reference to Promise
Future -> Promise

As a producer I promise something and responsible for it

As a consumer who retrieved a promise I expect to have a result in future

As for Java CompletableFutures it is a Promise because you can set the result and also it implements Future

Is iterating ConcurrentHashMap values thread safe?

You may use this class to test two accessing threads and one mutating the shared instance of ConcurrentHashMap:

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Map<String, String> map;

    public Accessor(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (Map.Entry<String, String> entry : this.map.entrySet())
      {
        System.out.println(
            Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']'
        );
      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Map<String, String> map;
    private final Random random = new Random();

    public Mutator(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (int i = 0; i < 100; i++)
      {
        this.map.remove("key" + random.nextInt(MAP_SIZE));
        this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
        System.out.println(Thread.currentThread().getName() + ": " + i);
      }
    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.map);
    Accessor a2 = new Accessor(this.map);
    Mutator m = new Mutator(this.map);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

No exception will be thrown.

Sharing the same iterator between accessor threads can lead to deadlock:

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();
  private final Iterator<Map.Entry<String, String>> iterator;

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
    this.iterator = this.map.entrySet().iterator();
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Iterator<Map.Entry<String, String>> iterator;

    public Accessor(Iterator<Map.Entry<String, String>> iterator)
    {
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while(iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        try
        {
          String st = Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
        } catch (Exception e)
        {
          e.printStackTrace();
        }

      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Map<String, String> map;
    private final Random random = new Random();

    public Mutator(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (int i = 0; i < 100; i++)
      {
        this.map.remove("key" + random.nextInt(MAP_SIZE));
        this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
      }
    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.iterator);
    Accessor a2 = new Accessor(this.iterator);
    Mutator m = new Mutator(this.map);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

As soon as you start sharing the same Iterator<Map.Entry<String, String>> among accessor and mutator threads java.lang.IllegalStateExceptions will start popping up.

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();
  private final Iterator<Map.Entry<String, String>> iterator;

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
    this.iterator = this.map.entrySet().iterator();
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Iterator<Map.Entry<String, String>> iterator;

    public Accessor(Iterator<Map.Entry<String, String>> iterator)
    {
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while (iterator.hasNext())
      {
        Map.Entry<String, String> entry = iterator.next();
        try
        {
          String st =
              Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
        } catch (Exception e)
        {
          e.printStackTrace();
        }

      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Random random = new Random();

    private final Iterator<Map.Entry<String, String>> iterator;

    private final Map<String, String> map;

    public Mutator(Map<String, String> map, Iterator<Map.Entry<String, String>> iterator)
    {
      this.map = map;
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while (iterator.hasNext())
      {
        try
        {
          iterator.remove();
          this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
        } catch (Exception ex)
        {
          ex.printStackTrace();
        }
      }

    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.iterator);
    Accessor a2 = new Accessor(this.iterator);
    Mutator m = new Mutator(map, this.iterator);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

Volatile vs Static in Java

In addition to other answers, I would like to add one image for it(pic makes easy to understand)

enter image description here

static variables may be cached for individual threads. In multi-threaded environment if one thread modifies its cached data, that may not reflect for other threads as they have a copy of it.

volatile declaration makes sure that threads won't cache the data and uses the shared copy only.

image source

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

To address the question more generally...

Keep in mind that using synchronized on methods is really just shorthand (assume class is SomeClass):

synchronized static void foo() {
    ...
}

is the same as

static void foo() {
    synchronized(SomeClass.class) {
        ...
    }
}

and

synchronized void foo() {
    ...
}

is the same as

void foo() {
    synchronized(this) {
        ...
    }
}

You can use any object as the lock. If you want to lock subsets of static methods, you can

class SomeClass {
    private static final Object LOCK_1 = new Object() {};
    private static final Object LOCK_2 = new Object() {};
    static void foo() {
        synchronized(LOCK_1) {...}
    }
    static void fee() {
        synchronized(LOCK_1) {...}
    }
    static void fie() {
        synchronized(LOCK_2) {...}
    }
    static void fo() {
        synchronized(LOCK_2) {...}
    }
}

(for non-static methods, you would want to make the locks be non-static fields)

What is a mutex?

To understand MUTEX at first you need to know what is "race condition" and then only you will understand why MUTEX is needed. Suppose you have a multi-threading program and you have two threads. Now, you have one job in the job queue. The first thread will check the job queue and after finding the job it will start executing it. The second thread will also check the job queue and find that there is one job in the queue. So, it will also assign the same job pointer. So, now what happens, both the threads are executing the same job. This will cause a segmentation fault. This is the example of a race condition.

The solution to this problem is MUTEX. MUTEX is a kind of lock which locks one thread at a time. If another thread wants to lock it, the thread simply gets blocked.

The MUTEX topic in this pdf file link is really worth reading.

What is the difference between concurrency and parallelism?

Pike's notion of "concurrency" is an intentional design and implementation decision. A concurrent-capable program design may or may not exhibit behavioral "parallelism"; it depends upon the runtime environment.

You don't want parallelism exhibited by a program that wasn't designed for concurrency. :-) But to the extent that it's a net gain for the relevant factors (power consumption, performance, etc.), you want a maximally-concurrent design so that the host system can parallelize its execution when possible.

Pike's Go programming language illustrates this in the extreme: his functions are all threads that can run correctly concurrently, i.e. calling a function always creates a thread that will run in parallel with the caller if the system is capable of it. An application with hundreds or even thousands of threads is perfectly ordinary in his world. (I'm no Go expert, that's just my take on it.)

What is a race condition?

Here is the classical Bank Account Balance example which will help newbies to understand Threads in Java easily w.r.t. race conditions:

public class BankAccount {

/**
 * @param args
 */
int accountNumber;
double accountBalance;

public synchronized boolean Deposit(double amount){
    double newAccountBalance=0;
    if(amount<=0){
        return false;
    }
    else {
        newAccountBalance = accountBalance+amount;
        accountBalance=newAccountBalance;
        return true;
    }

}
public synchronized boolean Withdraw(double amount){
    double newAccountBalance=0;
    if(amount>accountBalance){
        return false;
    }
    else{
        newAccountBalance = accountBalance-amount;
        accountBalance=newAccountBalance;
        return true;
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    BankAccount b = new BankAccount();
    b.accountBalance=2000;
    System.out.println(b.Withdraw(3000));

}

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

When and how should I use a ThreadLocal variable?

You have to be very careful with the ThreadLocal pattern. There are some major down sides like Phil mentioned, but one that wasn't mentioned is to make sure that the code that sets up the ThreadLocal context isn't "re-entrant."

Bad things can happen when the code that sets the information gets run a second or third time because information on your thread can start to mutate when you didn't expect it. So take care to make sure the ThreadLocal information hasn't been set before you set it again.

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

Is JavaScript guaranteed to be single-threaded?

JavaScript/ECMAScript is designed to live within a host environment. That is, JavaScript doesn't actually do anything unless the host environment decides to parse and execute a given script, and provide environment objects that let JavaScript actually be useful (such as the DOM in browsers).

I think a given function or script block will execute line-by-line and that is guaranteed for JavaScript. However, perhaps a host environment could execute multiple scripts at the same time. Or, a host environment could always provide an object that provides multi-threading. setTimeout and setInterval are examples, or at least pseudo-examples, of a host environment providing a way to do some concurrency (even if it's not exactly concurrency).

When do I need to use AtomicBoolean in Java?

When multiple threads need to check and change the boolean. For example:

if (!initialized) {
   initialize();
   initialized = true;
}

This is not thread-safe. You can fix it by using AtomicBoolean:

if (atomicInitialized.compareAndSet(false, true)) {
    initialize();
}

How to check if a table is locked in sql server

You can use the sys.dm_tran_locks view, which returns information about the currently active lock manager resources.

Try this

 SELECT 
     SessionID = s.Session_id,
     resource_type,   
     DatabaseName = DB_NAME(resource_database_id),
     request_mode,
     request_type,
     login_time,
     host_name,
     program_name,
     client_interface_name,
     login_name,
     nt_domain,
     nt_user_name,
     s.status,
     last_request_start_time,
     last_request_end_time,
     s.logical_reads,
     s.reads,
     request_status,
     request_owner_type,
     objectid,
     dbid,
     a.number,
     a.encrypted ,
     a.blocking_session_id,
     a.text       
 FROM   
     sys.dm_tran_locks l
     JOIN sys.dm_exec_sessions s ON l.request_session_id = s.session_id
     LEFT JOIN   
     (
         SELECT  *
         FROM    sys.dm_exec_requests r
         CROSS APPLY sys.dm_exec_sql_text(sql_handle)
     ) a ON s.session_id = a.session_id
 WHERE  
     s.session_id > 50

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

t.start() is the method that the library provides for your code to call when you want a new thread.

r.run() is the method that you provide for the library to call in the new thread.


Most of these answers miss the big picture, which is that, as far as the Java language is concerned, there is no more difference between t.start() and r.run() than there is between any other two methods.

They're both just methods. They both run in the thread that called them. They both do whatever they were coded to do, and then they both return, still in the same thread, to their callers.

The biggest difference is that most of the code for t.start() is native code while, in most cases, the code for r.run() is going to be pure Java. But that's not much of a difference. Code is code. Native code is harder to find, and harder to understand when you find it, but it's still just code that tells the computer what to do.

So, what does t.start() do?

It creates a new native thread, it arranges for that thread to call t.run(), and then it tells the OS to let the new thread run. Then it returns.

And what does r.run() do?

The funny thing is, the person asking this question is the person who wrote it. r.run() does whatever you (i.e., the developer who wrote it) designed it to do.

What is a semaphore?

A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece of code has access to that resource. This keeps two threads from concurrently accesing a resource, which can cause problems.

NSOperation vs Grand Central Dispatch

GCD is indeed lower-level than NSOperationQueue, its major advantage is that its implementation is very light-weight and focused on lock-free algorithms and performance.

NSOperationQueue does provide facilities that are not available in GCD, but they come at non-trivial cost, the implementation of NSOperationQueue is complex and heavy-weight, involves a lot of locking, and uses GCD internally only in a very minimal fashion.

If you need the facilities provided by NSOperationQueue by all means use it, but if GCD is sufficient for your needs, I would recommend using it directly for better performance, significantly lower CPU and power cost and more flexibility.

Synchronization vs Lock

Brian Goetz's "Java Concurrency In Practice" book, section 13.3: "...Like the default ReentrantLock, intrinsic locking offers no deterministic fairness guarantees, but the statistical fairness guarantees of most locking implementations are good enough for almost all situations..."

What is a good pattern for using a Global Mutex in C#?

I want to make sure this is out there, because it's so hard to get right:

using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection;                //Assembly
using System.Threading;                 //Mutex
using System.Security.AccessControl;    //MutexAccessRule
using System.Security.Principal;        //SecurityIdentifier

static void Main(string[] args)
{
    // get application GUID as defined in AssemblyInfo.cs
    string appGuid =
        ((GuidAttribute)Assembly.GetExecutingAssembly().
            GetCustomAttributes(typeof(GuidAttribute), false).
                GetValue(0)).Value.ToString();

    // unique id for global mutex - Global prefix means it is global to the machine
    string mutexId = string.Format( "Global\\{{{0}}}", appGuid );

    // Need a place to store a return value in Mutex() constructor call
    bool createdNew;

    // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
    // edited by 'Marc' to work also on localized systems (don't use just "Everyone") 
    var allowEveryoneRule =
        new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
                                                   , null)
                           , MutexRights.FullControl
                           , AccessControlType.Allow
                           );
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);

   // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
    using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
    {
        // edited by acidzombie24
        var hasHandle = false;
        try
        {
            try
            {
                // note, you may want to time out here instead of waiting forever
                // edited by acidzombie24
                // mutex.WaitOne(Timeout.Infinite, false);
                hasHandle = mutex.WaitOne(5000, false);
                if (hasHandle == false)
                    throw new TimeoutException("Timeout waiting for exclusive access");
            }
            catch (AbandonedMutexException)
            {
                // Log the fact that the mutex was abandoned in another process,
                // it will still get acquired
                hasHandle = true;
            }

            // Perform your work here.
        }
        finally
        {
            // edited by acidzombie24, added if statement
            if(hasHandle)
                mutex.ReleaseMutex();
        }
    }
}

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

From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.

SET NOCOUNT ON usage

I know it's pretty old question. but just for update.

Best way to use "SET NOCOUNT ON" is to put it up as a first statement in your SP and setting it OFF again just before the last SELECT statement.

How to asynchronously call a method in Java

You can use the Java8 syntax for CompletableFuture, this way you can perform additional async computations based on the result from calling an async function.

for example:

 CompletableFuture.supplyAsync(this::findSomeData)
                     .thenApply(this:: intReturningMethod)
                     .thenAccept(this::notify);

More details can be found in this article

iPhone - Grand Central Dispatch main thread

Dispatching a block to the main queue is usually done from a background queue to signal that some background processing has finished e.g.

- (void)doCalculation
{
    //you can use any string instead "com.mycompany.myqueue"
    dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);

    dispatch_async(backgroundQueue, ^{
        int result = <some really long calculation that takes seconds to complete>;

        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateMyUIWithResult:result];
        });    
    });
}

In this case, we are doing a lengthy calculation on a background queue and need to update our UI when the calculation is complete. Updating UI normally has to be done from the main queue so we 'signal' back to the main queue using a second nested dispatch_async.

There are probably other examples where you might want to dispatch back to the main queue but it is generally done in this way i.e. nested from within a block dispatched to a background queue.

  • background processing finished -> update UI
  • chunk of data processed on background queue -> signal main queue to start next chunk
  • incoming network data on background queue -> signal main queue that message has arrived
  • etc etc

As to why you might want to dispatch to the main queue from the main queue... Well, you generally wouldn't although conceivably you might do it to schedule some work to do the next time around the run loop.

What is mutex and semaphore in Java ? What is the main difference?

Semaphore can be counted, while mutex can only count to 1.

Suppose you have a thread running which accepts client connections. This thread can handle 10 clients simultaneously. Then each new client sets the semaphore until it reaches 10. When the Semaphore has 10 flags, then your thread won't accept new connections

Mutex are usually used for guarding stuff. Suppose your 10 clients can access multiple parts of the system. Then you can protect a part of the system with a mutex so when 1 client is connected to that sub-system, no one else should have access. You can use a Semaphore for this purpose too. A mutex is a "Mutual Exclusion Semaphore".

Why use a ReentrantLock if one can use synchronized(this)?

From oracle documentation page about ReentrantLock:

A reentrant mutual exclusion Lock with the same basic behaviour and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

  1. A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.

  2. The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order.

ReentrantLock key features as per this article

  1. Ability to lock interruptibly.
  2. Ability to timeout while waiting for lock.
  3. Power to create fair lock.
  4. API to get list of waiting thread for lock.
  5. Flexibility to try for lock without blocking.

You can use ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock to further acquire control on granular locking on read and write operations.

Have a look at this article by Benjamen on usage of different type of ReentrantLocks

Is there a concurrent List in Java's JDK?

You can very well use Collections.synchronizedList(List) if all you need is simple invocation synchronization:

 List<Object> objList = Collections.synchronizedList(new ArrayList<Object>());

Custom thread pool in Java 8 parallel stream

The parallel streams use the default ForkJoinPool.commonPool which by default has one less threads as you have processors, as returned by Runtime.getRuntime().availableProcessors() (This means that parallel streams leave one processor for the calling thread).

For applications that require separate or custom pools, a ForkJoinPool may be constructed with a given target parallelism level; by default, equal to the number of available processors.

This also means if you have nested parallel streams or multiple parallel streams started concurrently, they will all share the same pool. Advantage: you will never use more than the default (number of available processors). Disadvantage: you may not get "all the processors" assigned to each parallel stream you initiate (if you happen to have more than one). (Apparently you can use a ManagedBlocker to circumvent that.)

To change the way parallel streams are executed, you can either

  • submit the parallel stream execution to your own ForkJoinPool: yourFJP.submit(() -> stream.parallel().forEach(soSomething)).get(); or
  • you can change the size of the common pool using system properties: System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20") for a target parallelism of 20 threads. However, this no longer works after the backported patch https://bugs.openjdk.java.net/browse/JDK-8190974.

Example of the latter on my machine which has 8 processors. If I run the following program:

long start = System.currentTimeMillis();
IntStream s = IntStream.range(0, 20);
//System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
s.parallel().forEach(i -> {
    try { Thread.sleep(100); } catch (Exception ignore) {}
    System.out.print((System.currentTimeMillis() - start) + " ");
});

The output is:

215 216 216 216 216 216 216 216 315 316 316 316 316 316 316 316 415 416 416 416

So you can see that the parallel stream processes 8 items at a time, i.e. it uses 8 threads. However, if I uncomment the commented line, the output is:

215 215 215 215 215 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216

This time, the parallel stream has used 20 threads and all 20 elements in the stream have been processed concurrently.

ConcurrentModificationException for ArrayList

I like a reverse order for loop such as:

int size = list.size();
for (int i = size - 1; i >= 0; i--) {
    if(remove){
        list.remove(i);
    }
}

because it doesn't require learning any new data structures or classes.

ExecutorService that interrupts tasks after a timeout

Wrap the task in FutureTask and you can specify timeout for the FutureTask. Look at the example in my answer to this question,

java native Process timeout

Lock, mutex, semaphore... what's the difference?

Take a look at Multithreading Tutorial by John Kopplin.

In the section Synchronization Between Threads, he explain the differences among event, lock, mutex, semaphore, waitable timer

A mutex can be owned by only one thread at a time, enabling threads to coordinate mutually exclusive access to a shared resource

Critical section objects provide synchronization similar to that provided by mutex objects, except that critical section objects can be used only by the threads of a single process

Another difference between a mutex and a critical section is that if the critical section object is currently owned by another thread, EnterCriticalSection() waits indefinitely for ownership whereas WaitForSingleObject(), which is used with a mutex, allows you to specify a timeout

A semaphore maintains a count between zero and some maximum value, limiting the number of threads that are simultaneously accessing a shared resource.

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

Which concurrent Queue implementation should I use in Java?

Basically the difference between them are performance characteristics and blocking behavior.

Taking the easiest first, ArrayBlockingQueue is a queue of a fixed size. So if you set the size at 10, and attempt to insert an 11th element, the insert statement will block until another thread removes an element. The fairness issue is what happens if multiple threads try to insert and remove at the same time (in other words during the period when the Queue was blocked). A fairness algorithm ensures that the first thread that asks is the first thread that gets. Otherwise, a given thread may wait longer than other threads, causing unpredictable behavior (sometimes one thread will just take several seconds because other threads that started later got processed first). The trade-off is that it takes overhead to manage the fairness, slowing down the throughput.

The most important difference between LinkedBlockingQueue and ConcurrentLinkedQueue is that if you request an element from a LinkedBlockingQueue and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue will return right away with the behavior of an empty queue.

Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.

What is the difference between concurrent programming and parallel programming?

Classic scheduling of tasks can be serial, parallel or concurrent.

  • Serial: tasks must be executed one after the other in a known tricked order or it will not work. Easy enough.

  • Parallel: tasks must be executed at the same time or it will not work.

    • Any failure of any of the tasks - functionally or in time - will result in total system failure.
    • All tasks must have a common reliable sense of time.

    Try to avoid this or we will have tears by tea time.

  • Concurrent: we do not care. We are not careless, though: we have analysed it and it doesn't matter; we can therefore execute any task using any available facility at any time. Happy days.

Often, the available scheduling changes at known events which we call a state change.

People often think this is about software, but it is in fact a systems design concept that pre-dates computers; software systems were a little slow in the uptake, very few software languages even attempt to address the problem. You might try looking up the transputer language occam if you are interested.

Succinctly, systems design addresses the following:

  • the verb - what you are doing (operation or algorithm)
  • the noun - what you are doing it to (data or interface)
  • when - initiation, schedule, state changes
  • how - serial, parallel, concurrent
  • where - once you know when things happen, you can say where they can happen and not before.
  • why - is this the way to do it? Are there other ways, and more importantly, a better way? What happens if you don't do it?

Good luck.

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

In case of synchronized methods, lock will be acquired on an Object. But if you go with synchronized block you have an option to specify an object on which the lock will be acquired.

Example :

    Class Example {
    String test = "abc";
    // lock will be acquired on String  test object.
    synchronized (test) {
        // do something
    }

   lock will be acquired on Example Object
   public synchronized void testMethod() {
     // do some thing
   } 

   }

Choosing the best concurrency list in Java

If set is sufficient, ConcurrentSkipListSet might be used. (Its implementation is based on ConcurrentSkipListMap which implements a skip list.)

The expected average time cost is log(n) for the contains, add, and remove operations; the size method is not a constant-time operation.

Why there is no ConcurrentHashSet against ConcurrentHashMap

Set<String> mySet = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

Just to complete the other answers, I would like to quote Effective Java, 2nd Edition, by Joshua Bloch, chapter 10, Item 68 :

"Choosing the executor service for a particular application can be tricky. If you’re writing a small program, or a lightly loaded server, using Executors.new- CachedThreadPool is generally a good choice, as it demands no configuration and generally “does the right thing.” But a cached thread pool is not a good choice for a heavily loaded production server!

In a cached thread pool, submitted tasks are not queued but immediately handed off to a thread for execution. If no threads are available, a new one is created. If a server is so heavily loaded that all of its CPUs are fully utilized, and more tasks arrive, more threads will be created, which will only make matters worse.

Therefore, in a heavily loaded production server, you are much better off using Executors.newFixedThreadPool, which gives you a pool with a fixed number of threads, or using the ThreadPoolExecutor class directly, for maximum control."

What is the Swift equivalent to Objective-C's "@synchronized"?

Another method is to create a superclass and then inherit it. This way you can use GCD more directly

class Lockable {
    let lockableQ:dispatch_queue_t

    init() {
        lockableQ = dispatch_queue_create("com.blah.blah.\(self.dynamicType)", DISPATCH_QUEUE_SERIAL)
    }

    func lock(closure: () -> ()) {
        dispatch_sync(lockableQ, closure)
    }
}


class Foo: Lockable {

    func boo() {
        lock {
            ....... do something
        }
    }

How to check if another instance of my shell script is running

I you want the "pidof" method, here is the trick:

    if pidof -o %PPID -x "abc.sh">/dev/null; then
        echo "Process already running"
    fi

Where the -o %PPID parameter tells to omit the pid of the calling shell or shell script. More info in the pidof man page.

How can I use threading in Python?

For me, the perfect example for threading is monitoring asynchronous events. Look at this code.

# thread_test.py
import threading
import time

class Monitor(threading.Thread):
    def __init__(self, mon):
        threading.Thread.__init__(self)
        self.mon = mon

    def run(self):
        while True:
            if self.mon[0] == 2:
                print "Mon = 2"
                self.mon[0] = 3;

You can play with this code by opening an IPython session and doing something like:

>>> from thread_test import Monitor
>>> a = [0]
>>> mon = Monitor(a)
>>> mon.start()
>>> a[0] = 2
Mon = 2
>>>a[0] = 2
Mon = 2

Wait a few minutes

>>> a[0] = 2
Mon = 2

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

For your needs, use ConcurrentHashMap. It allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).

Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.

Practical uses for AtomicInteger

There are two main uses of AtomicInteger:

  • As an atomic counter (incrementAndGet(), etc) that can be used by many threads concurrently

  • As a primitive that supports compare-and-swap instruction (compareAndSet()) to implement non-blocking algorithms.

    Here is an example of non-blocking random number generator from Brian Göetz's Java Concurrency In Practice:

    public class AtomicPseudoRandom extends PseudoRandom {
        private AtomicInteger seed;
        AtomicPseudoRandom(int seed) {
            this.seed = new AtomicInteger(seed);
        }
    
        public int nextInt(int n) {
            while (true) {
                int s = seed.get();
                int nextSeed = calculateNext(s);
                if (seed.compareAndSet(s, nextSeed)) {
                    int remainder = s % n;
                    return remainder > 0 ? remainder : remainder + n;
                }
            }
        }
        ...
    }
    

    As you can see, it basically works almost the same way as incrementAndGet(), but performs arbitrary calculation (calculateNext()) instead of increment (and processes the result before return).

multiprocessing.Pool: When to use apply, apply_async or map?

Here is an overview in a table format in order to show the differences between Pool.apply, Pool.apply_async, Pool.map and Pool.map_async. When choosing one, you have to take multi-args, concurrency, blocking, and ordering into account:

                  | Multi-args   Concurrence    Blocking     Ordered-results
---------------------------------------------------------------------
Pool.map          | no           yes            yes          yes
Pool.map_async    | no           yes            no           yes
Pool.apply        | yes          no             yes          no
Pool.apply_async  | yes          yes            no           no
Pool.starmap      | yes          yes            yes          yes
Pool.starmap_async| yes          yes            no           no

Notes:

  • Pool.imap and Pool.imap_async – lazier version of map and map_async.

  • Pool.starmap method, very much similar to map method besides it acceptance of multiple arguments.

  • Async methods submit all the processes at once and retrieve the results once they are finished. Use get method to obtain the results.

  • Pool.map(or Pool.apply)methods are very much similar to Python built-in map(or apply). They block the main process until all the processes complete and return the result.

Examples:

map

Is called for a list of jobs in one time

results = pool.map(func, [1, 2, 3])

apply

Can only be called for one job

for x, y in [[1, 1], [2, 2]]:
    results.append(pool.apply(func, (x, y)))

def collect_result(result):
    results.append(result)

map_async

Is called for a list of jobs in one time

pool.map_async(func, jobs, callback=collect_result)

apply_async

Can only be called for one job and executes a job in the background in parallel

for x, y in [[1, 1], [2, 2]]:
    pool.apply_async(worker, (x, y), callback=collect_result)

starmap

Is a variant of pool.map which support multiple arguments

pool.starmap(func, [(1, 1), (2, 1), (3, 1)])

starmap_async

A combination of starmap() and map_async() that iterates over iterable of iterables and calls func with the iterables unpacked. Returns a result object.

pool.starmap_async(calculate_worker, [(1, 1), (2, 1), (3, 1)], callback=collect_result)

Reference:

Find complete documentation here: https://docs.python.org/3/library/multiprocessing.html

Collection was modified; enumeration operation may not execute

I want to point out other case not reflected in any of the answers. I have a Dictionary<Tkey,TValue> shared in a multi threaded app, which uses a ReaderWriterLockSlim to protect the read and write operations. This is a reading method that throws the exception:

public IEnumerable<Data> GetInfo()
{
    List<Data> info = null;
    _cacheLock.EnterReadLock();
    try
    {
        info = _cache.Values.SelectMany(ce => ce.Data); // Ad .Tolist() to avoid exc.
    }
    finally
    {
        _cacheLock.ExitReadLock();
    }
    return info;
}

In general, it works fine, but from time to time I get the exception. The problem is a subtlety of LINQ: this code returns an IEnumerable<Info>, which is still not enumerated after leaving the section protected by the lock. So, it can be changed by other threads before being enumerated, leading to the exception. The solution is to force the enumeration, for example with .ToList() as shown in the comment. In this way, the enumerable is already enumerated before leaving the protected section.

So, if using LINQ in a multi-threaded application, be aware to always materialize the queries before leaving the protected regions.

What is the fastest way to send 100,000 HTTP requests in Python?

For your case, threading will probably do the trick as you'll probably be spending most time waiting for a response. There are helpful modules like Queue in the standard library that might help.

I did a similar thing with parallel downloading of files before and it was good enough for me, but it wasn't on the scale you are talking about.

If your task was more CPU-bound, you might want to look at the multiprocessing module, which will allow you to utilize more CPUs/cores/threads (more processes that won't block each other since the locking is per process)

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

You could use your own subclass of ExecutorCompletionService to wrap taskExecutor, and your own implementation of BlockingQueue to get informed when each task completes and perform whatever callback or other action you desire when the number of completed tasks reaches your desired goal.

Making an asynchronous task in Flask

I would use Celery to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended).

app.py:

from flask import Flask
from celery import Celery

broker_url = 'amqp://guest@localhost'          # Broker URL for RabbitMQ task queue

app = Flask(__name__)    
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig')      # Your celery configurations in a celeryconfig.py

@celery.task(bind=True)
def some_long_task(self, x, y):
    # Do some long task
    ...

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    data = json.loads(request.data)
    text_list = data.get('text_list')
    final_file = audio_class.render_audio(data=text_list)
    some_long_task.delay(x, y)                 # Call your async task and pass whatever necessary variables
    return Response(
        mimetype='application/json',
        status=200
    )

Run your Flask app, and start another process to run your celery worker.

$ celery worker -A app.celery --loglevel=debug

I would also refer to Miguel Gringberg's write up for a more in depth guide to using Celery with Flask.

Using Java with Nvidia GPUs (CUDA)

From the research I have done, if you are targeting Nvidia GPUs and have decided to use CUDA over OpenCL, I found three ways to use the CUDA API in java.

  1. JCuda (or alternative)- http://www.jcuda.org/. This seems like the best solution for the problems I am working on. Many of libraries such as CUBLAS are available in JCuda. Kernels are still written in C though.
  2. JNI - JNI interfaces are not my favorite to write, but are very powerful and would allow you to do anything CUDA can do.
  3. JavaCPP - This basically lets you make a JNI interface in Java without writing C code directly. There is an example here: What is the easiest way to run working CUDA code in Java? of how to use this with CUDA thrust. To me, this seems like you might as well just write a JNI interface.

All of these answers basically are just ways of using C/C++ code in Java. You should ask yourself why you need to use Java and if you can't do it in C/C++ instead.

If you like Java and know how to use it and don't want to work with all the pointer management and what-not that comes with C/C++ then JCuda is probably the answer. On the other hand, the CUDA Thrust library and other libraries like it can be used to do a lot of the pointer management in C/C++ and maybe you should look at that.

If you like C/C++ and don't mind pointer management, but there are other constraints forcing you to use Java, then JNI might be the best approach. Though, if your JNI methods are just going be wrappers for kernel commands you might as well just use JCuda.

There are a few alternatives to JCuda such as Cuda4J and Root Beer, but those do not seem to be maintained. Whereas at the time of writing this JCuda supports CUDA 10.1. which is the most up-to-date CUDA SDK.

Additionally there are a few java libraries that use CUDA, such as deeplearning4j and Hadoop, that may be able to do what you are looking for without requiring you to write kernel code directly. I have not looked into them too much though.

How to stretch the background image to fill a div

Modern CSS3 (recommended for the future & probably the best solution)

.selector{
   background-size: cover;
   /* stretches background WITHOUT deformation so it would fill the background space,
      it may crop the image if the image's dimensions are in different ratio,
      than the element dimensions. */
}

Max. stretch without crop nor deformation (may not fill the background): background-size: contain;
Force absolute stretch (may cause deformation, but no crop): background-size: 100% 100%;

"Old" CSS "always working" way

Absolute positioning image as a first child of the (relative positioned) parent and stretching it to the parent size.

HTML

<div class="selector">
   <img src="path.extension" alt="alt text">
   <!-- some other content -->
</div>

Equivalent of CSS3 background-size: cover; :

To achieve this dynamically, you would have to use the opposite of contain method alternative (see below) and if you need to center the cropped image, you would need a JavaScript to do that dynamically - e.g. using jQuery:

$('.selector img').each(function(){ 
   $(this).css({ 
      "left": "50%", 
      "margin-left": "-"+( $(this).width()/2 )+"px", 
      "top": "50%", 
      "margin-top": "-"+( $(this).height()/2 )+"px" 
   }); 
});

Practical example:
css crop like example

Equivalent of CSS3 background-size: contain; :

This one can be a bit tricky - the dimension of your background that would overflow the parent will have CSS set to 100% the other one to auto. Practical example: css stretching background as image

.selector img{
   position: absolute; top:0; left: 0;
   width: 100%;
   height: auto;
   /* -- OR -- */
   /* width: auto; 
      height: 100%; */
}

Equivalent of CSS3 background-size: 100% 100%; :

.selector img{
   position: absolute; top:0; left: 0;
   width: 100%;
   height: 100%;
}

PS: To do the equivalents of cover/contain in the "old" way completely dynamically (so you will not have to care about overflows/ratios) you would have to use javascript to detect the ratios for you and set the dimensions as described...

Sonar properties files

You can define a Multi-module project structure, then you can set the configuration for sonar in one properties file in the root folder of your project, (Way #1)

How to delete an SVN project from SVN repository

In the case where you simply want to delete a project from the head revision, so that it no longer shows up in your repo when you run svn list file:///path/to/repo/ just run:

svn delete file:///path/to/repo/project 

However, if you need to delete all record of it in the repo, use another method.

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

If you use ES6 anon functions, it will conflict with $(this)

This works:

$('.dna-list').on('click', '.card', function(e) {
  console.log($(this));
});

This doesn't work:

$('.dna-list').on('click', '.card', (e) => {
  console.log($(this));
});

href overrides ng-click in Angular.js

Please check this

<a href="#" ng-click="logout(event)">Logout</a>

 $scope.logout = function(event)


 {
event.preventDefault();
alert("working..");
}

Where does Vagrant download its .box files to?

To change the Path, you can set a new Path to an Enviroment-Variable named: VAGRANT_HOME

export VAGRANT_HOME=my/new/path/goes/here/

Thats maybe nice if you want to have those vagrant-Images on another HDD.

More Information here in the Documentations: http://docs.vagrantup.com/v2/other/environmental-variables.html

Group query results by month and year in postgresql

There is another way to achieve the result using the date_part() function in postgres.

 SELECT date_part('month', txn_date) AS txn_month, date_part('year', txn_date) AS txn_year, sum(amount) as monthly_sum
     FROM yourtable
 GROUP BY date_part('month', txn_date)

Thanks

Import XXX cannot be resolved for Java SE standard classes

Right click on project - >BuildPath - >Configure BuildPath - >Libraries tab - >

Double click on JRE SYSTEM LIBRARY - >Then select alternate JRE

How to replace unicode characters in string with something else python?

  1. Decode the string to Unicode. Assuming it's UTF-8-encoded:

    str.decode("utf-8")
    
  2. Call the replace method and be sure to pass it a Unicode string as its first argument:

    str.decode("utf-8").replace(u"\u2022", "*")
    
  3. Encode back to UTF-8, if needed:

    str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
    

(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str shadows the built-in type str.)

How can I check whether a variable is defined in Node.js?

Determine if property is existing (but is not a falsy value):

if (typeof query !== 'undefined' && query !== null){
   doStuff();
}

Usually using

if (query){
   doStuff();
}

is sufficient. Please note that:

if (!query){
   doStuff();
}

doStuff() will execute even if query was an existing variable with falsy value (0, false, undefined or null)

Btw, there's a sexy coffeescript way of doing this:

if object?.property? then doStuff()

which compiles to:

if ((typeof object !== "undefined" && object !== null ? object.property : void 0) != null) 

{
  doStuff();
}

SameSite warning Chrome 77

If you are testing on localhost and you have no control of the response headers, you can disable it with a chrome flag.

Visit the url and disable it: chrome://flags/#same-site-by-default-cookies SameSite by default cookies screenshot

I need to disable it because Chrome Canary just started enforcing this rule as of approximately V 82.0.4078.2 and now it's not setting these cookies.

Note: I only turn this flag on in Chrome Canary that I use for development. It's best not to turn the flag on for everyday Chrome browsing for the same reasons that google is introducing it.

Ansible - read inventory hosts and variables to group_vars/all file

- name: host
   debug: msg="{{ item }}" 
   with_items:
    - "{{ groups['tests'] }}"

This piece of code will give the message:

'10.112.84.122'
'10.112.84.124'

as groups['tests'] basically return a list of unique ip addresses ['10.112.84.122','10.112.84.124'] whereas groups['tomcat'][0] returns 10.112.84.124.

The I/O operation has been aborted because of either a thread exit or an application request

In my case, the request was getting timed out. So all you need to do is to increase the time out while creating the HttpClient.

HttpClient client = new HttpClient();

client.Timeout = TimeSpan.FromMinutes(5);

How to get the browser viewport dimensions?

I looked and found a cross browser way:

_x000D_
_x000D_
function myFunction(){_x000D_
  if(window.innerWidth !== undefined && window.innerHeight !== undefined) { _x000D_
    var w = window.innerWidth;_x000D_
    var h = window.innerHeight;_x000D_
  } else {  _x000D_
    var w = document.documentElement.clientWidth;_x000D_
    var h = document.documentElement.clientHeight;_x000D_
  }_x000D_
  var txt = "Page size: width=" + w + ", height=" + h;_x000D_
  document.getElementById("demo").innerHTML = txt;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <body onresize="myFunction()" onload="myFunction()">_x000D_
   <p>_x000D_
    Try to resize the page._x000D_
   </p>_x000D_
   <p id="demo">_x000D_
    &nbsp;_x000D_
   </p>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to get just numeric part of CSS property with jQuery?

I use a simple jQuery plugin to return the numeric value of any single CSS property.

It applies parseFloat to the value returned by jQuery's default css method.

Plugin Definition:

$.fn.cssNum = function(){
  return parseFloat($.fn.css.apply(this,arguments));
}

Usage:

var element = $('.selector-class');
var numericWidth = element.cssNum('width') * 10 + 'px';
element.css('width', numericWidth);

How to find the .NET framework version of a Visual Studio project?

It depends which version of Visual Studio:

  • In 2002, all projects use .Net 1.0
  • In 2003, all projects use .Net 1.1
  • In 2005, all projects use .Net 2.0
  • In 2008, projects use .Net 2.0, 3.0, or 3.5; you can change the version in Project Properties
  • In 2010, projects use .Net 2.0, 3.0, 3.5, or 4.0; you can change the version in Project Properties
  • In 2012, projects use .Net 2.0, 3.0, 3.5, 4.0 or 4.5; you can change the version in Project Properties

Newer versions of Visual Studio support many versions of the .Net framework; check your project type and properties.

How can I style the border and title bar of a window in WPF?

I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:

  1. download the sample project here
  2. edit the generic.xaml file to customize the layout.
  3. enjoy :).

File loading by getClass().getResource()

getClass().getResource() uses the class loader to load the resource. This means that the resource must be in the classpath to be loaded.

When doing it with Eclipse, everything you put in the source folder is "compiled" by Eclipse:

  • .java files are compiled into .class files that go the the bin directory (by default)
  • other files are copied to the bin directory (respecting the package/folder hirearchy)

When launching the program with Eclipse, the bin directory is thus in the classpath, and since it contains the Test.properties file, this file can be loaded by the class loader, using getResource() or getResourceAsStream().

If it doesn't work from the command line, it's thus because the file is not in the classpath.

Note that you should NOT do

FileInputStream inputStream = new FileInputStream(new File(getClass().getResource(url).toURI()));

to load a resource. Because that can work only if the file is loaded from the file system. If you package your app into a jar file, or if you load the classes over a network, it won't work. To get an InputStream, just use

getClass().getResourceAsStream("Test.properties")

And finally, as the documentation indicates,

Foo.class.getResourceAsStream("Test.properties")

will load a Test.properties file located in the same package as the class Foo.

Foo.class.getResourceAsStream("/com/foo/bar/Test.properties")

will load a Test.properties file located in the package com.foo.bar.

How can I directly view blobs in MySQL Workbench

had the same problem, according to the MySQL documentation, you can select a Substring of a BLOB:

SELECT id, SUBSTRING(comment,1,2000) FROM t

HTH, glissi

Deleting objects from an ArrayList in Java

I'm good with Mnementh's recommentation.
Just one caveat though,

 ConcurrentModificationException

Mind that you don't have more than one thread running. This exception could appear if more than one thread executes, and the threads are not well synchronized.

Difference between timestamps with/without time zone in PostgreSQL

The differences are covered at the PostgreSQL documentation for date/time types. Yes, the treatment of TIME or TIMESTAMP differs between one WITH TIME ZONE or WITHOUT TIME ZONE. It doesn't affect how the values are stored; it affects how they are interpreted.

The effects of time zones on these data types is covered specifically in the docs. The difference arises from what the system can reasonably know about the value:

  • With a time zone as part of the value, the value can be rendered as a local time in the client.

  • Without a time zone as part of the value, the obvious default time zone is UTC, so it is rendered for that time zone.

The behaviour differs depending on at least three factors:

  • The timezone setting in the client.
  • The data type (i.e. WITH TIME ZONE or WITHOUT TIME ZONE) of the value.
  • Whether the value is specified with a particular time zone.

Here are examples covering the combinations of those factors:

foo=> SET TIMEZONE TO 'Japan';
SET
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP;
      timestamp      
---------------------
 2011-01-01 00:00:00
(1 row)

foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP WITH TIME ZONE;
      timestamptz       
------------------------
 2011-01-01 00:00:00+09
(1 row)

foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP;
      timestamp      
---------------------
 2011-01-01 00:00:00
(1 row)

foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP WITH TIME ZONE;
      timestamptz       
------------------------
 2011-01-01 06:00:00+09
(1 row)

foo=> SET TIMEZONE TO 'Australia/Melbourne';
SET
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP;
      timestamp      
---------------------
 2011-01-01 00:00:00
(1 row)

foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP WITH TIME ZONE;
      timestamptz       
------------------------
 2011-01-01 00:00:00+11
(1 row)

foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP;
      timestamp      
---------------------
 2011-01-01 00:00:00
(1 row)

foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP WITH TIME ZONE;
      timestamptz       
------------------------
 2011-01-01 08:00:00+11
(1 row)

Initializing C dynamic arrays

Instead of using

int * p;
p = {1,2,3};

we can use

int * p;
p =(int[3]){1,2,3};

DISTINCT for only one column

If you are using SQL Server 2005 or above use this:

SELECT *
  FROM (
                SELECT  ID, 
                        Email, 
                        ProductName, 
                        ProductModel,
                        ROW_NUMBER() OVER(PARTITION BY Email ORDER BY ID DESC) rn
                    FROM Products
              ) a
WHERE rn = 1

EDIT: Example using a where clause:

SELECT *
  FROM (
                SELECT  ID, 
                        Email, 
                        ProductName, 
                        ProductModel,
                        ROW_NUMBER() OVER(PARTITION BY Email ORDER BY ID DESC) rn
                    FROM Products
                   WHERE ProductModel = 2
                     AND ProductName LIKE 'CYBER%'

              ) a
WHERE rn = 1

How do you check current view controller class in Swift?

Try this

if self is MyViewController {        

}

ASP.NET MVC - Getting QueryString values

Query string parameters can be accepted simply by using an argument on the action - i.e.

public ActionResult Foo(string someValue, int someOtherValue) {...}

which will accept a query like .../someroute?someValue=abc&someOtherValue=123

Other than that, you can look at the request directly for more control.

How to Upload Image file in Retrofit 2

For those with an inputStream, you can upload inputStream using Multipart.

@Multipart
@POST("pictures")
suspend fun uploadPicture(
        @Part part: MultipartBody.Part
): NetworkPicture

Then in perhaps your repository class:

suspend fun upload(inputStream: InputStream) {
   val part = MultipartBody.Part.createFormData(
         "pic", "myPic", RequestBody.create(
              MediaType.parse("image/*"),
              inputStream.readBytes()
          )
   )
   uploadPicture(part)
}

To get an input stream you can do something like so.

In your fragment or activity, you need to create an image picker that returns an InputStream. The advantage of an InputStream is that it can be used for files on the cloud like google drive and dropbox.

Call pickImage() from a View.OnClickListener or onOptionsItemSelected.

    private fun pickImage() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        startActivityForResult(intent, PICK_PHOTO)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_PHOTO && resultCode == Activity.RESULT_OK) {
            try {
                data?.let {
                    val inputStream: InputStream? =
                        context?.contentResolver?.openInputStream(it.data!!)
                    inputStream?.let { stream ->
                        itemViewModel.uploadPicture(stream)
                    }
                }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }
        }
    }

    companion object {
        const val PICK_PHOTO = 1
    }

Concatenate a NumPy array to another NumPy array

In [1]: import numpy as np

In [2]: a = np.array([[1, 2, 3], [4, 5, 6]])

In [3]: b = np.array([[9, 8, 7], [6, 5, 4]])

In [4]: np.concatenate((a, b))
Out[4]: 
array([[1, 2, 3],
       [4, 5, 6],
       [9, 8, 7],
       [6, 5, 4]])

or this:

In [1]: a = np.array([1, 2, 3])

In [2]: b = np.array([4, 5, 6])

In [3]: np.vstack((a, b))
Out[3]: 
array([[1, 2, 3],
       [4, 5, 6]])

Homebrew refusing to link OpenSSL

The solution above from edwardthesecond worked for me too on Sierra

 brew install openssl
 cd /usr/local/include 
 ln -s ../opt/openssl/include/openssl 
 ./configure && make

Other steps I did before were:

  • installing openssl via brew

    brew install openssl
    
  • adding openssl to the path as suggested by homebrew

    brew info openssl
    echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
    

How to declare and initialize a static const array as a class member?

// in foo.h
class Foo {
    static const unsigned char* Msg;
};

// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;

How to take input in an array + PYTHON?

You want this - enter N and then take N number of elements.I am considering your input case is just like this

5
2 3 6 6 5

have this in this way in python 3.x (for python 2.x use raw_input() instead if input())

Python 3

n = int(input())
arr = input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

Python 2

n = int(raw_input())
arr = raw_input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

How can I convert the "arguments" object to an array in JavaScript?

Here's a clean and concise solution:

_x000D_
_x000D_
function argsToArray() {_x000D_
  return Object.values(arguments);_x000D_
}_x000D_
_x000D_
// example usage_x000D_
console.log(_x000D_
  argsToArray(1, 2, 3, 4, 5)_x000D_
  .map(arg => arg*11)_x000D_
);
_x000D_
_x000D_
_x000D_

Object.values( ) will return the values of an object as an array, and since arguments is an object, it will essentially convert arguments into an array, thus providing you with all of an array's helper functions such as map, forEach, filter, etc.

IIS7 Cache-Control

I use this

<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="500.00:00:00" />
</staticContent>

to cache static content for 500 days with public cache-control header.

Send data from activity to fragment in Android

just stumbled across this question, while most of the methods above will work. I just want to add that you can use the Event Bus Library, especially in scenarios where the component (Activity or Fragment) has not been created, its good for all sizes of android projects and many use cases. I have personally used it in several projects i have on playstore.

Import CSV file into SQL Server

You first need to create a table in your database in which you will be importing the CSV file. After the table is created, follow the steps below.

• Log into your database using SQL Server Management Studio

• Right click on your database and select Tasks -> Import Data...

• Click the Next > button

• For the Data Source, select Flat File Source. Then use the Browse button to select the CSV file. Spend some time configuring how you want the data to be imported before clicking on the Next > button.

• For the Destination, select the correct database provider (e.g. for SQL Server 2012, you can use SQL Server Native Client 11.0). Enter the Server name. Check the Use SQL Server Authentication radio button. Enter the User name, Password, and Database before clicking on the Next > button.

• On the Select Source Tables and Views window, you can Edit Mappings before clicking on the Next > button.

• Check the Run immediately check box and click on the Next > button.

• Click on the Finish button to run the package.

The above was found on this website (I have used it and tested):

C# Macro definitions in Preprocessor

You can use a C preprocessor (like mcpp) and rig it into your .csproj file. Then you chnage "build action" on your source file from Compile to Preprocess or whatever you call it. Just add BeforBuild to your .csproj like this:

  <Target Name="BeforeBuild" Inputs="@(Preprocess)" Outputs="@(Preprocess->'%(Filename)_P.cs')">
<Exec Command="..\Bin\cpp.exe @(Preprocess) -P -o %(RelativeDir)%(Filename)_P.cs" />
<CreateItem Include="@(Preprocess->'%(RelativeDir)%(Filename)_P.cs')">
  <Output TaskParameter="Include" ItemName="Compile" />
</CreateItem>

You may have to manually change Compile to Preprocess on at least one file (in a text editor) - then the "Preprocess" option should be available for selection in Visual Studio.

I know that macros are heavily overused and misused but removing them completely is equally bad if not worse. A classic example of macro usage would be NotifyPropertyChanged. Every programmer who had to rewrite this code by hand thousands of times knows how painful it is without macros.

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

The main point is this:

col-lg-* col-md-* col-xs-* col-sm define how many columns will there be in these different screen sizes.

Example: if you want there to be two columns in desktop screens and in phone screens you put two col-md-6 and two col-xs-6 classes in your columns.

If you want there to be two columns in desktop screens and only one column in phone screens (ie two rows stacked on top of each other) you put two col-md-6 and two col-xs-12 in your columns and because sum will be 24 they will auto stack on top of each other, or just leave xs style out.

Visual Studio Code: How to show line endings

AFAIK there is no way to visually see line endings in the editor space, but in the bottom-right corner of the window there is an indicator that says "CLRF" or "LF" which will let you set the line endings for a particular file. Clicking on the text will allow you to change the line endings as well.

enter image description here

How to center an image horizontally and align it to the bottom of the container?

This is tricky; the reason it's failing is that you can't position via margin or text-align while absolutely positioned.

If the image is alone in the div, then I recommend something like this:

.image_block {
    width: 175px;
    height: 175px;
    line-height: 175px;
    text-align: center;
    vertical-align: bottom;
}

You may need to stick the vertical-align call on the image instead; not really sure without testing it. Using vertical-align and line-height is going to treat you a lot better, though, than trying to mess around with absolute positioning.

Rails 4 - Strong Parameters - Nested Objects

I found this suggestion useful in my case:

  def product_params
    params.require(:product).permit(:name).tap do |whitelisted|
      whitelisted[:data] = params[:product][:data]
    end
  end

Check this link of Xavier's comment on github.

This approach whitelists the entire params[:measurement][:groundtruth] object.

Using the original questions attributes:

  def product_params
    params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
      whitelisted[:groundtruth] = params[:measurement][:groundtruth]
    end
  end

What is href="#" and why is it used?

As some of the other answers have pointed out, the a element requires an href attribute and the # is used as a placeholder, but it is also a historical artifact.

From Mozilla Developer Network:

href

This was the single required attribute for anchors defining a hypertext source link, but is no longer required in HTML5. Omitting this attribute creates a placeholder link. The href attribute indicates the link target, either a URL or a URL fragment. A URL fragment is a name preceded by a hash mark (#), which specifies an internal target location (an ID) within the current document.

Also, per the HTML5 spec:

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

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

Trigger a button click with JavaScript on the Enter key in a text box

In modern, undeprecated (without keyCode or onkeydown) Javascript:

<input onkeypress="if(event.key == 'Enter') {console.log('Test')}">

Java Minimum and Maximum values in Array

import java.util.*;
class Maxmin
{
    public static void main(String args[])
    {
        int[] arr = new int[10];
        Scanner in = new Scanner(System.in);
        int i, min=0, max=0;
        for(i=0; i<=arr.length; i++)
        {
            System.out.print("Enter any number: ");
            arr[i] = in.nextInt();          
        }
        min = arr[0];
        for(i=0; i<=9; i++)
        {
            if(arr[i] > max)
            {
                max = arr[i];
            }
            if(arr[i] < min)
            {
                min = arr[i];
            }
        }
        System.out.println("Maximum is: " + max);
        System.out.println("Minimum is: " + min);
    }
}

How to refresh activity after changing language (Locale) inside application

You can use recreate(); to restart your activity when Language change.

I am using following code to restart activity when language change:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Configuration config = getBaseContext().getResources().getConfiguration();

String lang = settings.getString("lang_list", "");

if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang)) {
      recreate();  //this is used for recreate activity
      Locale locale = new Locale(lang);
      Locale.setDefault(locale);
      config.locale = locale;
      getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}

How could I create a list in c++?

I take it that you know that C++ already has a linked list class, and you want to implement your own because you want to learn how to do it.

First, read Why do we use arrays instead of other data structures? , which contains a good answer of basic data-structures. Then think about how to model them in C++:

struct Node {
    int data;
    Node * next;
};

Basically that's all you need to implement a list! (a very simple one). Yet it has no abstractions, you have to link the items per hand:

Node a={1}, b={20, &a}, c={35, &b} d={42, &c};

Now, you have have a linked list of nodes, all allocated on the stack:

d -> c -> b -> a
42   35   20   1

Next step is to write a wrapper class List that points to the start node, and allows to add nodes as needed, keeping track of the head of the list (the following is very simplified):

class List {
    struct Node {
        int data;
        Node * next;
    };

    Node * head;

public:
    List() {
        head = NULL;
    }

    ~List() {
        while(head != NULL) {
            Node * n = head->next;
            delete head;
            head = n;
        }
    }

    void add(int value) {
        Node * n = new Node;
        n->data = value;
        n->next = head;
        head = n;
    }

    // ...
};

Next step is to make the List a template, so that you can stuff other values (not only integers).

If you are familiar with smart pointers, you can then replace the raw pointers used with smart pointers. Often i find people recommend smart pointers to starters. But in my opinion you should first understand why you need smart pointers, and then use them. But that requires that you need first understand raw pointers. Otherwise, you use some magic tool, without knowing why you need it.

Failed to decode downloaded font

I use .Net Framework 4.5/IIS 7

To fix it I put file Web.config in folder with font file.

Content of Web.config:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <authorization>
      <allow users="*" />
    </authorization>
  </system.web>
</configuration>

Print a string as hex bytes?

This can be done in following ways:

from __future__ import print_function
str = "Hello World !!"
for char in str:
    mm = int(char.encode('hex'), 16)
    print(hex(mm), sep=':', end=' ' )

The output of this will be in hex as follows:

0x48 0x65 0x6c 0x6c 0x6f 0x20 0x57 0x6f 0x72 0x6c 0x64 0x20 0x21 0x21

Alter a MySQL column to be AUTO_INCREMENT

Use the following queries:

ALTER TABLE YourTable DROP COLUMN IDCol

ALTER TABLE YourTable ADD IDCol INT IDENTITY(1,1)

Executing multi-line statements in the one-line command-line?

just use return and type it on the next line:

user@host:~$ python -c "import sys
> for r in range(10): print 'rob'"
rob
rob
...

How to change Maven local repository in eclipse

In general, these answer the question: How to change your user settings file? But the question I wanted answered was how to change my local maven repository location. The answer is that you have to edit settings.xml. If the file does not exist, you have to create it. You set or change the location of the file at Window > Preferences > Maven > User Settings. It's the User Settings entry at

Maven User Settings dialog

It's the second file input; the first with information in it.

If it's not clear, [redacted] should be replaced with the local file path to your .m2 folder.

If you click the "open file" link, it opens the settings.xml file for editing in Eclipse.

If you have no settings.xml file yet, the following will set the local repository to the Windows 10 default value for a user named mdfst13:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              https://maven.apache.org/xsd/settings-1.0.0.xsd">

  <localRepository>C:\Users\mdfst13\.m2\repository</localRepository>
</settings>

You should set this to a value appropriate to your system. I haven't tested it, but I suspect that in Linux, the default value would be /home/mdfst13/.m2/repository. And of course, you probably don't want to set it to the default value. If you are reading this, you probably want to set it to some other value. You could just delete it if you wanted the default.

Credit to this comment by @ejaenv for the name of the element in the settings file: <localRepository>. See Maven — Settings Reference for more information.

Credit to @Ajinkya's answer for specifying the location of the User Settings value in Eclipse Photon.

If you already have a settings.xml file, you should merge this into your existing file. I.e. <settings and <localRepository> should only appear once in the file, and you probably want to retain any settings already there. Or to say that another way, edit any existing local repository entry if it exists or just add that line to the file if it doesn't.

I had to restart Eclipse for it to load data into the new repository. Neither "Update Settings" nor "Reindex" was sufficient.

iPad WebApp Full Screen in Safari

This site has a working workaround, same effect, uses some javascript to set the first child div to total height of viewport. http://webapp-net.com/Demo/Index.html

How do I expire a PHP session after 30 minutes?

Is this to log the user out after a set time? Setting the session creation time (or an expiry time) when it is registered, and then checking that on each page load could handle that.

E.g.:

$_SESSION['example'] = array('foo' => 'bar', 'registered' => time());

// later

if ((time() - $_SESSION['example']['registered']) > (60 * 30)) {
    unset($_SESSION['example']);
}

Edit: I've got a feeling you mean something else though.

You can scrap sessions after a certain lifespan by using the session.gc_maxlifetime ini setting:

Edit: ini_set('session.gc_maxlifetime', 60*30);

ORA-01036: illegal variable name/number when running query through C#

I just spent several days checking parameters because I have to pass 60 to a stored procedure. It turns out that the one of the variable names (which I load into a list and pass to the Oracle Write method I created) had a space in the name at the end. When comparing to the variables in the stored procedure they were the same, but in the editor I used to compare them, I didnt notice the extra space. Drove me crazy for the last 4 days trying everything I could find, and changing even the .net Oracle driver. Just wanted to throw that out here so it can help someone else. We tend to concentrate on the characters and ignore the spaces. . .

Media query to detect if device is touchscreen

This solution will work until CSS4 is globally supported by all browsers. When that day comes just use CSS4. but until then, this works for current browsers.

browser-util.js

export const isMobile = {
  android: () => navigator.userAgent.match(/Android/i),
  blackberry: () => navigator.userAgent.match(/BlackBerry/i),
  ios: () => navigator.userAgent.match(/iPhone|iPad|iPod/i),
  opera: () => navigator.userAgent.match(/Opera Mini/i),
  windows: () => navigator.userAgent.match(/IEMobile/i),
  any: () => (isMobile.android() || isMobile.blackberry() || 
  isMobile.ios() || isMobile.opera() || isMobile.windows())
};

onload:

old way:

isMobile.any() ? document.getElementsByTagName("body")[0].className += 'is-touch' : null;

newer way:

isMobile.any() ? document.body.classList.add('is-touch') : null;

The above code will add the "is-touch" class to the body tag if the device has a touch screen. Now any location in your web application where you would have css for :hover you can call body:not(.is-touch) the_rest_of_my_css:hover

for example:

button:hover

becomes:

body:not(.is-touch) button:hover

This solution avoids using modernizer as the modernizer lib is a very big library. If all you're trying to do is detect touch screens, This will be best when the size of the final compiled source is a requirement.

Switch case in C# - a constant value is expected

This seems to work for me at least when i tried on visual studio 2017.

public static class Words
{
     public const string temp = "What";
     public const string temp2 = "the";
}
var i = "the";

switch (i)
{
  case Words.temp:
    break;
  case Words.temp2:
    break;
}

Passing multiple argument through CommandArgument of Button in Asp.net

Either store it in the gridview datakeys collection, or store it in a hidden field inside the same cell, or join the values together. That is the only way. You can't store two values in one link.

how to set background image in submit button?

You can try the following code:

background-image:url('url of your image') 10px 10px no-repeat

Difference between ApiController and Controller in ASP.NET MVC

I love the fact that ASP.NET Core's MVC6 merged the two patterns into one because I often need to support both worlds. While it's true that you can tweak any standard MVC Controller (and/or develop your own ActionResult classes) to act & behave just like an ApiController, it can be very hard to maintain and to test: on top of that, having Controllers methods returning ActionResult mixed with others returning raw/serialized/IHttpActionResult data can be very confusing from a developer perspective, expecially if you're not working alone and need to bring other developers to speed with that hybrid approach.

The best technique I've come so far to minimize that issue in ASP.NET non-Core web applications is to import (and properly configure) the Web API package into the MVC-based Web Application, so I can have the best of both worlds: Controllers for Views, ApiControllers for data.

In order to do that, you need to do the following:

  • Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
  • Add one or more ApiControllers to your /Controllers/ folder.
  • Add the following WebApiConfig.cs file to your /App_Config/ folder:

using System.Web.Http;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Finally, you'll need to register the above class to your Startup class (either Startup.cs or Global.asax.cs, depending if you're using OWIN Startup template or not).

Startup.cs

 public void Configuration(IAppBuilder app)
 {
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ConfigureAuth(app);
    // ...
}

Global.asax.cs

protected void Application_Start()
{
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    // ...
}

This approach - together with its pros and cons - is further explained in this post I wrote on my blog.

ADB Android Device Unauthorized

As the message have stated, you need to allow the adb access on your phone.

You need to first connect the phone to your PC with USB cables, then the authorization message will pop out on the screen. Tick remember your choice, then allow it.

IF your device doesnt shows any messages when connected to the PC.Just do this.

Remove /data/misc/adb/adb_key, reboot your phone and try connect again. The message should come up.

How to handle the new window in Selenium WebDriver using Java?

Set<String> windows = driver.getWindowHandles();
Iterator<String> itr = windows.iterator();

//patName will provide you parent window
String patName = itr.next();

//chldName will provide you child window
String chldName = itr.next();

//Switch to child window
driver.switchto().window(chldName);

//Do normal selenium code for performing action in child window

//To come back to parent window
driver.switchto().window(patName);

What is the purpose of class methods?

I think the most clear answer is AmanKow's one. It boils down to how u want to organize your code. You can write everything as module level functions which are wrapped in the namespace of the module i.e

module.py (file 1)
---------
def f1() : pass
def f2() : pass
def f3() : pass


usage.py (file 2)
--------
from module import *
f1()
f2()
f3()
def f4():pass 
def f5():pass

usage1.py (file 3)
-------------------
from usage import f4,f5
f4()
f5()

The above procedural code is not well organized, as you can see after only 3 modules it gets confusing, what is each method do ? You can use long descriptive names for functions(like in java) but still your code gets unmanageable very quick.

The object oriented way is to break down your code into manageable blocks i.e Classes & objects and functions can be associated with objects instances or with classes.

With class functions you gain another level of division in your code compared with module level functions. So you can group related functions within a class to make them more specific to a task that you assigned to that class. For example you can create a file utility class :

class FileUtil ():
  def copy(source,dest):pass
  def move(source,dest):pass
  def copyDir(source,dest):pass
  def moveDir(source,dest):pass

//usage
FileUtil.copy("1.txt","2.txt")
FileUtil.moveDir("dir1","dir2")

This way is more flexible and more maintainable, you group functions together and its more obvious to what each function do. Also you prevent name conflicts, for example the function copy may exist in another imported module(for example network copy) that you use in your code, so when you use the full name FileUtil.copy() you remove the problem and both copy functions can be used side by side.

What should be the values of GOPATH and GOROOT?

GOPATH is discussed here:

The GOPATH Environment Variable

GOPATH may be set to a colon-separated list of paths inside which Go code, package objects, and executables may be found.

Set a GOPATH to use goinstall to build and install your own code and external libraries outside of the Go tree (and to avoid writing Makefiles).

And GOROOT is discussed here:

$GOROOT The root of the Go tree, often $HOME/go. This defaults to the parent of the directory where all.bash is run. If you choose not to set $GOROOT, you must run gomake instead of make or gmake when developing Go programs using the conventional makefiles.

Radio button validation in javascript

Full validation example with javascript:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Radio button: full validation example with javascript</title>
        <script>
            function send() {
                var genders = document.getElementsByName("gender");
                if (genders[0].checked == true) {
                    alert("Your gender is male");
                } else if (genders[1].checked == true) {
                    alert("Your gender is female");
                } else {
                    // no checked
                    var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
                    document.getElementById('msg').innerHTML = msg;
                    return false;
                }
                return true;
            }

            function reset_msg() {
                document.getElementById('msg').innerHTML = '';
            }
        </script>
    </head>
    <body>
        <form action="" method="POST">
            <label>Gender:</label>
            <br />
            <input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
            <br />
            <input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
            <br />
            <div id="msg"></div>
            <input type="submit" value="send>>" onclick="return send();" />
        </form>
    </body>
</html>

Regards,

Fernando

SqlServer: Login failed for user

In my case I have configured as below in my springboot application.properties file then I am able to connect to the sqlserver database using service account:

url=jdbc:sqlserver://SERVER_NAME:PORT_NUMBER;databaseName=DATABASE_NAME;sendStringParametersAsUnicode=false;multiSubnetFailover=true;integratedSecurity=true
    jdbcUrl=${url}
    username=YourDomain\\$SERVICE-ACCOUNT-USER-NAME
    password=
    hikari.connection-timeout=60000
    hikari.maximum-pool-size=5
    driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

Show values from a MySQL database table inside a HTML table on a webpage

Surely a better solution would by dynamic so that it would work for any query without having to know the column names?

If so, try this (obviously the query should match your database):

// You'll need to put your db connection details in here.
$conn = new mysqli($server_hostname, $server_username, $server_password, $server_database);

// Run the query.
$result = $conn->query("SELECT * FROM table LIMIT 10");

// Get the result in to a more usable format.
$query = array();
while($query[] = mysqli_fetch_assoc($result));
array_pop($query);

// Output a dynamic table of the results with column headings.
echo '<table border="1">';
echo '<tr>';
foreach($query[0] as $key => $value) {
    echo '<td>';
    echo $key;
    echo '</td>';
}
echo '</tr>';
foreach($query as $row) {
    echo '<tr>';
    foreach($row as $column) {
        echo '<td>';
        echo $column;
        echo '</td>';
    }
    echo '</tr>';
}
echo '</table>';

Taken from here: https://www.antropy.co.uk/blog/handy-php-snippets/

Failed to connect to camera service

I know this question has been answered long time ago, but I would like to add a small thing.

To everyone having the same error, make sure to add this permission in you manifest file:

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

IMPORTANT to use the CAPITAL letters for CAMERA, as I had the permission with small letters and it didn't work.

Origin <origin> is not allowed by Access-Control-Allow-Origin

router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header("Access-Control-Allow-Headers", "*");
next();});

add this to your routes which you are calling from front-end. Ex- if you call for http://localhost:3000/users/register you must add this code fragment on your back-end .js file which this route lays.

How to play .wav files with java

Here is the most elegant form I could come up without using sun.*:

import java.io.*;
import javax.sound.sampled.*;

try {
    File yourFile;
    AudioInputStream stream;
    AudioFormat format;
    DataLine.Info info;
    Clip clip;

    stream = AudioSystem.getAudioInputStream(yourFile);
    format = stream.getFormat();
    info = new DataLine.Info(Clip.class, format);
    clip = (Clip) AudioSystem.getLine(info);
    clip.open(stream);
    clip.start();
}
catch (Exception e) {
    //whatevers
}

Oracle: how to set user password unexpire?

If you create a user using a profile like this:

CREATE PROFILE my_profile LIMIT
       PASSWORD_LIFE_TIME 30;
ALTER USER scott PROFILE my_profile;

then you can change the password lifetime like this:

ALTER PROFILE my_profile LIMIT
  PASSWORD_LIFE_TIME UNLIMITED;

I hope that helps.

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

This is what did it for me in .htaccess (it could be that you had a directive making all files load as MIME type text/html):

In .htaccess

AddType text/css .css

Remove duplicate values from JS array

function arrayDuplicateRemove(arr){
    var c = 0;
    var tempArray = [];
    console.log(arr);
    arr.sort();
    console.log(arr);
    for (var i = arr.length - 1; i >= 0; i--) {
        if(arr[i] != tempArray[c-1]){
            tempArray.push(arr[i])
            c++;
        }
    };
    console.log(tempArray);
    tempArray.sort();
    console.log(tempArray);
}

Differences between action and actionListener

actionListener

Use actionListener if you want have a hook before the real business action get executed, e.g. to log it, and/or to set an additional property (by <f:setPropertyActionListener>), and/or to have access to the component which invoked the action (which is available by ActionEvent argument). So, purely for preparing purposes before the real business action gets invoked.

The actionListener method has by default the following signature:

import javax.faces.event.ActionEvent;
// ...

public void actionListener(ActionEvent event) {
    // ...
}

And it's supposed to be declared as follows, without any method parentheses:

<h:commandXxx ... actionListener="#{bean.actionListener}" />

Note that you can't pass additional arguments by EL 2.2. You can however override the ActionEvent argument altogether by passing and specifying custom argument(s). The following examples are valid:

<h:commandXxx ... actionListener="#{bean.methodWithoutArguments()}" />
<h:commandXxx ... actionListener="#{bean.methodWithOneArgument(arg1)}" />
<h:commandXxx ... actionListener="#{bean.methodWithTwoArguments(arg1, arg2)}" />
public void methodWithoutArguments() {}
public void methodWithOneArgument(Object arg1) {}
public void methodWithTwoArguments(Object arg1, Object arg2) {}

Note the importance of the parentheses in the argumentless method expression. If they were absent, JSF would still expect a method with ActionEvent argument.

If you're on EL 2.2+, then you can declare multiple action listener methods via <f:actionListener binding>.

<h:commandXxx ... actionListener="#{bean.actionListener1}">
    <f:actionListener binding="#{bean.actionListener2()}" />
    <f:actionListener binding="#{bean.actionListener3()}" />
</h:commandXxx>
public void actionListener1(ActionEvent event) {}
public void actionListener2() {}
public void actionListener3() {}

Note the importance of the parentheses in the binding attribute. If they were absent, EL would confusingly throw a javax.el.PropertyNotFoundException: Property 'actionListener1' not found on type com.example.Bean, because the binding attribute is by default interpreted as a value expression, not as a method expression. Adding EL 2.2+ style parentheses transparently turns a value expression into a method expression. See also a.o. Why am I able to bind <f:actionListener> to an arbitrary method if it's not supported by JSF?


action

Use action if you want to execute a business action and if necessary handle navigation. The action method can (thus, not must) return a String which will be used as navigation case outcome (the target view). A return value of null or void will let it return to the same page and keep the current view scope alive. A return value of an empty string or the same view ID will also return to the same page, but recreate the view scope and thus destroy any currently active view scoped beans and, if applicable, recreate them.

The action method can be any valid MethodExpression, also the ones which uses EL 2.2 arguments such as below:

<h:commandXxx value="submit" action="#{bean.edit(item)}" />

With this method:

public void edit(Item item) {
    // ...
}

Note that when your action method solely returns a string, then you can also just specify exactly that string in the action attribute. Thus, this is totally clumsy:

<h:commandLink value="Go to next page" action="#{bean.goToNextpage}" />

With this senseless method returning a hardcoded string:

public String goToNextpage() {
    return "nextpage";
}

Instead, just put that hardcoded string directly in the attribute:

<h:commandLink value="Go to next page" action="nextpage" />

Please note that this in turn indicates a bad design: navigating by POST. This is not user nor SEO friendly. This all is explained in When should I use h:outputLink instead of h:commandLink? and is supposed to be solved as

<h:link value="Go to next page" outcome="nextpage" />

See also How to navigate in JSF? How to make URL reflect current page (and not previous one).


f:ajax listener

Since JSF 2.x there's a third way, the <f:ajax listener>.

<h:commandXxx ...>
    <f:ajax listener="#{bean.ajaxListener}" />
</h:commandXxx>

The ajaxListener method has by default the following signature:

import javax.faces.event.AjaxBehaviorEvent;
// ...

public void ajaxListener(AjaxBehaviorEvent event) {
    // ...
}

In Mojarra, the AjaxBehaviorEvent argument is optional, below works as good.

public void ajaxListener() {
    // ...
}

But in MyFaces, it would throw a MethodNotFoundException. Below works in both JSF implementations when you want to omit the argument.

<h:commandXxx ...>
    <f:ajax execute="@form" listener="#{bean.ajaxListener()}" render="@form" />
</h:commandXxx>

Ajax listeners are not really useful on command components. They are more useful on input and select components <h:inputXxx>/<h:selectXxx>. In command components, just stick to action and/or actionListener for clarity and better self-documenting code. Moreover, like actionListener, the f:ajax listener does not support returning a navigation outcome.

<h:commandXxx ... action="#{bean.action}">
    <f:ajax execute="@form" render="@form" />
</h:commandXxx>

For explanation on execute and render attributes, head to Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.


Invocation order

The actionListeners are always invoked before the action in the same order as they are been declared in the view and attached to the component. The f:ajax listener is always invoked before any action listener. So, the following example:

<h:commandButton value="submit" actionListener="#{bean.actionListener}" action="#{bean.action}">
    <f:actionListener type="com.example.ActionListenerType" />
    <f:actionListener binding="#{bean.actionListenerBinding()}" />
    <f:setPropertyActionListener target="#{bean.property}" value="some" />
    <f:ajax listener="#{bean.ajaxListener}" />
</h:commandButton>

Will invoke the methods in the following order:

  1. Bean#ajaxListener()
  2. Bean#actionListener()
  3. ActionListenerType#processAction()
  4. Bean#actionListenerBinding()
  5. Bean#setProperty()
  6. Bean#action()

Exception handling

The actionListener supports a special exception: AbortProcessingException. If this exception is thrown from an actionListener method, then JSF will skip any remaining action listeners and the action method and proceed to render response directly. You won't see an error/exception page, JSF will however log it. This will also implicitly be done whenever any other exception is being thrown from an actionListener. So, if you intend to block the page by an error page as result of a business exception, then you should definitely be performing the job in the action method.

If the sole reason to use an actionListener is to have a void method returning to the same page, then that's a bad one. The action methods can perfectly also return void, on the contrary to what some IDEs let you believe via EL validation. Note that the PrimeFaces showcase examples are littered with this kind of actionListeners over all place. This is indeed wrong. Don't use this as an excuse to also do that yourself.

In ajax requests, however, a special exception handler is needed. This is regardless of whether you use listener attribute of <f:ajax> or not. For explanation and an example, head to Exception handling in JSF ajax requests.

What is the most efficient way to check if a value exists in a NumPy array?

Adding to @HYRY's answer in1d seems to be fastest for numpy. This is using numpy 1.8 and python 2.7.6.

In this test in1d was fastest, however 10 in a look cleaner:

a = arange(0,99999,3)
%timeit 10 in a
%timeit in1d(a, 10)

10000 loops, best of 3: 150 µs per loop
10000 loops, best of 3: 61.9 µs per loop

Constructing a set is slower than calling in1d, but checking if the value exists is a bit faster:

s = set(range(0, 99999, 3))
%timeit 10 in s

10000000 loops, best of 3: 47 ns per loop

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

Can I use multiple versions of jQuery on the same page?

Taken from http://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page:

  • Original page loads his "jquery.versionX.js" -- $ and jQuery belong to versionX.
  • You call your "jquery.versionY.js" -- now $ and jQuery belong to versionY, plus _$ and _jQuery belong to versionX.
  • my_jQuery = jQuery.noConflict(true); -- now $ and jQuery belong to versionX, _$ and _jQuery are probably null, and my_jQuery is versionY.

Invalid use side-effecting operator Insert within a function

You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:

User-defined functions cannot be used to perform actions that modify the database state.

"Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).

You should be using a stored procedure, not a function.

How to change option menu icon in the action bar?

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
            android:id="@+id/logout"
            android:icon="@drawable/logout"
            android:title="Log Out"
            app:showAsAction="always"
        />
</menu>

This did the trick for me!

When to use references vs. pointers

Points to keep in mind:

  1. Pointers can be NULL, references cannot be NULL.

  2. References are easier to use, const can be used for a reference when we don't want to change value and just need a reference in a function.

  3. Pointer used with a * while references used with a &.

  4. Use pointers when pointer arithmetic operation are required.

  5. You can have pointers to a void type int a=5; void *p = &a; but cannot have a reference to a void type.

Pointer Vs Reference

void fun(int *a)
{
    cout<<a<<'\n'; // address of a = 0x7fff79f83eac
    cout<<*a<<'\n'; // value at a = 5
    cout<<a+1<<'\n'; // address of a increment by 4 bytes(int) = 0x7fff79f83eb0
    cout<<*(a+1)<<'\n'; // value here is by default = 0
}
void fun(int &a)
{
    cout<<a<<'\n'; // reference of original a passed a = 5
}
int a=5;
fun(&a);
fun(a);

Verdict when to use what

Pointer: For array, linklist, tree implementations and pointer arithmetic.

Reference: In function parameters and return types.

Array vs ArrayList in performance

When deciding to use Array or ArrayList, your first instinct really shouldn't be worrying about performance, though they do perform differently. You first concern should be whether or not you know the size of the Array before hand. If you don't, naturally you would go with an array list, just for functionality.

Check if specific input file is empty

if($_FILES['img_name']['name']!=""){
   echo "File Present";
}else{
  echo "Empty file";
}

Running Windows batch file commands asynchronously

You can use the start command to spawn background processes without launching new windows:

start /b foo.exe

The new process will not be interruptable with CTRL-C; you can kill it only with CTRL-BREAK (or by closing the window, or via Task Manager.)

How to show validation message below each textbox using jquery?

is only the matter of finding the dom where you want to insert the the text.

DEMO jsfiddle

$().text(); 

How to disable the parent form when a child form is active?

You can do that with the following:

Form3 formshow = new Form3();

formshow.ShowDialog();

How can I find the first and last date in a month using PHP?

You can use DateTimeImmutable::modify() :


$date = DateTimeImmutable::createFromFormat('Y-m-d', '2021-02-13');

var_dump($date->modify('first day of this month')->format('Y-m-d')); // string(10) "2021-02-01"
var_dump($date->modify('last day of this month')->format('Y-m-d')); // string(10) "2021-02-28"

Integration Testing POSTing an entire object to Spring MVC controller

Here is the method I made to transform recursively the fields of an object in a map ready to be used with a MockHttpServletRequestBuilder

public static void objectToPostParams(final String key, final Object value, final Map<String, String> map) throws IllegalAccessException {
    if ((value instanceof Number) || (value instanceof Enum) || (value instanceof String)) {
        map.put(key, value.toString());
    } else if (value instanceof Date) {
        map.put(key, new SimpleDateFormat("yyyy-MM-dd HH:mm").format((Date) value));
    } else if (value instanceof GenericDTO) {
        final Map<String, Object> fieldsMap = ReflectionUtils.getFieldsMap((GenericDTO) value);
        for (final Entry<String, Object> entry : fieldsMap.entrySet()) {
            final StringBuilder sb = new StringBuilder();
            if (!GenericValidator.isEmpty(key)) {
                sb.append(key).append('.');
            }
            sb.append(entry.getKey());
            objectToPostParams(sb.toString(), entry.getValue(), map);
        }
    } else if (value instanceof List) {
        for (int i = 0; i < ((List) value).size(); i++) {
            objectToPostParams(key + '[' + i + ']', ((List) value).get(i), map);
        }
    }
}

GenericDTO is a simple class extending Serializable

public interface GenericDTO extends Serializable {}

and here is the ReflectionUtils class

public final class ReflectionUtils {
    public static List<Field> getAllFields(final List<Field> fields, final Class<?> type) {
        if (type.getSuperclass() != null) {
            getAllFields(fields, type.getSuperclass());
        }
        // if a field is overwritten in the child class, the one in the parent is removed
        fields.addAll(Arrays.asList(type.getDeclaredFields()).stream().map(field -> {
            final Iterator<Field> iterator = fields.iterator();
            while(iterator.hasNext()){
                final Field fieldTmp = iterator.next();
                if (fieldTmp.getName().equals(field.getName())) {
                    iterator.remove();
                    break;
                }
            }
            return field;
        }).collect(Collectors.toList()));
        return fields;
    }

    public static Map<String, Object> getFieldsMap(final GenericDTO genericDTO) throws IllegalAccessException {
        final Map<String, Object> map = new HashMap<>();
        final List<Field> fields = new ArrayList<>();
        getAllFields(fields, genericDTO.getClass());
        for (final Field field : fields) {
            final boolean isFieldAccessible = field.isAccessible();
            field.setAccessible(true);
            map.put(field.getName(), field.get(genericDTO));
            field.setAccessible(isFieldAccessible);
        }
        return map;
    }
}

You can use it like

final MockHttpServletRequestBuilder post = post("/");
final Map<String, String> map = new TreeMap<>();
objectToPostParams("", genericDTO, map);
for (final Entry<String, String> entry : map.entrySet()) {
    post.param(entry.getKey(), entry.getValue());
}

I didn't tested it extensively, but it seems to work.

Convert character to Date in R

The easiest way is to use lubridate:

library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)

This function automatically returns objects of class POSIXct and will work with either factors or characters.

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

If after following the steps as described by Surjeet you still can't connect, try turning your computer's Wi-Fi off and on again. This worked for me.

Also, be sure to trust the developer certificate on the iOS device (Settings - General - Profiles & Device Management - Developer App).

SQL query to get most recent row for each instance of a given key

Both of the above answers assume that you only have one row for each user and time_stamp. Depending on the application and the granularity of your time_stamp this may not be a valid assumption. If you need to deal with ties of time_stamp for a given user, you'd need to extend one of the answers given above.

To write this in one query would require another nested sub-query - things will start getting more messy and performance may suffer.

I would have loved to have added this as a comment but I don't yet have 50 reputation so sorry for posting as a new answer!

Google Maps V3 - How to calculate the zoom level for a given bounds

None of the highly upvoted answers worked for me. They threw various undefined errors and ended up calculating inf/nan for angles. I suspect perhaps the behavior of LatLngBounds has changed over time. In any case, I found this code to work for my needs, perhaps it can help someone:

function latRad(lat) {
  var sin = Math.sin(lat * Math.PI / 180);
  var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
  return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
}

function getZoom(lat_a, lng_a, lat_b, lng_b) {

      let latDif = Math.abs(latRad(lat_a) - latRad(lat_b))
      let lngDif = Math.abs(lng_a - lng_b)

      let latFrac = latDif / Math.PI 
      let lngFrac = lngDif / 360 

      let lngZoom = Math.log(1/latFrac) / Math.log(2)
      let latZoom = Math.log(1/lngFrac) / Math.log(2)

      return Math.min(lngZoom, latZoom)

}

How do I know which version of Javascript I'm using?

In chrome you can find easily not only your JS version but also a flash version. All you need is to type chrome://version/ in a command line and you will get something like this:

enter image description here

ngModel cannot be used to register form controls with a parent formGroup directive

I just got this error because I did not enclose all my form controls within a div with a formGroup attribute.

For example, this will throw an error

<div [formGroup]='formGroup'>
</div>
<input formControlName='userName' />

This can be quite easy to miss if its a particularly long form.

Why is "except: pass" a bad programming practice?

Why is “except: pass” a bad programming practice?

Why is this bad?

try:
    something
except:
    pass

This catches every possible exception, including GeneratorExit, KeyboardInterrupt, and SystemExit - which are exceptions you probably don't intend to catch. It's the same as catching BaseException.

try:
    something
except BaseException:
    pass

Older versions of the documentation say:

Since every error in Python raises an exception, using except: can make many programming errors look like runtime problems, which hinders the debugging process.

Python Exception Hierarchy

If you catch a parent exception class, you also catch all of their child classes. It is much more elegant to only catch the exceptions you are prepared to handle.

Here's the Python 3 exception hierarchy - do you really want to catch 'em all?:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
           +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Don't Do this

If you're using this form of exception handling:

try:
    something
except: # don't just do a bare except!
    pass

Then you won't be able to interrupt your something block with Ctrl-C. Your program will overlook every possible Exception inside the try code block.

Here's another example that will have the same undesirable behavior:

except BaseException as e: # don't do this either - same as bare!
    logging.info(e)

Instead, try to only catch the specific exception you know you're looking for. For example, if you know you might get a value-error on a conversion:

try:
    foo = operation_that_includes_int(foo)
except ValueError as e:
    if fatal_condition(): # You can raise the exception if it's bad,
        logging.info(e)   # but if it's fatal every time,
        raise             # you probably should just not catch it.
    else:                 # Only catch exceptions you are prepared to handle.
        foo = 0           # Here we simply assign foo to 0 and continue. 

Further Explanation with another example

You might be doing it because you've been web-scraping and been getting say, a UnicodeError, but because you've used the broadest Exception catching, your code, which may have other fundamental flaws, will attempt to run to completion, wasting bandwidth, processing time, wear and tear on your equipment, running out of memory, collecting garbage data, etc.

If other people are asking you to complete so that they can rely on your code, I understand feeling compelled to just handle everything. But if you're willing to fail noisily as you develop, you will have the opportunity to correct problems that might only pop up intermittently, but that would be long term costly bugs.

With more precise error handling, you code can be more robust.

C - function inside struct

This will only work in C++. Functions in structs are not a feature of C.

Same goes for your client.AddClient(); call ... this is a call for a member function, which is object oriented programming, i.e. C++.

Convert your source to a .cpp file and make sure you are compiling accordingly.

If you need to stick to C, the code below is (sort of) the equivalent:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;

};


pno AddClient(pno *pclient) 
{
    /* code */
}


int main()
{

    client_t client;

    //code ..

    AddClient(client);

}

What is the meaning of @_ in Perl?

Also if a function returns an array, but the function is called without assigning its returned data to any variable like below. Here split() is called, but it is not assigned to any variable. We can access its returned data later through @_:

$str = "Mr.Bond|Chewbaaka|Spider-Man";
split(/\|/, $str);

print @_[0]; # 'Mr.Bond'

This will split the string $str and set the array @_.

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Cross browser JavaScript (not jQuery...) scroll to top animation

This is a cross browser approach based on answers above

function scrollTo(to, duration) {
    if (duration < 0) return;
    var scrollTop = document.body.scrollTop + document.documentElement.scrollTop;
    var difference = to - scrollTop;
    var perTick = difference / duration * 10;

    setTimeout(function() {
      scrollTop = scrollTop + perTick;
      document.body.scrollTop = scrollTop;
      document.documentElement.scrollTop = scrollTop;
      if (scrollTop === to) return;
      scrollTo(to, duration - 10);
    }, 10);
  }

PHP to write Tab Characters inside a file?

Use \t and enclose the string with double-quotes:

$chunk = "abc\tdef\tghi";

What is class="mb-0" in Bootstrap 4?

m - sets margin

p - sets padding

t - sets margin-top or padding-top

b - sets margin-bottom or padding-bottom

l - sets margin-left or padding-left

r - sets margin-right or padding-right

x - sets both padding-left and padding-right or margin-left and margin-right

y - sets both padding-top and padding-bottom or margin-top and margin-bottom

blank - sets a margin or padding on all 4 sides of the element

0 - sets margin or padding to 0

1 - sets margin or padding to .25rem (4px if font-size is 16px)

2 - sets margin or padding to .5rem (8px if font-size is 16px)

3 - sets margin or padding to 1rem (16px if font-size is 16px)

4 - sets margin or padding to 1.5rem (24px if font-size is 16px)

5 - sets margin or padding to 3rem (48px if font-size is 16px)

auto - sets margin to auto

How to reset Jenkins security settings from the command line?

Jenkins over KUBENETES and Docker

In case of Jenkins over a container managed by a Kubernetes POD is a bit more complex since: kubectl exec PODID --namespace=jenkins -it -- /bin/bash will you allow to access directly to the container running Jenkins, but you will not have root access, sudo, vi and many commands are not available and therefore a workaround is needed.

Use kubectl describe pod [...] to find the node running your Pod and the container ID (docker://...)

  • SSH into the node
  • run docker exec -ti -u root -- /bin/bash to access the container with Root privileges
  • apt-get update
  • sudo apt-get install vim

The second difference is that the Jenkins configuration file are placed in a different path that corresponds to the mounting point of the persistent volume, i.e. /var/jenkins_home, this location might change in the future, check it running df.

Then disable security - change true to false in /var/jenkins_home/jenkins/config.xml file.

<useSecurity>false</useSecurity>

Now it is enough to restart the Jenkins, action that will cause the container and the Pod to die, it will created again in some seconds with the configuration updated (and all the chance like vi, update erased) thanks to the persistent volume.

The whole solution has been tested on Google Kubernetes Engine. UPDATE Notice that you can as well run ps -aux the password in plain text is shown even without root access.

jenkins@jenkins-87c47bbb8-g87nw:/$ps -aux
[...]
jenkins [..] -jar /usr/share/jenkins/jenkins.war --argumentsRealm.passwd.jenkins=password --argumentsRealm.roles.jenkins=admin
[...]

Change working directory in my current shell context when running Node script

There is no built-in method for Node to change the CWD of the underlying shell running the Node process.

You can change the current working directory of the Node process through the command process.chdir().

var process = require('process');
process.chdir('../');

When the Node process exists, you will find yourself back in the CWD you started the process in.

DLL load failed error when importing cv2

Under Winpython : the Winpython-64bit-.../python_.../DLLs directory the file cv2.pyd should be renamed to _cv2.pyd

Validate email address textbox using JavaScript

Assuming your regular expression is correct:

inside your script tags

function validateEmail(emailField){
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(emailField.value) == false) 
        {
            alert('Invalid Email Address');
            return false;
        }

        return true;

}

in your textfield:

<input type="text" onblur="validateEmail(this);" />

Converting a date in MySQL from string field

Yes, there's str_to_date

mysql> select str_to_date("03/02/2009","%d/%m/%Y");
+--------------------------------------+
| str_to_date("03/02/2009","%d/%m/%Y") |
+--------------------------------------+
| 2009-02-03                           |
+--------------------------------------+
1 row in set (0.00 sec)

git push rejected: error: failed to push some refs

for me following worked, just ran these command one by one

git pull -r origin master

git push -f origin your_branch

javascript code to check special characters

Did you write return true somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.

function isValid(str) {
    var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";

    for (var i = 0; i < str.length; i++) {
       if (iChars.indexOf(str.charAt(i)) != -1) {
           alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
           return false;
       }
    }
    return true;
}

I tried this in my chrome console and it worked well.

JavaScript Chart.js - Custom data formatting to display on tooltip

This is what my final options section looks like for chart.js version 2.8.0.

        options: {
        legend: {
            display: false //Have this or else legend will display as undefined
        },
        scales: {
            //This will show money for y-axis labels with format of $xx.xx
            yAxes: [{
              ticks: {
                beginAtZero: true,
                callback: function(value) {
                    return (new Intl.NumberFormat('en-US', {
                        style: 'currency',
                        currency: 'USD',
                    })).format(value);
                }
              }
            }]
        },
        //This will show money in tooltip with format of $xx.xx
        tooltips: {
            callbacks: {
                label: function (tooltipItem) {
                    return (new Intl.NumberFormat('en-US', {
                        style: 'currency',
                        currency: 'USD',
                    })).format(tooltipItem.value);
                }
            }
        }
    }

I wanted to show money values for both the y-axis and the tooltip values that show up when you hover over them. This works to show $49.99 and values with zero cents (ex: $50.00)

"CSV file does not exist" for a filename with embedded quotes

Sometimes we ignore a little bit issue which is not a Python or IDE fault its logical error We assumed a file .csv which is not a .csv file its a Excell Worksheet file have a look


Tiktok file which is worksheet file not a CSV file Shown in Green border


When you try to open that file using Import compiler will through the error have a look enter image description here

To Resolve the issue

open your Target file into Microsoft Excell and save that file in .csv format it is important to note that Encoding is important because it will help you to open the file when you try to open it with

with open('YourTargetFile.csv','r',encoding='UTF-8') as file:

enter image description here

So you are set to go now Try to open your file as this

import csv
with open('plain.csv','r',encoding='UTF-8') as file:
load = csv.reader(file)
for line in load:
    print(line)

Here is the Output Plain.csv File Running

setTimeout in React Native

There looks to be an issue when the time of the phone/emulator is different to the one of the server (where react-native packager is running). In my case there was a 1 minute difference between the time of the phone and the computer. After synchronizing them (didn't do anything fancy, the phone was set on manual time, and I just set it to use the network(sim) provided time), everything worked fine. This github issue helped me find the problem.

Pass values of checkBox to controller action in asp.net mvc4

If a checkbox is checked, then the postback values will contain a key-value pair of the form [InputName]=[InputValue]

If a checkbox is not checked, then the posted form contains no reference to the checkbox at all.

Knowing this, the following will work:

In the markup code:

 <input id="responsable" name="checkResp" value="true" type="checkbox" />

And your action method signature:

public ActionResult Index( string responsables, bool checkResp = false)

This will work because when the checkbox is checked, the postback will contain checkResp=true, and if the checkbox is not checked the parameter will default to false.

Error: Local workspace file ('angular.json') could not be found

For me, the issue was that I have an angular project folder inside a rails project folder, and I ran all the angular update commands in the rails parent folder rather than the actual angular folder.

AutoComplete TextBox in WPF

I'm surprised why no one suggested to use the WinForms Textbox.

XAML:

     <WindowsFormsHost  Margin="10" Width="70">
        <wf:TextBox x:Name="textbox1"/>
     </WindowsFormsHost>

Also don't forget the Winforms Namespace:

xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

C#:

     AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection(){"String 1", "String 2", "etc..."};
   
     textbox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
     textbox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
     textbox1.AutoCompleteCustomSource = stringCollection;

With Autocomplete, you need to do it in the Code behind, because for some reasons, others might can explain, it throws an exception.

How to restore the permissions of files and directories within git if they have been modified?

Git keeps track of filepermission and exposes permission changes when creating patches using git diff -p. So all we need is:

  1. create a reverse patch
  2. include only the permission changes
  3. apply the patch to our working copy

As a one-liner:

git diff -p -R --no-ext-diff --no-color \
    | grep -E "^(diff|(old|new) mode)" --color=never  \
    | git apply

you can also add it as an alias to your git config...

git config --global --add alias.permission-reset '!git diff -p -R --no-ext-diff --no-color | grep -E "^(diff|(old|new) mode)" --color=never | git apply'

...and you can invoke it via:

git permission-reset

Note, if you shell is bash, make sure to use ' instead of " quotes around the !git, otherwise it gets substituted with the last git command you ran.

Thx to @Mixologic for pointing out that by simply using -R on git diff, the cumbersome sed command is no longer required.

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

  1. Set npm registry globally

    use the below command to modify the .npmrc config file for the logged in user

    npm config set registry <registry url>

    Example: npm config set registry https://registry.npmjs.org/


  1. Set npm registry Scope

    Scopes allow grouping of related packages together. Scoped packages will be installed in a sub-folder under node_modules folder.

    Example: node_modules/@my-org/packagaename

    To set the scope registry use: npm config set @my-org:registry http://example.reg-org.com

    To install packages using scope use: npm install @my-org/mypackage

    whenever you install any packages from scope @my-org npm will search in the registry setting linked to scope @my-org for the registry url.


  1. Set npm registry locally for a project

    To modify the npm registry only for the current project. create a file inside the root folder of the project as .npmrc

    Add the below contents in the file

   registry = 'https://registry.npmjs.org/'

MemoryStream - Cannot access a closed Stream

This is because the StreamReader closes the underlying stream automatically when being disposed of. The using statement does this automatically.

However, the StreamWriter you're using is still trying to work on the stream (also, the using statement for the writer is now trying to dispose of the StreamWriter, which is then trying to close the stream).

The best way to fix this is: don't use using and don't dispose of the StreamReader and StreamWriter. See this question.

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);
    var sr = new StreamReader(ms);

    sw.WriteLine("data");
    sw.WriteLine("data 2");
    ms.Position = 0;

    Console.WriteLine(sr.ReadToEnd());                        
}

If you feel bad about sw and sr being garbage-collected without being disposed of in your code (as recommended), you could do something like that:

StreamWriter sw = null;
StreamReader sr = null;

try
{
    using (var ms = new MemoryStream())
    {
        sw = new StreamWriter(ms);
        sr = new StreamReader(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;

        Console.WriteLine(sr.ReadToEnd());                        
    }
}
finally
{
    if (sw != null) sw.Dispose();
    if (sr != null) sr.Dispose();
}

Correct way to delete cookies server-side

Setting "expires" to a past date is the standard way to delete a cookie.

Your problem is probably because the date format is not conventional. IE probably expects GMT only.

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

The error is try to fix a Youtube error.

The solution to avoid your Javascript-Console-Error complex is to accept that Youtube (and also other webpages) can have Javascript errors that you can't fix.

That is all.

How to uninstall Jenkins?

run this on Terminal:

sh "/Library/Application Support/Jenkins/Uninstall.command"

What is the difference between the dot (.) operator and -> in C++?

The target. dot works on objects; arrow works on pointers to objects.

std::string str("foo");
std::string * pstr = new std::string("foo");

str.size ();
pstr->size ();

How to save a PNG image server-side, from a base64 data string

It's simple :

Let's imagine that you are trying to upload a file within js framework, ajax request or mobile application (Client side)

  1. Firstly you send a data attribute that contains a base64 encoded string.
  2. In the server side you have to decode it and save it in a local project folder.

Here how to do it using PHP

<?php 

$base64String = "kfezyufgzefhzefjizjfzfzefzefhuze"; // I put a static base64 string, you can implement you special code to retrieve the data received via the request.

$filePath = "/MyProject/public/uploads/img/test.png";

file_put_contents($filePath, base64_decode($base64String));

?>

Xcode couldn't find any provisioning profiles matching

I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem

How to use double or single brackets, parentheses, curly braces

Truncate the contents of a variable

$ var="abcde"; echo ${var%d*}
abc

Make substitutions similar to sed

$ var="abcde"; echo ${var/de/12}
abc12

Use a default value

$ default="hello"; unset var; echo ${var:-$default}
hello

How can I delay a :hover effect in CSS?

You can use transitions to delay the :hover effect you want, if the effect is CSS-based.

For example

div{
    transition: 0s background-color;
}

div:hover{
    background-color:red;    
    transition-delay:1s;
}

this will delay applying the the hover effects (background-color in this case) for one second.


Demo of delay on both hover on and off:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
    transition-delay:1s;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_

Demo of delay only on hover on:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;    _x000D_
    transition-delay:1s;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_


Vendor Specific Extentions for Transitions and W3C CSS3 transitions

conflicting types for 'outchar'

It's because you haven't declared outchar before you use it. That means that the compiler will assume it's a function returning an int and taking an undefined number of undefined arguments.

You need to add a prototype pf the function before you use it:

void outchar(char);  /* Prototype (declaration) of a function to be called */  int main(void) {     ... }  void outchar(char ch) {     ... } 

Note the declaration of the main function differs from your code as well. It's actually a part of the official C specification, it must return an int and must take either a void argument or an int and a char** argument.

AngularJS : Why ng-bind is better than {{}} in angular?

This is because with {{}} the angular compiler considers both the text node and it's parent as there is a possibility of merging of 2 {{}} nodes. Hence there are additional linkers that add to the load time. Of course for a few such occurrences the difference is immaterial, however when you are using this inside a repeater of large number of items, it will cause an impact in slower runtime environment.

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

Delaying function in swift

 NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHere", userInfo: nil, repeats: false)

This would call the function functionHere() with a 3 seconds delay

AngularJS: Service vs provider vs factory

Just to clarify things, from the AngularJS source, you can see a service just calls the factory function which in turn calls the provider function:

function factory(name, factoryFn) { 
    return provider(name, { $get: factoryFn }); 
}

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
      return $injector.instantiate(constructor);
    }]);
}

How to clamp an integer to some range?

Avoid writing functions for such small tasks, unless you apply them often, as it will clutter up your code.

for individual values:

min(clamp_max, max(clamp_min, value))

for lists of values:

map(lambda x: min(clamp_max, max(clamp_min, x)), values)

assigning column names to a pandas series

You can also use the .to_frame() method.

If it is a Series, I assume 'Gene' is already the index, and will remain the index after converting it to a DataFrame. The name argument of .to_frame() will name the column.

x = x.to_frame('count')

If you want them both as columns, you can reset the index:

x = x.to_frame('count').reset_index()

syntax error: unexpected token <

This error can also arise from a JSON AJAX call to a PHP script that has an error in its code. Servers are often set up to return PHP error information formatted with html markup. This response is interpreted as invalid JSON, resulting in the "unexpected token <" AJAX error.

To view the PHP error using Chrome, go to the Network panel in the web inspector, click the PHP file listed on the left side, and click on the Response tab.

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Simple logical operators in Bash

very close

if [[ $varA -eq 1 ]] && [[ $varB == 't1' || $varC == 't2' ]]; 
  then 
    scale=0.05
  fi

should work.

breaking it down

[[ $varA -eq 1 ]] 

is an integer comparison where as

$varB == 't1'

is a string comparison. otherwise, I am just grouping the comparisons correctly.

Double square brackets delimit a Conditional Expression. And, I find the following to be a good reading on the subject: "(IBM) Demystify test, [, [[, ((, and if-then-else"

How to know what the 'errno' means?

There's a few useful functions for dealing with errnos. (Just to make it clear, these are built-in to libc -- I'm just providing sample implementations because some people find reading code clearer than reading English.)

#include <string.h>
char *strerror(int errnum);

/* you can think of it as being implemented like this: */
static char strerror_buf[1024];
const char *sys_errlist[] = {
    [EPERM]  = "Operation not permitted",
    [ENOENT] = "No such file or directory",
    [ESRCH]  = "No such process",
    [EINTR]  = "Interrupted system call",
    [EIO]    = "I/O error",
    [ENXIO]  = "No such device or address",
    [E2BIG]  = "Argument list too long",
    /* etc. */
};
int sys_nerr = sizeof(sys_errlist) / sizeof(char *);
char *strerror(int errnum) {
    if (0 <= errnum && errnum < sys_nerr && sys_errlist[errnum])
        strcpy(strerror_buf, sys_errlist[errnum]);
    else
        sprintf(strerror_buf, "Unknown error %d", errnum);
    return strerror_buf;
}

strerror returns a string describing the error number you've passed to it. Caution, this is not thread- or interrupt-safe; it is free to rewrite the string and return the same pointer on the next invocation. Use strerror_r if you need to worry about that.

#include <stdio.h>
void perror(const char *s);

/* you can think of it as being implemented like this: */
void perror(const char *s) {
    fprintf(stderr, "%s: %s\n", s, strerror(errno));
}

perror prints out the message you give it, plus a string describing the current errno, to standard error.

Return only string message from Spring MVC 3 Controller

For outputing String as text/plain use:

@RequestMapping(value="/foo", method=RequestMethod.GET, produces="text/plain")
@ResponseBody
public String foo() {
    return "bar";
}

How to set environment variable or system property in spring tests?

One can also use a test ApplicationContextInitializer to initialize a system property:

public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext)
    {
        System.setProperty("myproperty", "value");
    }
}

and then configure it on the test class in addition to the Spring context config file locations:

@ContextConfiguration(initializers = TestApplicationContextInitializer.class, locations = "classpath:whereever/context.xml", ...)
@RunWith(SpringJUnit4ClassRunner.class)
public class SomeTest
{
...
}

This way code duplication can be avoided if a certain system property should be set for all the unit tests.

bootstrap datepicker today as default

This question is about bootstrap date picker. But all of the above answers are for the jquery date picker. For Bootstrap datepicker, you just need to provide the defaut date in the value of the input element. Like this.

<input class="form-control datepicker" value=" <?= date("Y-m-d") ?>">

loop through json array jquery

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data);
$.each(data, function(i, item) {
    alert(item);
});

How to make ConstraintLayout work with percentage values?

Using Guidelines you can change the positioning to be percentage based

<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5"/>

You can also use this way

android:layout_width="0dp"
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent="0.4"

C# LINQ select from list

Execute the GetEventIdsByEventDate() method and save the results in a variable, and then you can use the .Contains() method

HTML - how can I show tooltip ONLY when ellipsis is activated

Here are two other pure CSS solutions:

  1. Show the truncated text in place:

_x000D_
_x000D_
.overflow {_x000D_
  overflow: hidden;_x000D_
  -ms-text-overflow: ellipsis;_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
}_x000D_
_x000D_
.overflow:hover {_x000D_
  overflow: visible;_x000D_
}_x000D_
_x000D_
.overflow:hover span {_x000D_
  position: relative;_x000D_
  background-color: white;_x000D_
_x000D_
  box-shadow: 0 0 4px 0 black;_x000D_
  border-radius: 1px;_x000D_
}
_x000D_
<div>_x000D_
  <span class="overflow" style="float: left; width: 50px">_x000D_
    <span>Long text that might overflow.</span>_x000D_
  </span>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad recusandae perspiciatis accusantium quas aut explicabo ab. Doloremque quam eos, alias dolore, iusto pariatur earum, ullam, quidem dolores deleniti perspiciatis omnis._x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. Show an arbitrary "tooltip":

_x000D_
_x000D_
.wrap {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.overflow {_x000D_
  white-space: nowrap; _x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  _x000D_
  pointer-events:none;_x000D_
}_x000D_
_x000D_
.overflow:after {_x000D_
  content:"";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  width: 20px;_x000D_
  height: 15px;_x000D_
  z-index: 1;_x000D_
  border: 1px solid red; /* for visualization only */_x000D_
  pointer-events:initial;_x000D_
_x000D_
}_x000D_
_x000D_
.overflow:hover:after{_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.tooltip {_x000D_
  /* visibility: hidden; */_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 10;_x000D_
  left: 0;_x000D_
  background-color: #fff;_x000D_
  padding: 10px;_x000D_
  -webkit-box-shadow: 0 0 50px 0 rgba(0,0,0,0.3);_x000D_
  opacity: 0;_x000D_
  transition: opacity 0.5s ease;_x000D_
}_x000D_
_x000D_
_x000D_
.overflow:hover + .tooltip {_x000D_
  /*visibility: visible; */_x000D_
  display: initial;_x000D_
  transition: opacity 0.5s ease;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div>_x000D_
  <span class="wrap">_x000D_
    <span class="overflow" style="float: left; width: 50px">Long text that might overflow</span>_x000D_
    <span class='tooltip'>Long text that might overflow.</span>_x000D_
  </span>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad recusandae perspiciatis accusantium quas aut explicabo ab. Doloremque quam eos, alias dolore, iusto pariatur earum, ullam, quidem dolores deleniti perspiciatis omnis._x000D_
</div>
_x000D_
_x000D_
_x000D_

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

I put together a quick demo: http://jsbin.com/agugo3/edit

My results on Internet Explorer 8 are 156, 782, and 750, which would indicate slice is much faster in this case.

How to make a simple rounded button in Storyboard?

Short Answer: YES

You can absolutely make a simple rounded button without the need of an additional background image or writing any code for the same. Just follow the screenshot given below, to set the runtime attributes for the button, to get the desired result.

It won't show in the Storyboard but it will work fine when you run the project.

enter image description here

Note:
The 'Key Path' layer.cornerRadius and value is 5. The value needs to be changed according to the height and width of the button. The formula for it is the height of button * 0.50. So play around the value to see the expected rounded button in the simulator or on the physical device. This procedure will look tedious when you have more than one button to be rounded in the storyboard.

C# how to use enum with switch

No need to convert. You can apply conditions on Enums inside a switch. Like so,

public enum Operator
{ 
    PLUS,
    MINUS,
    MULTIPLY,
    DIVIDE
}

public double Calculate(int left, int right, Operator op)
{
    switch (op)
    {
        case Operator.PLUS: return left + right; 
        case Operator.MINUS: return left - right; 
        case Operator.MULTIPLY: return left * right;
        case Operator.DIVIDE: return left / right;
        default: return 0.0; 
    }
}

Then, call it like this:

Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, Operator.PLUS));

Find ALL tweets from a user (not just the first 3,200)

The only way to see more is to start saving them before the user's tweet count hits 3200. Services which show more than 3200 tweets have saved them in their own dbs. There's currently no way to get more than that through any Twitter API.

http://www.quora.com/Is-there-a-way-to-get-more-than-3200-tweets-from-a-twitter-user-using-Twitters-API-or-scraping

https://dev.twitter.com/discussions/276

Note from that second link: "…the 3,200 limit is for browsing the timeline only. Tweets can always be requested by their ID using the GET statuses/show/:id method."

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

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

How to create a file on Android Internal Storage?

Write a file

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir()

      Returns a File representing an internal directory for your app.

getCacheDir()

     Returns a File representing an internal directory for your 
     app's temporary cache files.
     Be sure to delete each file once it is no longer needed and implement a reasonable 
     size limit for the amount of memory you use at any given time, such as 1MB.

Caution: If the system runs low on storage, it may delete your cache files without warning.

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

if you are using httpd/apache, you can add a file something like ws.conf and add this code to it. Also, this solution can proxy something like this "http://localhost:6001/socket.io" to just this "http://localhost/socket.io"

<VirtualHost *:80>
    RewriteEngine on

    #redirect WebSocket
    RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
    RewriteCond %{QUERY_STRING} transport=websocket    [NC]
    RewriteRule /(.*)           ws://localhost:6001/$1 [P,L]

    ProxyPass        /socket.io http://localhost:6001/socket.io
    ProxyPassReverse /socket.io http://localhost:6001/socket.io
</VirtualHost>

How to set a cron job to run every 3 hours

Change Minute to be 0. That's it :)

Note: you can check your "crons" in http://cronchecker.net/

Example

Convert a Pandas DataFrame to a dictionary

DataFrame.to_dict() converts DataFrame to dictionary.

Example

>>> df = pd.DataFrame(
    {'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b'])
>>> df
   col1  col2
a     1   0.1
b     2   0.2
>>> df.to_dict()
{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}

See this Documentation for details

PHP: How to check if a date is today, yesterday or tomorrow

Here is a more polished version of the accepted answer. It accepts only timestamps and returns a relative date or a formatted date string for everything +/-2 days

<?php

/**
 * Relative time
 *
 * date Format http://php.net/manual/en/function.date.php
 * strftime Format http://php.net/manual/en/function.strftime.php
 * latter can be used with setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
 *
 * @param  timestamp $target
 * @param  timestamp $base   start time, defaults to time()
 * @param  string $format use date('Y') or strftime('%Y') format string
 * @return string
 */
function relative_time($target, $base = NULL, $format = 'Y-m-d H:i:s')
{

    if(is_null($base)) {
        $base = time();
    }

    $baseDate = new DateTime();
    $targetDate = new DateTime();

    $baseDate->setTimestamp($base);
    $targetDate->setTimestamp($target);

    // don't modify original dates
    $baseDateTemp = clone $baseDate;
    $targetDateTemp = clone $targetDate;

    // normalize times -> reset to midnight that day
    $baseDateTemp = $baseDateTemp->modify('midnight');
    $targetDateTemp = $targetDateTemp->modify('midnight');

    $interval = (int) $baseDateTemp->diff($targetDateTemp)->format('%R%a');

    d($baseDate->format($format));

    switch($interval) {
        case 0:
            return (string) 'today';
        break;

        case -1:
            return (string) 'yesterday';
        break;

        case 1:
            return (string) 'tomorrow';
        break;

        default:
            if(strpos($format,'%') !== false )
            {
                return (string) strftime($format,  $targetDate->getTimestamp());
            }
            return (string) $targetDate->format($format);
        break;

    }
}

setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo relative_time($weather->time, null, '%A, %#d. %B'); // Montag, 6. August 
echo relative_time($weather->time, null, 'l, j. F'); // Monday, 6. August

TypeError: method() takes 1 positional argument but 2 were given

Pass cls parameter into @classmethod to resolve this problem.

@classmethod
def test(cls):
    return ''

How to select an item in a ListView programmatically?

Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application.

  1. The simple solution is to set the focus to the ListView first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load event, or immediately after you set the Selected property:

    myListView.Select();
    

    The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button).

  2. To fix that, you will need to set the HideSelection property of the ListView control to False. That will cause the selected item to remain highlighted, even when the control loses the focus.

    When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text.

    You can set this property either at design time, or through code:

    myListView.HideSelection = false;
    

How to replace an entire line in a text file by line number

# Replace the line of the given line number with the given replacement in the given file.
function replace-line-in-file() {
    local file="$1"
    local line_num="$2"
    local replacement="$3"

    # Escape backslash, forward slash and ampersand for use as a sed replacement.
    replacement_escaped=$( echo "$replacement" | sed -e 's/[\/&]/\\&/g' )

    sed -i "${line_num}s/.*/$replacement_escaped/" "$file"
}

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

i also had this issue- very annoying and haven't found a satisfactory sql answer myself yet (aside from long-winded ones involving creating temp tables etc.) and i didn't have time to explore it to the conclusion i'd have liked.

In the end just used SQL Server Management Studio to do it by selecting the table, right-clicking on the column and hitting rename. simples!

obviously i'd rather know how to do it without a gui but sometimes you've just gotta get sh** done!

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

How can I add a line to a file in a shell script?

To answer your original question, here's how you do it with sed:

sed -i '1icolumn1, column2, column3' testfile.csv

The "1i" command tells sed to go to line 1 and insert the text there.

The -i option causes the file to be edited "in place" and can also take an optional argument to create a backup file, for example

sed -i~ '1icolumn1, column2, column3' testfile.csv

would keep the original file in "testfile.csv~".

What's the difference between jquery.js and jquery.min.js?

summary - popular js frameworks like jquery or dojo offer one commented, pretty formatted version with comments for DEVELOPMENT and a minified version (quicker) without comments etc. for PRODUCTION

jquery.js - development jquery.min.js - production

long long in C/C++

The letters 100000000000 make up a literal integer constant, but the value is too large for the type int. You need to use a suffix to change the type of the literal, i.e.

long long num3 = 100000000000LL;

The suffix LL makes the literal into type long long. C is not "smart" enough to conclude this from the type on the left, the type is a property of the literal itself, not the context in which it is being used.

How do I refresh a DIV content?

Complete working code would look like this:

<script> 
$(document).ready(function(){
setInterval(function(){
      $("#here").load(window.location.href + " #here" );
}, 3000);
});
</script>

<div id="here">dynamic content ?</div>

self reloading div container refreshing every 3 sec.

Order columns through Bootstrap4

This can also be achieved with the CSS "Order" property and a media query.

Something like this:

@media only screen and (max-width: 768px) {
    #first {
        order: 2;
    }
    #second {
        order: 4;
    }
    #third {
        order: 1;
    }
    #fourth {
        order: 3;
    }
}

CodePen Link: https://codepen.io/preston206/pen/EwrXqm

How To Get Selected Value From UIPickerView

This is what I did:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    selectedEntry = [allEntries objectAtIndex:row];

}

The selectedEntry is a NSString and will hold the currently selected entry in the pickerview. I am new to objective C but I think this is much easier.

How do I use T-SQL's Case/When?

As soon as a WHEN statement is true the break is implicit.

You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.

More information here: break in case statement in T-SQL

JavaScript, Node.js: is Array.forEach asynchronous?

Here is a small example you can run to test it:

[1,2,3,4,5,6,7,8,9].forEach(function(n){
    var sum = 0;
    console.log('Start for:' + n);
    for (var i = 0; i < ( 10 - n) * 100000000; i++)
        sum++;

    console.log('Ended for:' + n, sum);
});

It will produce something like this(if it takes too less/much time, increase/decrease the number of iterations):

(index):48 Start for:1
(index):52 Ended for:1 900000000
(index):48 Start for:2
(index):52 Ended for:2 800000000
(index):48 Start for:3
(index):52 Ended for:3 700000000
(index):48 Start for:4
(index):52 Ended for:4 600000000
(index):48 Start for:5
(index):52 Ended for:5 500000000
(index):48 Start for:6
(index):52 Ended for:6 400000000
(index):48 Start for:7
(index):52 Ended for:7 300000000
(index):48 Start for:8
(index):52 Ended for:8 200000000
(index):48 Start for:9
(index):52 Ended for:9 100000000
(index):45 [Violation] 'load' handler took 7285ms

Using Mockito to test abstract classes

You can instantiate an anonymous class, inject your mocks and then test that class.

@RunWith(MockitoJUnitRunner.class)
public class ClassUnderTest_Test {

    private ClassUnderTest classUnderTest;

    @Mock
    MyDependencyService myDependencyService;

    @Before
    public void setUp() throws Exception {
        this.classUnderTest = getInstance();
    }

    private ClassUnderTest getInstance() {
        return new ClassUnderTest() {

            private ClassUnderTest init(
                    MyDependencyService myDependencyService
            ) {
                this.myDependencyService = myDependencyService;
                return this;
            }

            @Override
            protected void myMethodToTest() {
                return super.myMethodToTest();
            }
        }.init(myDependencyService);
    }
}

Keep in mind that the visibility must be protected for the property myDependencyService of the abstract class ClassUnderTest.

Location for session files in Apache/PHP

Another common default location besides /tmp/ is /var/lib/php5/

How do I get rid of the "cannot empty the clipboard" error?

check this tip. worked for here http://mobeer.blogspot.com/2009/01/excel-2007-cannot-empty-clipboard.html:

This might save somebody some time and headaches if google picks it up. I was getting a 'Cannot empty the Clipboard' error every time I moved cells around in Excel - eventually I mucked around with the settings and made it go away. Here's how; In the excel main menu (glass globe w/logo), click Excel options, then Advanced, then turn off 'Show paste options buttons'

How exciting was this as my first post of the year?

Update: I still haven't found a permanent solution but I found another thing that seems to help. In Excel 2007, from the "home" tab, the first thing on the left is the clipboard tool panel. Expand the panel to view the clipboard and in the clipboard you might find "cannot empty clipboard" as an entry. Empty the clipboard, keep the panel open for a second or two while you do a few cut and pastes/drags etc. and then the bogey seems to go away.

I call this the cable dance because back in the day I had a printer that only worked if you unplugged the cable, shook it out and plugged it back in.

Reading Excel files from C#

I just used ExcelLibrary to load an .xls spreadsheet into a DataSet. Worked great for me.

writing integer values to a file using out.write()

i = Your_int_value

Write bytes value like this for example:

the_file.write(i.to_bytes(2,"little"))

Depend of you int value size and the bit order your prefer

How to align form at the center of the page in html/css

I would just use table and not the form. Its done by using margin.

table {
  margin: 0 auto;
}

also try using something like

table td {
    padding-bottom: 5px;
}

instead of <br />

and also your input should end with /> e.g:

<input type="password" name="cpwd" />

How to enable authentication on MongoDB through Docker?

I want to comment but don't have enough reputation.

The user-adding executable script shown above has to be modified with --authenticationDatabase admin and NEWDATABASENAME.

mongo --authenticationDatabase admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED NEWDATABASENAME --eval "db.createUser({user: 'NEWUSERNAME', pwd: 'PASSWORD', roles: [{role: 'readWrite', db: 'NEWDATABASENAME'}]});"

https://i.stack.imgur.com/MdyXo.png

@Value annotation type casting to Integer from String

If you want to convert a property to an integer from properties file there are 2 solutions which I found:

Given scenario: customer.properties contains customer.id = 100 as a field and you want to access it in spring configuration file as integer.The property customerId is declared as type int in the Bean Customer

Solution 1:

_x000D_
_x000D_
<property name="customerId" value="#{T(java.lang.Integer).parseInt('${customer.id}')}" />
_x000D_
_x000D_
_x000D_

In the above line, the string value from properties file is converted to int type.

solution 2: Use some other extension inplace of propeties.For Ex.- If your properties file name is customer.properties then make it customer.details and in the configuration file use the below code

_x000D_
_x000D_
<property name="customerId"   value="${customer.id}" />
_x000D_
_x000D_
_x000D_

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

I feel like this has been well covered, maybe except for the following:

  • Simple KEY / INDEX (or otherwise called SECONDARY INDEX) do increase performance if selectivity is sufficient. On this matter, the usual recommendation is that if the amount of records in the result set on which an index is applied exceeds 20% of the total amount of records of the parent table, then the index will be ineffective. In practice each architecture will differ but, the idea is still correct.

  • Secondary Indexes (and that is very specific to mysql) should not be seen as completely separate and different objects from the primary key. In fact, both should be used jointly and, once this information known, provide an additional tool to the mysql DBA: in Mysql, indexes embed the primary key. It leads to significant performance improvements, specifically when cleverly building implicit covering indexes such as described there.

  • If you feel like your data should be UNIQUE, use a unique index. You may think it's optional (for instance, working it out at application level) and that a normal index will do, but it actually represents a guarantee for Mysql that each row is unique, which incidentally provides a performance benefit.

  • You can only use FULLTEXT (or otherwise called SEARCH INDEX) with Innodb (In MySQL 5.6.4 and up) and Myisam Engines

  • You can only use FULLTEXT on CHAR, VARCHAR and TEXT column types

  • FULLTEXT index involves a LOT more than just creating an index. There's a bunch of system tables created, a completely separate caching system and some specific rules and optimizations applied. See http://dev.mysql.com/doc/refman/5.7/en/fulltext-restrictions.html and http://dev.mysql.com/doc/refman/5.7/en/innodb-fulltext-index.html

What's the difference between lists enclosed by square brackets and parentheses in Python?

The first is a list, the second is a tuple. Lists are mutable, tuples are not.

Take a look at the Data Structures section of the tutorial, and the Sequence Types section of the documentation.

Export to xls using angularjs

I had this problem and I made a tool to export an HTML table to CSV file. The problem I had with FileSaver.js is that this tool grabs the table with html format, this is why some people can't open the file in excel or google. All you have to do is export the js file and then call the function. This is the github url https://github.com/snake404/tableToCSV if someone has the same problem.

iOS Swift - Get the Current Local Time and Date Timestamp

in Swift 5

extension Date {
    static var currentTimeStamp: Int64{
        return Int64(Date().timeIntervalSince1970 * 1000)
    }
}

call like this:

let timeStamp = Date.currentTimeStamp
print(timeStamp)

Thanks @lenooh

How to make modal dialog in WPF?

Window.Show will show the window, and continue execution -- it's a non-blocking call.

Window.ShowDialog will block the calling thread (kinda [1]), and show the dialog. It will also block interaction with the parent/owning window. When the dialog is dismissed (for whatever reason), ShowDialog will return to the caller, and will allow you to access DialogResult (if you want it).

[1] It will keep the dispatcher pumping by pushing a dispatcher frame onto the WPF dispatcher. This will cause the message pump to keep pumping.

How to access site running apache server over lan without internet connection

Open httpd.conf of Apache server (backup first) Look for the the following : Listen

Change the line to

Listen *:80

Still in httpd.conf, look for the following (or similar):

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
    Deny from all
</Directory>

Change this block to :

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
    #Deny from all
</Directory>

Save httpd.conf and restart apache

Open port 80 of the server such that everyone can access your server.

Open Control Panel >> System and Security >> Windows Firewall then click on “Advance Setting” and then select “Inbound Rules” from the left panel and then click on “Add Rule…”. Select “PORT” as an option from the list and then in the next screen select “TCP” protocol and enter port number “80” under “Specific local port” then click on the ”Next” button and select “Allow the Connection” and then give the general name and description to this port and click Done.

Restart WAMP and access your machine in LAN or WAN.

How do I URL encode a string

This one is working for me.

func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {
    let unreserved = "*-._"
    let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
    allowed.addCharactersInString(unreserved)

    if plusForSpace {
        allowed.addCharactersInString(" ")
    }

    var encoded = stringByAddingPercentEncodingWithAllowedCharacters(allowed)
    if plusForSpace {
        encoded = encoded?.stringByReplacingOccurrencesOfString(" ",
                                                                withString: "+")
    }
    return encoded
}

I found the above function from this link: http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/

You can also use this function with swift extension. Please let me know if there is any issue.

CSS force new line

Use the display property

a{
    display: block;
}

This will make the link to display in new line

If you want to remove list styling, use

li{
    list-style: none;
}

How can I schedule a daily backup with SQL Server Express?

The folks at MSSQLTips have some very helpful articles, the one most relevant for this is "Automating SQL Server 2005 Express Backups and Deletion of Older Backup Files"

The basic approach is to set up two tasks using the Windows Task Scheduler. One task runs a TSQL script that generates separate backup files for all MSSQL databases (except TEMPDB) with the database name and a date/time stamp in the file name into a specified directory. The second task runs a VBScript script that goes through that directory and deletes all files with a .BAK extension that are more than 3 days old.

Both scripts require minor editing for your environment (paths, how long to keep those database dumps) but are very close to drop-in-and-run.

Note that there are possible security implications if you're sloppy with these or with directory permissions, since they are plain text files that will need to run with some level of privilege. Don't be sloppy.

Show hide divs on click in HTML and CSS without jQuery

You can use a checkbox to simulate onClick with CSS:

input[type=checkbox]:checked + p {
    display: none;
}

JSFiddle

Adjacent sibling selectors

How do I reset a sequence in Oracle?

This is my approach:

  1. drop the sequence
  2. recreate it

Example:

--Drop sequence

DROP SEQUENCE MY_SEQ;

-- Create sequence 

create sequence MY_SEQ
minvalue 1
maxvalue 999999999999999999999
start with 1
increment by 1
cache 20;

Java Returning method which returns arraylist?

You can use on another class

public ArrayList<Integer> myNumbers = new Foo().myNumbers();

or

Foo myClass = new Foo();
 public ArrayList<Integer> myNumbers = myclass.myNumbers();

What EXACTLY is meant by "de-referencing a NULL pointer"?

From wiki

A null pointer has a reserved value, often but not necessarily the value zero, indicating that it refers to no object
..

Since a null-valued pointer does not refer to a meaningful object, an attempt to dereference a null pointer usually causes a run-time error.

int val =1;
int *p = NULL;
*p = val; // Whooosh!!!! 

How to position background image in bottom right corner? (CSS)

Did you try something like:

body {background: url('[url to your image]') no-repeat right bottom;}

SQL: Alias Column Name for Use in CASE Statement

  • If you write only equal condition just: Select Case columns1 When 0 then 'Value1' when 1 then 'Value2' else 'Unknown' End

  • If you want to write greater , Less then or equal you must do like this: Select Case When [ColumnsName] >0 then 'value1' When [ColumnsName]=0 Or [ColumnsName]<0 then 'value2' Else 'Unkownvalue' End

From tablename

Thanks Mr.Buntha Khin

Is there a max size for POST parameter content?

Yes there is 2MB max and it can be increased by configuration change like this. If your POST body is not in form of multipart file then you might need to add the max-http-post configuration for tomcat in the application yml configuration file.

Increase max size of each multipart file to 10MB and total payload size of 100MB max

 spring:
    servlet:
      multipart:max-file-size: 10MB
      multipart:max-request-size: 100MB
 

Setting max size of post requests which might just be the formdata in string format to ~10 MB

 server:
    tomcat:
        max-http-post-size: 100000000 # max-http-form-post-size: 10MB for new version

You might need to add this for the latest sprintboot version ->

server: tomcat: max-http-form-post-size: 10MB

How to find the Number of CPU Cores via .NET/C#?

One option would be to read the data from the registry. MSDN Article On The Topic: http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.localmachine(v=vs.71).aspx)

The processors, I believe can be located here, HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor

    private void determineNumberOfProcessCores()
    {
        RegistryKey rk = Registry.LocalMachine;
        String[] subKeys = rk.OpenSubKey("HARDWARE").OpenSubKey("DESCRIPTION").OpenSubKey("System").OpenSubKey("CentralProcessor").GetSubKeyNames();

        textBox1.Text = "Total number of cores:" + subKeys.Length.ToString();
    }

I am reasonably sure the registry entry will be there on most systems.

Though I would throw my $0.02 in.

Reading a UTF8 CSV file with Python

The link to the help page is the same for python 2.6 and as far as I know there was no change in the csv module since 2.5 (besides bug fixes). Here is the code that just works without any encoding/decoding (file da.csv contains the same data as the variable data). I assume that your file should be read correctly without any conversions.

test.py:

## -*- coding: utf-8 -*-
#
# NOTE: this first line is important for the version b) read from a string(unicode) variable
#

import csv

data = \
"""0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert"""

# a) read from a file
print 'reading from a file:'
for (f1, f2, f3) in csv.reader(open('da.csv'), dialect=csv.excel):
    print (f1, f2, f3)

# b) read from a string(unicode) variable
print 'reading from a list of strings:'
reader = csv.reader(data.split('\n'), dialect=csv.excel)
for (f1, f2, f3) in reader:
    print (f1, f2, f3)

da.csv:

0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert

Best way to track onchange as-you-type in input type="text"?

Please, judge next approach using JQuery:

HTML:

<input type="text" id="inputId" />

Javascript(JQuery):

$("#inputId").keyup(function(){
        $("#inputId").blur();
        $("#inputId").focus();
});

$("#inputId").change(function(){
        //do whatever you need to do on actual change of the value of the input field
});

Round integers to the nearest 10

if you want the algebric form and still use round for it it's hard to get simpler than:

interval = 5
n = 4
print(round(n/interval))*interval

How to map with index in Ruby?

Over the top obfuscation:

arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

Traverse all the Nodes of a JSON Object Tree with JavaScript

Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.

function traverse(o, fn) {
    const stack = [o]

    while (stack.length) {
        const obj = stack.shift()

        Object.keys(obj).forEach((key) => {
            fn(key, obj[key], obj)
            if (obj[key] instanceof Object) {
                stack.unshift(obj[key])
                return
            }
        })
    }
}

const o = {
    name: 'Max',
    legal: false,
    other: {
        name: 'Maxwell',
        nested: {
            legal: true
        }
    }
}

const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

DECLARE @name VARCHAR(255)
DECLARE @type VARCHAR(10)
DECLARE @prefix VARCHAR(255)
DECLARE @sql VARCHAR(255)

DECLARE curs CURSOR FOR
SELECT [name], xtype
FROM sysobjects
WHERE xtype IN ('U', 'P', 'FN', 'IF', 'TF', 'V', 'TR') -- Configuration point 1
ORDER BY name

OPEN curs
FETCH NEXT FROM curs INTO @name, @type

WHILE @@FETCH_STATUS = 0
BEGIN
-- Configuration point 2
SET @prefix = CASE @type
WHEN 'U' THEN 'DROP TABLE'
WHEN 'P' THEN 'DROP PROCEDURE'
WHEN 'FN' THEN 'DROP FUNCTION'
WHEN 'IF' THEN 'DROP FUNCTION'
WHEN 'TF' THEN 'DROP FUNCTION'
WHEN 'V' THEN 'DROP VIEW'
WHEN 'TR' THEN 'DROP TRIGGER'
END

SET @sql = @prefix + ' ' + @name
PRINT @sql
EXEC(@sql)
FETCH NEXT FROM curs INTO @name, @type
END

CLOSE curs
DEALLOCATE curs