Programs & Examples On #Pthreads

Pthreads (POSIX Threads) is a standardised C-based API for creating and manipulating threads. It is currently defined by POSIX.1-2008 (IEEE Std 1003.1, 2013 Edition / The Open Group Base Specifications Issue 7).

mingw-w64 threads: posix vs win32

GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.

I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.

To summarize:

  • posix: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.
  • win32: No C++11 multithreading features.

Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.

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

As @Ninefingers mentioned, pthreads are unix-only. Posix only, really.

That said, Microsoft does have a library that duplicates pthreads:

Microsoft Windows Services for UNIX Version 3.5

Library Download

How to return a value from pthread threads in C?

Here is a correct solution. In this case tdata is allocated in the main thread, and there is a space for the thread to place its result.

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

typedef struct thread_data {
   int a;
   int b;
   int result;

} thread_data;

void *myThread(void *arg)
{
   thread_data *tdata=(thread_data *)arg;

   int a=tdata->a;
   int b=tdata->b;
   int result=a+b;

   tdata->result=result;
   pthread_exit(NULL);
}

int main()
{
   pthread_t tid;
   thread_data tdata;

   tdata.a=10;
   tdata.b=32;

   pthread_create(&tid, NULL, myThread, (void *)&tdata);
   pthread_join(tid, NULL);

   printf("%d + %d = %d\n", tdata.a, tdata.b, tdata.result);   

   return 0;
}

Undefined reference to pthread_create in Linux

Compile it like this : gcc demo.c -o demo -pthread

How to print pthread_t

No need to get fancy, you can treat pthread_t as a pointer without a cast:

printf("awesome worker thread id %p\n", awesome_worker_thread_id);

Output:

awesome worker thread id 0x6000485e0

How to get thread id of a pthread in linux c program?

Platform-independent way (starting from c++11) is:

#include <thread>

std::this_thread::get_id();

pthread function from a class

My first answer ever in the hope that it'll be usefull to someone : I now this is an old question but I encountered exactly the same error as the above question as I'm writing a TcpServer class and I was trying to use pthreads. I found this question and I understand now why it was happening. I ended up doing this:

#include <thread>

method to run threaded -> void* TcpServer::sockethandler(void* lp) {/*code here*/}

and I call it with a lambda -> std::thread( [=] { sockethandler((void*)csock); } ).detach();

that seems a clean approach to me.

Still Reachable Leak detected by Valgrind

Since there is some routine from the the pthread family on the bottom (but I don't know that particular one), my guess would be that you have launched some thread as joinable that has terminated execution.

The exit state information of that thread is kept available until you call pthread_join. Thus, the memory is kept in a loss record at program termination, but it is still reachable since you could use pthread_join to access it.

If this analysis is correct, either launch these threads detached, or join them before terminating your program.

Edit: I ran your sample program (after some obvious corrections) and I don't have errors but the following

==18933== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
--18933-- 
--18933-- used_suppression:      2 dl-hack3-cond-1
--18933-- used_suppression:      2 glibc-2.5.x-on-SUSE-10.2-(PPC)-2a

Since the dl- thing resembles much of what you see I guess that you see a known problem that has a solution in terms of a suppression file for valgrind. Perhaps your system is not up to date, or your distribution doesn't maintain these things. (Mine is ubuntu 10.4, 64bit)

Mutex lock threads

Below, code snippet, will help you in understanding the mutex-lock-unlock concept. Attempt dry-run on the code. (further by varying the wait-time and process-time, you can build you understanding).

Code for your reference:

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

void in_progress_feedback(int);

int global = 0;
pthread_mutex_t mutex;
void *compute(void *arg) {

    pthread_t ptid = pthread_self();
    printf("ptid : %08x \n", (int)ptid);    

    int i;
    int lock_ret = 1;   
    do{

        lock_ret = pthread_mutex_trylock(&mutex);
        if(lock_ret){
            printf("lock failed(%08x :: %d)..attempt again after 2secs..\n", (int)ptid,  lock_ret);
            sleep(2);  //wait time here..
        }else{  //ret =0 is successful lock
            printf("lock success(%08x :: %d)..\n", (int)ptid, lock_ret);
            break;
        }

    } while(lock_ret);

        for (i = 0; i < 10*10 ; i++) 
        global++;

    //do some stuff here
    in_progress_feedback(10);  //processing-time here..

    lock_ret = pthread_mutex_unlock(&mutex);
    printf("unlocked(%08x :: %d)..!\n", (int)ptid, lock_ret);

     return NULL;
}

void in_progress_feedback(int prog_delay){

    int i=0;
    for(;i<prog_delay;i++){
    printf(". ");
    sleep(1);
    fflush(stdout);
    }

    printf("\n");
    fflush(stdout);
}

int main(void)
{
    pthread_t tid0,tid1;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid0, NULL, compute, NULL);
    pthread_create(&tid1, NULL, compute, NULL);
    pthread_join(tid0, NULL);
    pthread_join(tid1, NULL);
    printf("global = %d\n", global);
    pthread_mutex_destroy(&mutex);
          return 0;
}

When to use pthread_exit() and when to use pthread_join() in Linux?

  #include<stdio.h>
  #include<pthread.h>
  #include<semaphore.h>
 
   sem_t st;
   void *fun_t(void *arg);
   void *fun_t(void *arg)
   {
       printf("Linux\n");
       sem_post(&st);
       //pthread_exit("Bye"); 
       while(1);
       pthread_exit("Bye");
   }
   int main()
   {
       pthread_t pt;
       void *res_t;
       if(pthread_create(&pt,NULL,fun_t,NULL) == -1)
           perror("pthread_create");
       if(sem_init(&st,0,0) != 0)
           perror("sem_init");
       if(sem_wait(&st) != 0)
           perror("sem_wait");
       printf("Sanoundry\n");
       //Try commenting out join here.
       if(pthread_join(pt,&res_t) == -1)
           perror("pthread_join");
       if(sem_destroy(&st) != 0)
           perror("sem_destroy");
       return 0;
   }

Copy and paste this code on a gdb. Onlinegdb would work and see for yourself.

Make sure you understand once you have created a thread, the process run along with main together at the same time.

  1. Without the join, main thread continue to run and return 0
  2. With the join, main thread would be stuck in the while loop because it waits for the thread to be done executing.
  3. With the join and delete the commented out pthread_exit, the thread will terminate before running the while loop and main would continue
  4. Practical usage of pthread_exit can be used as an if conditions or case statements to ensure 1 version of some code runs before exiting.
void *fun_t(void *arg)
   {
       printf("Linux\n");
       sem_post(&st); 
       if(2-1 == 1)  
           pthread_exit("Bye");
       else
       { 
           printf("We have a problem. Computer is bugged");
           pthread_exit("Bye"); //This is redundant since the thread will exit at the end
                                //of scope. But there are instances where you have a bunch
                                //of else if here.
       }
   }

I would want to demonstrate how sometimes you would need to have a segment of code running first using semaphore in this example.

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>

sem_t st;

void* fun_t (void* arg)
{
    printf("I'm thread\n");
    sem_post(&st);
}

int main()
{
    pthread_t pt;
    pthread_create(&pt,NULL,fun_t,NULL);
    sem_init(&st,0,0);
    sem_wait(&st);
    printf("before_thread\n");
    pthread_join(pt,NULL);
    printf("After_thread\n");
    
}

Noticed how fun_t is being ran after "before thread" The expected output if it is linear from top to bottom would be before thread, I'm thread, after thread. But under this circumstance, we block the main from running any further until the semaphore is released by func_t. The result can be verified with https://www.onlinegdb.com/

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

}

What's the difference between deadlock and livelock?

DEADLOCK Deadlock is a condition in which a task waits indefinitely for conditions that can never be satisfied - task claims exclusive control over shared resources - task holds resources while waiting for other resources to be released - tasks cannot be forced to relinguish resources - a circular waiting condition exists

LIVELOCK Livelock conditions can arise when two or more tasks depend on and use the some resource causing a circular dependency condition where those tasks continue running forever, thus blocking all lower priority level tasks from running (these lower priority tasks experience a condition called starvation)

Multiple arguments to function called by pthread_create()?

Because you say

struct arg_struct *args = (struct arg_struct *)args;

instead of

struct arg_struct *args = arguments;

cmake and libpthread

target_compile_options solution above is wrong, it won't link the library.

Use:

SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")

OR

target_link_libraries(XXX PUBLIC pthread)

OR

set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)

Simple pthread! C++

Linkage. Try this:

extern "C" void *print_message() {...

How can I remove duplicate rows?

Using CTE. The idea is to join on one or more columns that form a duplicate record and then remove whichever you like:

;with cte as (
    select 
        min(PrimaryKey) as PrimaryKey
        UniqueColumn1,
        UniqueColumn2
    from dbo.DuplicatesTable 
    group by
        UniqueColumn1, UniqueColumn1
    having count(*) > 1
)
delete d
from dbo.DuplicatesTable d 
inner join cte on 
    d.PrimaryKey > cte.PrimaryKey and
    d.UniqueColumn1 = cte.UniqueColumn1 and 
    d.UniqueColumn2 = cte.UniqueColumn2;

Convert text into number in MySQL query

You can use CAST() to convert from string to int. e.g. SELECT CAST('123' AS INTEGER);

Target a css class inside another css class

I use div instead of tables and am able to target classes within the main class, as below:

CSS

.main {
    .width: 800px;
    .margin: 0 auto;
    .text-align: center;
}
.main .table {
    width: 80%;
}
.main .row {
   / ***something ***/
}
.main .column {
    font-size: 14px;
    display: inline-block;
}
.main .left {
    width: 140px;
    margin-right: 5px;
    font-size: 12px;
}
.main .right {
    width: auto;
    margin-right: 20px;
    color: #fff;
    font-size: 13px;
    font-weight: normal;
}

HTML

<div class="main">
    <div class="table">
        <div class="row">
            <div class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

.main #red { color: red; }

<div class="main">
    <div class="table">
        <div class="row">
            <div id="red" class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

Multiplying Two Columns in SQL Server

select InitialPayment * MonthlyRate as MultiplyingCalculation, InitialPayment - MonthlyRate as SubtractingCalculation from Payment

If a DOM Element is removed, are its listeners also removed from memory?

Just extending other answers...

Delegated events handlers will not be removed upon element removal.

$('body').on('click', '#someEl', function (event){
  console.log(event);
});

$('#someEL').remove(); // removing the element from DOM

Now check:

$._data(document.body, 'events');

How do you connect to multiple MySQL databases on a single webpage?

Warning : mysql_xx functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php), use mysqli_xx functions or see the answer below from @Troelskn


You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for the '$new_link' (fourth) parameter, otherwise the same connection is reused. For example:

$dbh1 = mysql_connect($hostname, $username, $password); 
$dbh2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);

Then to query database 1 pass the first link identifier:

mysql_query('select * from tablename', $dbh1);

and for database 2 pass the second:

mysql_query('select * from tablename', $dbh2);

If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2) e.g.:

mysql_query('select * from tablename');

Other options

If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:

  • Keep one connection open and call mysql_select_db() to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.
  • Specify the database name when you reference tables within your queries (e.g. SELECT * FROM database2.tablename). This is likely to be a pain to implement.

Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.

Difference between DataFrame, Dataset, and RDD in Spark

A DataFrame is an RDD that has a schema. You can think of it as a relational database table, in that each column has a name and a known type. The power of DataFrames comes from the fact that, when you create a DataFrame from a structured dataset (Json, Parquet..), Spark is able to infer a schema by making a pass over the entire (Json, Parquet..) dataset that's being loaded. Then, when calculating the execution plan, Spark, can use the schema and do substantially better computation optimizations. Note that DataFrame was called SchemaRDD before Spark v1.3.0

How to set caret(cursor) position in contenteditable element (div)?

  const el = document.getElementById("editable");
  el.focus()
  let char = 1, sel; // character at which to place caret

  if (document.selection) {
    sel = document.selection.createRange();
    sel.moveStart('character', char);
    sel.select();
  }
  else {
    sel = window.getSelection();
    sel.collapse(el.lastChild, char);
  }

How to kill all processes matching a name?

You can also evaluate your output as a sub-process, by surrounding everything with back ticks or with putting it inside $():

`ps aux | grep -ie amarok | awk '{print "kill -9 " $2}'`

 $(ps aux | grep -ie amarok | awk '{print "kill -9 " $2}')     

How to view data saved in android database(SQLite)?

Dowlnoad sqlite manager and install it from Here.Open the sqlite file using that browser.

Command line to remove an environment variable from the OS level configuration

To remove the variable from the current environment (not permanently):

set FOOBAR=

To permanently remove the variable from the user environment (which is the default place setx puts it):

REG delete HKCU\Environment /F /V FOOBAR

If the variable is set in the system environment (e.g. if you originally set it with setx /M), as an administrator run:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR

Note: The REG commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.

Getting a random value from a JavaScript array

To get crypto-strong random item form array use

_x000D_
_x000D_
let rndItem = a=> a[rnd()*a.length|0];_x000D_
let rnd = ()=> crypto.getRandomValues(new Uint32Array(1))[0]/2**32;_x000D_
_x000D_
var myArray = ['January', 'February', 'March'];_x000D_
_x000D_
console.log( rndItem(myArray) )
_x000D_
_x000D_
_x000D_

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

Get CPU Usage from Windows Command Prompt

The following works correctly on Windows 7 Ultimate from an elevated command prompt:

C:\Windows\system32>typeperf "\Processor(_Total)\% Processor Time"

"(PDH-CSV 4.0)","\\vm\Processor(_Total)\% Processor Time"
"02/01/2012 14:10:59.361","0.648721"
"02/01/2012 14:11:00.362","2.986384"
"02/01/2012 14:11:01.364","0.000000"
"02/01/2012 14:11:02.366","0.000000"
"02/01/2012 14:11:03.367","1.038332"

The command completed successfully.

C:\Windows\system32>

Or for a snapshot:

C:\Windows\system32>wmic cpu get loadpercentage
LoadPercentage
8

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

I modified the script by Nicolay77 to output the database to stdout (the usual way of unix scripts) so that I could output the data to text file or pipe it to any program I want. The resulting script is a bit simpler and works well.

Some examples:

./mdb_to_mysql.sh database.mdb > data.sql

./mdb_to_mysql.sh database.mdb | mysql destination-db -u user -p

Here is the modified script (save to mdb_to_mysql.sh)

#!/bin/bash
TABLES=$(mdb-tables -1 $1)

for t in $TABLES
do
    echo "DROP TABLE IF EXISTS $t;"
done

mdb-schema $1 mysql

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t
done

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Embedding JavaScript engine into .NET

Microsoft's documented way to add script extensibility to anything is IActiveScript. You can use IActiveScript from within anyt .NET app, to call script logic. The logic can party on .NET objects that you've placed into the scripting context.

This answer provides an application that does it, with code:

SELECT query with CASE condition and SUM()

Use an "Or"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

or an "IN"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

It can be that you need to add or update your privacy policy. You can easily create a privacy policy using this template

https://app-privacy-policy-generator.firebaseapp.com/

How to export and import environment variables in windows?

You can use RegEdit to export the following two keys:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

HKEY_CURRENT_USER\Environment

The first set are system/global environment variables; the second set are user-level variables. Edit as needed and then import the .reg files on the new machine.

invalid types 'int[int]' for array subscript

You are subscripting a three-dimensional array myArray[10][10][10] four times myArray[i][t][x][y]. You will probably need to add another dimension to your array. Also consider a container like Boost.MultiArray, though that's probably over your head at this point.

What would be the Unicode character for big bullet in the middle of the character?

http://www.unicode.org is the place to look for symbol names.

? BLACK CIRCLE        25CF
? MEDIUM BLACK CIRCLE 26AB
? BLACK LARGE CIRCLE  2B24

or even:

 NEW MOON SYMBOL   1F311

Good luck finding a font that supports them all. Only one shows up in Windows 7 with Chrome.

Contain form within a bootstrap popover?

I would put my form into the markup and not into some data tag. This is how it could work:

JS Code:

$('#popover').popover({ 
    html : true,
    title: function() {
      return $("#popover-head").html();
    },
    content: function() {
      return $("#popover-content").html();
    }
});

HTML Markup:

<a href="#" id="popover">the popover link</a>
<div id="popover-head" class="hide">
  some title
</div>
<div id="popover-content" class="hide">
  <!-- MyForm -->
</div>

Demo

Alternative Approaches:

X-Editable

You might want to take a look at X-Editable. A library that allows you to create editable elements on your page based on popovers.

X-Editable demo

Webcomponents

Mike Costello has released Bootstrap Web Components. This nifty library has a Popovers Component that lets you embed the form as markup:

<button id="popover-target" data-original-title="MyTitle" title="">Popover</button>

<bs-popover title="Popover with Title" for="popover-target">
  <!-- MyForm -->
</bs-popover>

Demo

How to get min, seconds and milliseconds from datetime.now() in python?

Another similar solution:

>>> a=datetime.now()
>>> "%s:%s.%s" % (a.hour, a.minute, a.microsecond)
'14:28.971209'

Yes, I know I didn't get the string formatting perfect.

Adding ASP.NET MVC5 Identity Authentication to an existing project

I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.

Overview

IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.

For more information, e.g.

  • support for MembershipReboot and ASP.NET Identity based user stores
  • support for additional Katana authentication middleware (e.g. Google, Twitter, Facebook etc)
  • support for EntityFramework based persistence of configuration
  • support for WS-Federation
  • extensibility

check out the documentation and the demo.

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

Open Terminal:

sudo gem update --system 

It works!

Java URLConnection Timeout

You can set timeouts for all connections made from the jvm by changing the following System-properties:

System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");

Every connection will time out after 10 seconds.

Setting 'defaultReadTimeout' is not needed, but shown as an example if you need to control reading.

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

Regex for not empty and not whitespace

/^[\s]*$/ matches empty strings and strings containing whitespaces only

How can I use Bash syntax in Makefile targets?

There is a way to do this without explicitly setting your SHELL variable to point to bash. This can be useful if you have many makefiles since SHELL isn't inherited by subsequent makefiles or taken from the environment. You also need to be sure that anyone who compiles your code configures their system this way.

If you run sudo dpkg-reconfigure dash and answer 'no' to the prompt, your system will not use dash as the default shell. It will then point to bash (at least in Ubuntu). Note that using dash as your system shell is a bit more efficient though.

How to recover just deleted rows in mysql?

Unfortunately, no. If you were running the server in default config, go get your backups (you have backups, right?) - generally, a database doesn't keep previous versions of your data, or a revision of changes: only the current state.

(Alternately, if you have deleted the data through a custom frontend, it is quite possible that the frontend doesn't actually issue a DELETE: many tables have a is_deleted field or similar, and this is simply toggled by the frontend. Note that this is a "soft delete" implemented in the frontend app - the data is not actually deleted in such cases; if you actually issued a DELETE, TRUNCATE or a similar SQL command, this is not applicable.)

How do you update Xcode on OSX to the latest version?

In my case (Xcode 6.1, iOS 8.2) I did not see the update in AppStore. I found Xcode 6.2 for download and pressed "Install". Then, it installed and asked for the update (more than 2 Gb). Xcode 6.2 works correctly with iOS 8.2 and iOS 8.1.2

Hopefully this tip will help somebody else...

how to get text from textview

If it is the sum of all the numbers you want, I made a little snippet for you that can handle both + and - using a regex (I left some print-calls in there to help visualise what happens):

    final String string = "  " + 5 + "\n" + "-" + " " + 9+"\n"+"+"+" "+5; //Or get the value from a TextView
    final Pattern pattern = Pattern.compile("(-?).?(\\d+)");
    Matcher matcher = pattern.matcher(string);

    System.out.print(string);
    System.out.print('\n');
    int sum = 0;

    while( matcher.find() ){
        System.out.print(matcher.group(1));
        System.out.print(matcher.group(2));
        System.out.print('\n');
        sum += Integer.parseInt(matcher.group(1)+matcher.group(2));
    }
    System.out.print("\nSum: "+sum);

This code prints the following:

  5
- 9
+ 5
5
-9
5

Sum: 1

Edit: sorry if I misunderstood your question, it was a little bit unclear what you wanted to do. I assumed you wanted to get the sum of the numbers as an integer rather than a string.

Edit2: to get the numbers separate from each other, do something like this instead:

    final String string = "  " + 5 + "\n" + "-" + " " + 9+"\n"+"+"+" "+5; //Or get the value from a TextView
    final Pattern pattern = Pattern.compile("(-?).?(\\d+)");
    Matcher matcher = pattern.matcher(string);
    ArrayList<Integer> numbers = new ArrayList<Integer>();

    while( matcher.find() ){
        numbers.add(Integer.parseInt(matcher.group(1)+matcher.group(2)));
    }

Faster way to zero memory than with memset?

That's an interesting question. I made this implementation that is just slightly faster (but hardly measurable) when 32-bit release compiling on VC++ 2012. It probably can be improved on a lot. Adding this in your own class in a multithreaded environment would probably give you even more performance gains since there are some reported bottleneck problems with memset() in multithreaded scenarios.

// MemsetSpeedTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include "Windows.h"
#include <time.h>

#pragma comment(lib, "Winmm.lib") 
using namespace std;

/** a signed 64-bit integer value type */
#define _INT64 __int64

/** a signed 32-bit integer value type */
#define _INT32 __int32

/** a signed 16-bit integer value type */
#define _INT16 __int16

/** a signed 8-bit integer value type */
#define _INT8 __int8

/** an unsigned 64-bit integer value type */
#define _UINT64 unsigned _INT64

/** an unsigned 32-bit integer value type */
#define _UINT32 unsigned _INT32

/** an unsigned 16-bit integer value type */
#define _UINT16 unsigned _INT16

/** an unsigned 8-bit integer value type */
#define _UINT8 unsigned _INT8

/** maximum allo

wed value in an unsigned 64-bit integer value type */
    #define _UINT64_MAX 18446744073709551615ULL

#ifdef _WIN32

/** Use to init the clock */
#define TIMER_INIT LARGE_INTEGER frequency;LARGE_INTEGER t1, t2;double elapsedTime;QueryPerformanceFrequency(&frequency);

/** Use to start the performance timer */
#define TIMER_START QueryPerformanceCounter(&t1);

/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
#define TIMER_STOP QueryPerformanceCounter(&t2);elapsedTime=(t2.QuadPart-t1.QuadPart)*1000.0/frequency.QuadPart;wcout<<elapsedTime<<L" ms."<<endl;
#else
/** Use to init the clock */
#define TIMER_INIT clock_t start;double diff;

/** Use to start the performance timer */
#define TIMER_START start=clock();

/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
#define TIMER_STOP diff=(clock()-start)/(double)CLOCKS_PER_SEC;wcout<<fixed<<diff<<endl;
#endif    


void *MemSet(void *dest, _UINT8 c, size_t count)
{
    size_t blockIdx;
    size_t blocks = count >> 3;
    size_t bytesLeft = count - (blocks << 3);
    _UINT64 cUll = 
        c 
        | (((_UINT64)c) << 8 )
        | (((_UINT64)c) << 16 )
        | (((_UINT64)c) << 24 )
        | (((_UINT64)c) << 32 )
        | (((_UINT64)c) << 40 )
        | (((_UINT64)c) << 48 )
        | (((_UINT64)c) << 56 );

    _UINT64 *destPtr8 = (_UINT64*)dest;
    for (blockIdx = 0; blockIdx < blocks; blockIdx++) destPtr8[blockIdx] = cUll;

    if (!bytesLeft) return dest;

    blocks = bytesLeft >> 2;
    bytesLeft = bytesLeft - (blocks << 2);

    _UINT32 *destPtr4 = (_UINT32*)&destPtr8[blockIdx];
    for (blockIdx = 0; blockIdx < blocks; blockIdx++) destPtr4[blockIdx] = (_UINT32)cUll;

    if (!bytesLeft) return dest;

    blocks = bytesLeft >> 1;
    bytesLeft = bytesLeft - (blocks << 1);

    _UINT16 *destPtr2 = (_UINT16*)&destPtr4[blockIdx];
    for (blockIdx = 0; blockIdx < blocks; blockIdx++) destPtr2[blockIdx] = (_UINT16)cUll;

    if (!bytesLeft) return dest;

    _UINT8 *destPtr1 = (_UINT8*)&destPtr2[blockIdx];
    for (blockIdx = 0; blockIdx < bytesLeft; blockIdx++) destPtr1[blockIdx] = (_UINT8)cUll;

    return dest;
}

int _tmain(int argc, _TCHAR* argv[])
{
    TIMER_INIT

    const size_t n = 10000000;
    const _UINT64 m = _UINT64_MAX;
    const _UINT64 o = 1;
    char test[n];
    {
        cout << "memset()" << endl;
        TIMER_START;

        for (int i = 0; i < m ; i++)
            for (int j = 0; j < o ; j++)
                memset((void*)test, 0, n);  

        TIMER_STOP;
    }
    {
        cout << "MemSet() took:" << endl;
        TIMER_START;

        for (int i = 0; i < m ; i++)
            for (int j = 0; j < o ; j++)
                MemSet((void*)test, 0, n);

        TIMER_STOP;
    }

    cout << "Done" << endl;
    int wait;
    cin >> wait;
    return 0;
}

Output is as follows when release compiling for 32-bit systems:

memset() took:
5.569000
MemSet() took:
5.544000
Done

Output is as follows when release compiling for 64-bit systems:

memset() took:
2.781000
MemSet() took:
2.765000
Done

Here you can find the source code Berkley's memset(), which I think is the most common implementation.

Get absolute path of initially run script

try this on your script

echo getcwd() . "\n";

get specific row from spark dataframe

This is how I achieved the same in Scala. I am not sure if it is more efficient than the valid answer, but it requires less coding

val parquetFileDF = sqlContext.read.parquet("myParquetFule.parquet")

val myRow7th = parquetFileDF.rdd.take(7).last

Java - ignore exception and continue

I've upvoted Amir Afghani's answer, which seems to be the only one as of yet that actually answers the question.

But I would have written it like this instead:

UserInfo ui = new UserInfo();

DirectoryUser du = null;
try {
    du = LDAPService.findUser(username);
} catch (NullPointerException npe) {
    // It's fine if findUser throws a NPE
}
if (du != null) {
   ui.setUserInfo(du.getUserInfo());
}

Of course, it depends on whether or not you want to catch NPEs from the ui.setUserInfo() and du.getUserInfo() calls.

Object spread vs. Object.assign

I'd like to add this simple example when you have to use Object.assign.

class SomeClass {
  constructor() {
    this.someValue = 'some value';
  }

  someMethod() {
    console.log('some action');
  }
}


const objectAssign = Object.assign(new SomeClass(), {});
objectAssign.someValue; // ok
objectAssign.someMethod(); // ok

const spread = {...new SomeClass()};
spread.someValue; // ok
spread.someMethod(); // there is no methods of SomeClass!

It can be not clear when you use JavaScript. But with TypeScript it is easier if you want to create instance of some class

const spread: SomeClass = {...new SomeClass()} // Error

Firebug-like debugger for Google Chrome

Well, it is possible to enable Greasemonkey scripts for Google Chrome so maybe there is a way to sort of install Firebug using this method? Firebug Lite would also work, but it's just not the same feeling as using the full featured one :(

willshouse.com/2009/05/29/install-greasemonkey-for-chrome-a-better-guide/

How to enter command with password for git pull?

Note that the way the git credential helper "store" will store the unencrypted passwords changes with Git 2.5+ (Q2 2014).
See commit 17c7f4d by Junio C Hamano (gitster)

credential-xdg

Tweak the sample "store" backend of the credential helper to honor XDG configuration file locations when specified.

The doc now say:

If not specified:

  • credentials will be searched for from ~/.git-credentials and $XDG_CONFIG_HOME/git/credentials, and
  • credentials will be written to ~/.git-credentials if it exists, or $XDG_CONFIG_HOME/git/credentials if it exists and the former does not.

Convert Unicode data to int in python

int(limit) returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).

Do this instead:

limit = int(limit)

Or when definiting limit:

if 'limit' in user_data :
    limit = int(user_data['limit'])

How can I delete a query string parameter in JavaScript?

Here a solution that:

  1. uses URLSearchParams (no difficult to understand regex)
  2. updates the URL in the search bar without reload
  3. maintains all other parts of the URL (e.g. hash)
  4. removes superflous ? in query string if the last parameter was removed
function removeParam(paramName) {
    let searchParams = new URLSearchParams(window.location.search);
    searchParams.delete(paramName);
    if (history.replaceState) {
        let searchString = searchParams.toString().length > 0 ? '?' + searchParams.toString() : '';
        let newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname +  searchString + window.location.hash;
        history.replaceState(null, '', newUrl);
    }
}

Note: as pointed out in other answers URLSearchParams is not supported in IE, so use a polyfill.

How to get hostname from IP (Linux)?

Another simple way I found for using in LAN is

ssh [username@ip] uname -n

If you need to login command line will be

sshpass -p "[password]" ssh [username@ip] uname -n

Time calculation in php (add 10 hours)?

$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.

see DateTime Class (PHP 5 >= 5.2.0)

Get the records of last month in SQL server

SELECT * 
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, date_created) = DATEPART(yyyy, DATEADD(m, -1, getdate()))

You need to check the month and year.

HttpClient does not exist in .net 4.0: what can I do?

read this...

Portable HttpClient for .NET Framework and Windows Phone

see paragraph Using HttpClient on .NET Framework 4.0 or Windows Phone 7.5 http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx

how can I set visible back to true in jquery

I would be careful with setting the display of the element to block. Different elements have the standard display as different things. For example setting display to block for a table row in firefox causes the width of the cells to be incorrect.

Is the name of the element actually test1. I know that .NET can add extra things onto the start or end. The best way to find out if your selector is working properly is by doing this.

alert($('#text1').length);

You might just need to remove the visibility attribute

$('#text1').removeAttr('visibility');

'\r': command not found - .bashrc / .bash_profile

For the Emacs users out there:

  1. Open the file
  2. M-x set-buffer-file-coding-system
  3. Select "unix"

This will update the new characters in the file to be unix style. More info on "Newline Representation" in Emacs can be found here:

http://ergoemacs.org/emacs/emacs_line_ending_char.html

Note: The above steps could be made into an Emacs script if one preferred to execute this from the command line.

How to reset a select element with jQuery

Reset single select field to default option.

<select id="name">
    <option>select something</option>
    <option value="1" >something 1</option>
    <option value="2" selected="selected" >Default option</option>
</select>
<script>
    $('name').val( $('name').find("option[selected]").val() );
</script>


Or if you want to reset all form fields to the default option:

<script>
    $('select').each( function() {
        $(this).val( $(this).find("option[selected]").val() );
    });
</script>

PHP foreach loop through multidimensional array

<?php
$first = reset($arr_nav); // Get the first element
$last  = end($arr_nav);   // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) { 
   $first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
   $last['class'] = 'last';
}

Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.

Mac install and open mysql using terminal

This command works for me:

./mysql -u root -p

(PS: I'm working on mac through terminal)

How do I break out of nested loops in Java?

You can use labels:

label1: 
for (int i = 0;;) {
    for (int g = 0;;) {
      break label1;
    }
}

Add placeholder text inside UITextView in Swift?


Floating Placeholder


It's simple, safe and reliable to position a placeholder label above a text view, set its font, color and manage placeholder visibility by tracking changes to the text view's character count.

Swift 3:

class NotesViewController : UIViewController, UITextViewDelegate {

    @IBOutlet var textView : UITextView!
    var placeholderLabel : UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.delegate = self
        placeholderLabel = UILabel()
        placeholderLabel.text = "Enter some text..."
        placeholderLabel.font = UIFont.italicSystemFont(ofSize: (textView.font?.pointSize)!)
        placeholderLabel.sizeToFit()
        textView.addSubview(placeholderLabel)
        placeholderLabel.frame.origin = CGPoint(x: 5, y: (textView.font?.pointSize)! / 2)
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.isHidden = !textView.text.isEmpty
    }

    func textViewDidChange(_ textView: UITextView) {
        placeholderLabel.isHidden = !textView.text.isEmpty
    }
}

Swift 2: Same, except:italicSystemFontOfSize(textView.font.pointSize), UIColor.lightGrayColor


Opening A Specific File With A Batch File?

start wgnplot.exe "c:\path to file to open\foo.dat"

Including another class in SCSS

Looks like @mixin and @include are not needed for a simple case like this.

One can just do:

.myclass {
  font-weight: bold;
  font-size: 90px;
}

.myotherclass {
  @extend .myclass;
  color: #000000;
}

Eclipse DDMS error "Can't bind to local 8600 for debugger"

I had a similar problem on OSX. It just so happens I had opened two instances of Eclipse so I could refer to some code in another workspace. Eventually I realized the two instances might be interfering with each other so I closed one. After that, I'm no longer seeing the "Can't bind..." error.

What is the shortest function for reading a cookie by name in JavaScript?

code from google analytics ga.js

function c(a){
    var d=[],
        e=document.cookie.split(";");
    a=RegExp("^\\s*"+a+"=\\s*(.*?)\\s*$");
    for(var b=0;b<e.length;b++){
        var f=e[b].match(a);
        f&&d.push(f[1])
    }
    return d
}

Removing u in list

u'AB' is just a text representation of the corresponding Unicode string. Here're several methods that create exactly the same Unicode string:

L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
print u", ".join(L)

Output

AB, AB, AB, AB

There is no u'' in memory. It is just the way to represent the unicode object in Python 2 (how you would write the Unicode string literal in a Python source code). By default print L is equivalent to print "[%s]" % ", ".join(map(repr, L)) i.e., repr() function is called for each list item:

print L
print "[%s]" % ", ".join(map(repr, L))

Output

[u'AB', u'AB', u'AB', u'AB']
[u'AB', u'AB', u'AB', u'AB']

If you are working in a REPL then a customizable sys.displayhook is used that calls repr() on each object by default:

>>> L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
>>> L
[u'AB', u'AB', u'AB', u'AB']
>>> ", ".join(L)
u'AB, AB, AB, AB'
>>> print ", ".join(L)
AB, AB, AB, AB

Don't encode to bytes. Print unicode directly.


In your specific case, I would create a Python list and use json.dumps() to serialize it instead of using string formatting to create JSON text:

#!/usr/bin/env python2
import json
# ...
test = [dict(email=player.email, gem=player.gem)
        for player in players]
print test
print json.dumps(test)

Output

[{'email': u'[email protected]', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test1', 'gem': 0}]
[{"email": "[email protected]", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test1", "gem": 0}]

Converting a JToken (or string) to a given Type

System.Convert.ChangeType(jtoken.ToString(), targetType);

or

JsonConvert.DeserializeObject(jtoken.ToString(), targetType);

--EDIT--

Uzair, Here is a complete example just to show you they work

string json = @"{
        ""id"" : 77239923,
        ""username"" : ""UzEE"",
        ""email"" : ""[email protected]"",
        ""name"" : ""Uzair Sajid"",
        ""twitter_screen_name"" : ""UzEE"",
        ""join_date"" : ""2012-08-13T05:30:23Z05+00"",
        ""timezone"" : 5.5,
        ""access_token"" : {
            ""token"" : ""nkjanIUI8983nkSj)*#)(kjb@K"",
            ""scope"" : [ ""read"", ""write"", ""bake pies"" ],
            ""expires"" : 57723
        },
        ""friends"" : [{
            ""id"" : 2347484,
            ""name"" : ""Bruce Wayne""
        },
        {
            ""id"" : 996236,
            ""name"" : ""Clark Kent""
        }]
    }";

var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(int);
var i1 = System.Convert.ChangeType(obj["id"].ToString(), type);
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

Linking static libraries to other static libraries

On Linux or MingW, with GNU toolchain:

ar -M <<EOM
    CREATE libab.a
    ADDLIB liba.a
    ADDLIB libb.a
    SAVE
    END
EOM
ranlib libab.a

Of if you do not delete liba.a and libb.a, you can make a "thin archive":

ar crsT libab.a liba.a libb.a

On Windows, with MSVC toolchain:

lib.exe /OUT:libab.lib liba.lib libb.lib

How to maintain state after a page refresh in React.js?

We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.

When the user selects an option, we can push the value of that onto the current route with:

history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});

pathname can be the current path. In your case params would look something like:

{
  selectedOption: 5
}

Then at the top level of the React tree, React Router will update the props of that component with a prop of location.search which is the encoded value we set earlier, so there will be something in componentWillReceiveProps like:

params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});

Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.

React Router: https://github.com/reactjs/react-router

History: https://github.com/ReactTraining/history

The query string library: https://github.com/ljharb/qs

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Try this:

ORDER BY 1, 2

OR

ORDER BY rsc.RadioServiceCodeId, rsc.RadioServiceCode + ' - ' + rsc.RadioService

How can I check if char* variable points to empty string?

My preferred method:

if (*ptr == 0) // empty string

Probably more common:

if (strlen(ptr) == 0) // empty string

Change keystore password from no password to a non blank password

On my system the password is 'changeit'. On blank if I hit enter then it complains about short password. Hope this helps

enter image description here

how to check and set max_allowed_packet mysql variable

max_allowed_packet is set in mysql config, not on php side

[mysqld]
max_allowed_packet=16M 

You can see it's curent value in mysql like this:

SHOW VARIABLES LIKE 'max_allowed_packet';

You can try to change it like this, but it's unlikely this will work on shared hosting:

SET GLOBAL max_allowed_packet=16777216;

You can read about it here http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html

EDIT

The [mysqld] is necessary to make the max_allowed_packet working since at least mysql version 5.5.

Recently setup an instance on AWS EC2 with Drupal and Solr Search Engine, which required 32M max_allowed_packet. It you set the value under [mysqld_safe] (which is default settings came with the mysql installation) mode in /etc/my.cnf, it did no work. I did not dig into the problem. But after I change it to [mysqld] and restarted the mysqld, it worked.

PHP ini file_get_contents external url

Complementing Aillyn's answer, you could use a function like the one below to mimic the behavior of file_get_contents:

function get_content($URL){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_URL, $URL);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
}

echo get_content('http://example.com');

How do I drop a foreign key constraint only if it exists in sql server?

ALTER TABLE [dbo].[TableName]
    DROP CONSTRAINT FK_TableName_TableName2

Check if table exists without using "select from"

None of the options except SELECT doesn't allow database name as used in SELECT, so I wrote this:

SELECT COUNT(*) AS cnt FROM information_schema.TABLES 
WHERE CONCAT(table_schema,".",table_name)="db_name.table_name";

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

Angular 2 execute script after template render

Actually ngAfterViewInit() will initiate only once when the component initiate.

If you really want a event triggers after the HTML element renter on the screen then you can use ngAfterViewChecked()

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

Yes, it is security issue. Check folder permissions and service account under which SQL server 2008 starts.

Disallow Twitter Bootstrap modal window from closing

Kind of like @AymKdn's answer, but this will allow you to change the options without re-initializing the modal.

$('#myModal').data('modal').options.keyboard = false;

Or if you need to do multiple options, JavaScript's with comes in handy here!

with ($('#myModal').data("modal").options) {
    backdrop = 'static';
    keyboard = false;
}

If the modal is already open, these options will only take effect the next time the modal is opened.

Difference between AutoPostBack=True and AutoPostBack=False?

Taken from http://www.dotnetspider.com/resources/189-AutoPostBack-What-How-works.aspx:

Autopostback is the mechanism by which the page will be posted back to the server automatically based on some events in the web controls. In some of the web controls, the property called auto post back, if set to true, will send the request to the server when an event happens in the control.

Whenever we set the autopostback attribute to true on any of the controls, the .NET framework will automatically insert a few lines of code into the HTML generated to implement this functionality.

  1. A JavaScript method with name __doPostBack (eventtarget, eventargument)
  2. Two hidden variables with name __EVENTTARGET and __EVENTARGUMENT
  3. OnChange JavaScript event to the control

Bootstrap 3 and Youtube in Modal

_x000D_
_x000D_
$('#videoLink').click(function () {_x000D_
    var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';_x000D_
    // $('#introVideo').modal('show'); <-- remove this line_x000D_
    $('#introVideo iframe').attr('src', src);_x000D_
});_x000D_
_x000D_
$('#introVideo button.close').on('hidden.bs.modal', function () {_x000D_
    $('#introVideo iframe').removeAttr('src');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- triggering Link -->_x000D_
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>_x000D_
_x000D_
<!-- Intro video -->_x000D_
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">_x000D_
  <div class="modal-dialog modal-lg">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <div class="embed-responsive embed-responsive-16by9">_x000D_
            <iframe class="embed-responsive-item allowfullscreen"></iframe>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The application was unable to start correctly (0xc000007b)

I tried all the things specified here and found yet another answer. I had to compile my application with 32-bit DLLs. I had built the libraries both in 32-bit and 64-bit but had my PATH set to 64-bit libraries. After I recompiled my application (with a number of changes in my code as well) I got this dreaded error and struggled for two days. Finally, after trying a number of other things, I changed my PATH to have the 32-bit DLLs before the 64-bit DLLs (they have the same names). And it worked. I am just adding it here for completeness.

Why is NULL undeclared?

Are you including "stdlib.h" or "cstdlib" in this file? NULL is defined in stdlib.h/cstdlib

#include <stdlib.h>

or

#include <cstdlib>  // This is preferrable for c++

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!

How to get the Android Emulator's IP address?

Within the code of my app I can get the running device IP andress easily like beolow:

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

SQL RANK() versus ROW_NUMBER()

This article covers an interesting relationship between ROW_NUMBER() and DENSE_RANK() (the RANK() function is not treated specifically). When you need a generated ROW_NUMBER() on a SELECT DISTINCT statement, the ROW_NUMBER() will produce distinct values before they are removed by the DISTINCT keyword. E.g. this query

SELECT DISTINCT
  v, 
  ROW_NUMBER() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number

... might produce this result (DISTINCT has no effect):

+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a |          1 |
| a |          2 |
| a |          3 |
| b |          4 |
| c |          5 |
| c |          6 |
| d |          7 |
| e |          8 |
+---+------------+

Whereas this query:

SELECT DISTINCT
  v, 
  DENSE_RANK() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number

... produces what you probably want in this case:

+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a |          1 |
| b |          2 |
| c |          3 |
| d |          4 |
| e |          5 |
+---+------------+

Note that the ORDER BY clause of the DENSE_RANK() function will need all other columns from the SELECT DISTINCT clause to work properly.

The reason for this is that logically, window functions are calculated before DISTINCT is applied.

All three functions in comparison

Using PostgreSQL / Sybase / SQL standard syntax (WINDOW clause):

SELECT
  v,
  ROW_NUMBER() OVER (window) row_number,
  RANK()       OVER (window) rank,
  DENSE_RANK() OVER (window) dense_rank
FROM t
WINDOW window AS (ORDER BY v)
ORDER BY v

... you'll get:

+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a |          1 |    1 |          1 |
| a |          2 |    1 |          1 |
| a |          3 |    1 |          1 |
| b |          4 |    4 |          2 |
| c |          5 |    5 |          3 |
| c |          6 |    5 |          3 |
| d |          7 |    7 |          4 |
| e |          8 |    8 |          5 |
+---+------------+------+------------+

Find integer index of rows with NaN in pandas dataframe

One line solution. However it works for one column only.

df.loc[pandas.isna(df["b"]), :].index

How to check the maximum number of allowed connections to an Oracle database?

There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e.

The number of sessions the database was configured to allow

SELECT name, value 
  FROM v$parameter
 WHERE name = 'sessions'

The number of sessions currently active

SELECT COUNT(*)
  FROM v$session

As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM.

Why not use Double or Float to represent currency?

American currency can easily be represented with dollar and cent amounts. Integers are 100% precise, while floating point binary numbers do not exactly match floating point decimals.

Spring RequestMapping for controllers that produce and consume JSON

There are 2 annotations in Spring: @RequestBody and @ResponseBody. These annotations consumes, respectively produces JSONs. Some more info here.

How to generate List<String> from SQL query?

Or a nested List (okay, the OP was for a single column and this is for multiple columns..):

        //Base list is a list of fields, ie a data record
        //Enclosing list is then a list of those records, ie the Result set
        List<List<String>> ResultSet = new List<List<String>>();

        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand(qString, connection);

            // Create and execute the DataReader..
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                var rec = new List<string>();
                for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
                {                      
                    rec.Add(reader.GetString(i));
                }
                ResultSet.Add(rec);

            }
        }

How to use a DataAdapter with stored procedure and parameter

I got it!...hehe

protected DataTable RetrieveEmployeeSubInfo(string employeeNo)
        {
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            DataTable dt = new DataTable();
            try
            {
                cmd = new SqlCommand("RETRIEVE_EMPLOYEE", pl.ConnOpen());
                cmd.Parameters.Add(new SqlParameter("@EMPLOYEENO", employeeNo));
                cmd.CommandType = CommandType.StoredProcedure;
                da.SelectCommand = cmd;
                da.Fill(dt);
                dataGridView1.DataSource = dt;
            }
            catch (Exception x)
            {
                MessageBox.Show(x.GetBaseException().ToString(), "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                cmd.Dispose();
                pl.MySQLConn.Close();
            }
            return dt;
        }

Finding the source code for built-in Python functions?

As mentioned by @Jim, the file organization is described here. Reproduced for ease of discovery:

For Python modules, the typical layout is:

Lib/<module>.py
Modules/_<module>.c (if there’s also a C accelerator module)
Lib/test/test_<module>.py
Doc/library/<module>.rst

For extension-only modules, the typical layout is:

Modules/<module>module.c
Lib/test/test_<module>.py
Doc/library/<module>.rst

For builtin types, the typical layout is:

Objects/<builtin>object.c
Lib/test/test_<builtin>.py
Doc/library/stdtypes.rst

For builtin functions, the typical layout is:

Python/bltinmodule.c
Lib/test/test_builtin.py
Doc/library/functions.rst

Some exceptions:

builtin type int is at Objects/longobject.c
builtin type str is at Objects/unicodeobject.c
builtin module sys is at Python/sysmodule.c
builtin module marshal is at Python/marshal.c
Windows-only module winreg is at PC/winreg.c

How can I get the max (or min) value in a vector?

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

int main()
{

    int vector[500];

    vector[0] = 100;
    vector[1] = 2;
    vector[2] = 1239;
    vector[3] = 5;
    vector[4] = 10;
    vector[5] = 1;
    vector[6] = 123;
    vector[7] = 1000;
    vector[8] = 9;
    vector[9] = 123;
    vector[10] = 10;

    int i = 0;

    int winner = vector[0];

    for(i=0;i < 10; i++)
    {
        printf("vector = %d \n", vector[i]);

        if(winner > vector[i])
        {
            printf("winner was %d \n", winner);
            winner = vector[i];
            printf("but now is %d \n", winner);
        }
    }

    printf("the minimu is %d", winner);
}

The complet nooby way... in C

Javascript Regexp dynamic generation from variables?

You have to use RegExp:

str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));

When I'm concatenating strings, all slashes are gone.

If you have a backslash in your pattern to escape a special regex character, (like \(), you have to use two backslashes in the string (because \ is the escape character in a string): new RegExp('\\(') would be the same as /\(/.

So your patterns have to become:

var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

Looking at the Volley perspective here are some advantages for your requirement:

Volley, on one hand, is totally focused on handling individual, small HTTP requests. So if your HTTP request handling has some quirks, Volley probably has a hook for you. If, on the other hand, you have a quirk in your image handling, the only real hook you have is ImageCache. "It’s not nothing, but it’s not a lot!, either". but it has more other advantages like Once you define your requests, using them from within a fragment or activity is painless unlike parallel AsyncTasks

Pros and cons of Volley:

So what’s nice about Volley?

  • The networking part isn’t just for images. Volley is intended to be an integral part of your back end. For a fresh project based off of a simple REST service, this could be a big win.

  • NetworkImageView is more aggressive about request cleanup than Picasso, and more conservative in its GC usage patterns. NetworkImageView relies exclusively on strong memory references, and cleans up all request data as soon as a new request is made for an ImageView, or as soon as that ImageView moves offscreen.

  • Performance. This post won’t evaluate this claim, but they’ve clearly taken some care to be judicious in their memory usage patterns. Volley also makes an effort to batch callbacks to the main thread to reduce context switching.

  • Volley apparently has futures, too. Check out RequestFuture if you’re interested.

  • If you’re dealing with high-resolution compressed images, Volley is the only solution here that works well.

  • Volley can be used with Okhttp (New version of Okhttp supports NIO for better performance )

  • Volley plays nice with the Activity life cycle.

Problems With Volley:
Since Volley is new, few things are not supported yet, but it's fixed.

  1. Multipart Requests (Solution: https://github.com/vinaysshenoy/enhanced-volley)

  2. status code 201 is taken as an error, Status code from 200 to 207 are successful responses now.(Fixed: https://github.com/Vinayrraj/CustomVolley)

    Update: in latest release of Google volley, the 2XX Status codes bug is fixed now!Thanks to Ficus Kirkpatrick!

  3. it's less documented but many of the people are supporting volley in github, java like documentation can be found here. On android developer website, you may find guide for Transmitting Network Data Using Volley. And volley source code can be found at Google Git

  4. To solve/change Redirect Policy of Volley Framework use Volley with OkHTTP (CommonsWare mentioned above)

Also you can read this Comparing Volley's image loading with Picasso

Retrofit:

It's released by Square, This offers very easy to use REST API's (Update: Voila! with NIO support)

Pros of Retrofit:

  • Compared to Volley, Retrofit's REST API code is brief and provides excellent API documentation and has good support in communities! It is very easy to add into the projects.

  • We can use it with any serialization library, with error handling.

Update: - There are plenty of very good changes in Retrofit 2.0.0-beta2

  • version 1.6 of Retrofit with OkHttp 2.0 is now dependent on Okio to support java.io and java.nio which makes it much easier to access, store and process your data using ByteString and Buffer to do some clever things to save CPU and memory. (FYI: This reminds me of the Koush's OIN library with NIO support!) We can use Retrofit together with RxJava to combine and chain REST calls using rxObservables to avoid ugly callback chains (to avoid callback hell!!).

Cons of Retrofit for version 1.6:

  • Memory related error handling functionality is not good (in older versions of Retrofit/OkHttp) not sure if it's improved with the Okio with Java NIO support.

  • Minimum threading assistance can result call back hell if we use this in an improper way.

(All above Cons have been solved in the new version of Retrofit 2.0 beta)

========================================================================

Update:

Android Async vs Volley vs Retrofit performance benchmarks (milliseconds, lower value is better):

Android Async vs Volley vs Retrofit performance benchmarks

(FYI above Retrofit Benchmarks info will improve with java NIO support because the new version of OKhttp is dependent on NIO Okio library)

In all three tests with varying repeats (1 – 25 times), Volley was anywhere from 50% to 75% faster. Retrofit clocked in at an impressive 50% to 90% faster than the AsyncTasks, hitting the same endpoint the same number of times. On the Dashboard test suite, this translated into loading/parsing the data several seconds faster. That is a massive real-world difference. In order to make the tests fair, the times for AsyncTasks/Volley included the JSON parsing as Retrofit does it for you automatically.

RetroFit Wins in benchmark test!

In the end, we decided to go with Retrofit for our application. Not only is it ridiculously fast, but it meshes quite well with our existing architecture. We were able to make a parent Callback Interface that automatically performs error handling, caching, and pagination with little to no effort for our APIs. In order to merge in Retrofit, we had to rename our variables to make our models GSON compliant, write a few simple interfaces, delete functions from the old API, and modify our fragments to not use AsyncTasks. Now that we have a few fragments completely converted, it’s pretty painless. There were some growing pains and issues that we had to overcome, but overall it went smoothly. In the beginning, we ran into a few technical issues/bugs, but Square has a fantastic Google+ community that was able to help us through it.

When to use Volley?!

We can use Volley when we need to load images as well as consuming REST APIs!, network call queuing system is needed for many n/w request at the same time! also Volley has better memory related error handling than Retrofit!

OkHttp can be used with Volley, Retrofit uses OkHttp by default! It has SPDY support, connection pooling, disk caching, transparent compression! Recently, it has got some support of java NIO with Okio library.

Source, credit: volley-vs-retrofit by Mr. Josh Ruesch

Note: About streaming it depends on what type of streaming you want like RTSP/RTCP.

Make an HTTP request with android

With a thread:

private class LoadingThread extends Thread {
    Handler handler;

    LoadingThread(Handler h) {
        handler = h;
    }
    @Override
    public void run() {
        Message m = handler.obtainMessage();
        try {
            BufferedReader in = 
                new BufferedReader(new InputStreamReader(url.openStream()));
            String page = "";
            String inLine;

            while ((inLine = in.readLine()) != null) {
                page += inLine;
            }

            in.close();
            Bundle b = new Bundle();
            b.putString("result", page);
            m.setData(b);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        handler.sendMessage(m);
    }
}

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Download whatever configuration script that your browser is using.

the script would have various host:port configuration. based on the domain you want to connect , one of the host:port is selected by the borwser.

in the eclipse network setting you can try to put on of the host ports and see if that works.

worked for me.

the config script looks like,

if (isPlainHostName(host))
    return "DIRECT";
else if (dnsDomainIs(host, "<***sample host name *******>"))
    return "PROXY ***some ip*****; DIRECT";
else if (dnsDomainIs(host, "address.com")
        || dnsDomainIs(host, "adress2..com")
        || dnsDomainIs(host, "address3.com")
        || dnsDomainIs(host, "address4.com")        
    return "PROXY <***some proxyhost****>:8080";

you would need to look for the host port in the return statement.

Connection failed: SQLState: '01000' SQL Server Error: 10061

I had the same error which was coming and dont need to worry about this error, just restart the server and restart the SQL services. This issue comes when there is low disk space issue and system will go into hung state and then the sql services will stop automatically.

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

ECLIPSE PHOTON ON MAC

  1. Get your current JAVA_HOME path /Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home

  2. open /Users/you/eclipse/jee-photon/Eclipse.app/Contents/Eclipse/ and click on package content. Then open eclipse.ini file using any text file editor.

  3. Edit your -VM argument as below( Make sure the Java Path is same as $JAVA_HOME)

-vm

/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/bin

  1. save and start your eclipse.

How to avoid scientific notation for large numbers in JavaScript?

I had the same issue with oracle returning scientic notation, but I needed the actual number for a url. I just used a PHP trick by subtracting zero, and I get the correct number.

for example 5.4987E7 is the val.

newval = val - 0;

newval now equals 54987000

SQL Server : How to test if a string has only digit characters

Use Not Like

where some_column NOT LIKE '%[^0-9]%'

Demo

declare @str varchar(50)='50'--'asdarew345'

select 1 where @str NOT LIKE '%[^0-9]%'

Update elements in a JSONObject

Hello I can suggest you universal method. use recursion.

    public static JSONObject function(JSONObject obj, String keyMain,String valueMain, String newValue) throws Exception {
    // We need to know keys of Jsonobject
    JSONObject json = new JSONObject()
    Iterator iterator = obj.keys();
    String key = null;
    while (iterator.hasNext()) {
        key = (String) iterator.next();
        // if object is just string we change value in key
        if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
            if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
                // put new value
                obj.put(key, newValue);
                return obj;
            }
        }

        // if it's jsonobject
        if (obj.optJSONObject(key) != null) {
            function(obj.getJSONObject(key), keyMain, valueMain, newValue);
        }

        // if it's jsonarray
        if (obj.optJSONArray(key) != null) {
            JSONArray jArray = obj.getJSONArray(key);
            for (int i=0;i<jArray.length();i++) {
                    function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
            }
        }
    }
    return obj;
}

It should work. If you have questions, go ahead.. I'm ready.

How do I find out my root MySQL password?

It is actually very simple. You don't have to go through a lot of stuff. Just run the following command in terminal and follow on-screen instructions.

sudo mysql_secure_installation

Github: error cloning my private repository

I received this error after moving git across hard drives. Deleting and reinstalling in the new location fixed things

Unix's 'ls' sort by name

The beauty of *nix tools is you can combine them:

ls -l | sort -k9,9

The output of ls -l will look like this

-rw-rw-r-- 1 luckydonald luckydonald  532 Feb 21  2017 Makefile
-rwxrwxrwx 1 luckydonald luckydonald 4096 Nov 17 23:47 file.txt

So with 9,9 you sort column 9 up to the column 9, being the file names. You have to provide where to stop, which is the same column in this case. The columns start with 1.

Also, if you want to ignore upper/lower case, add --ignore-case to the sort command.

Decoding JSON String in Java

This is the best and easiest code:

public class test
{
    public static void main(String str[])
    {
        String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject newJSON = jsonObject.getJSONObject("stat");
        System.out.println(newJSON.toString());
        jsonObject = new JSONObject(newJSON.toString());
        System.out.println(jsonObject.getString("rcv"));
       System.out.println(jsonObject.getJSONArray("argv"));
    }
}

The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.

You can download the zip. And then create a package in your project with org.json as name. and paste all the downloaded codes there, and have fun.

I feel this to be the best and the most easiest JSON Decoding.

twitter bootstrap text-center when in xs mode

Bootstrap 4

<div class="col-md-9 col-xs-12 text-md-left text-center">md left, xs center</div>
<div class="col-md-9 col-xs-12 text-md-right text-center">md right, xs center</div>

How to exit if a command failed?

Using exit directly may be tricky as the script may be sourced from other places (e.g. from terminal). I prefer instead using subshell with set -e (plus errors should go into cerr, not cout) :

set -e
ERRCODE=0
my_command || ERRCODE=$?
test $ERRCODE == 0 ||
    (>&2 echo "My command failed ($ERRCODE)"; exit $ERRCODE)

How to hash some string with sha256 in Java?

You can use MessageDigest in the following way:

public static String getSHA256(String data){
    StringBuffer sb = new StringBuffer();
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data.getBytes());
        byte byteData[] = md.digest();

        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
    } catch(Exception e){
        e.printStackTrace();
    }
    return sb.toString();
}

Inserting an item in a Tuple

t = (1,2,3,4,5)

t= t + (6,7)

output :

(1,2,3,4,5,6,7)

Vue-router redirect on page not found (404)

This answer may come a bit late but I have found an acceptable solution. My approach is a bit similar to @Mani one but I think mine is a bit more easy to understand.

Putting it into global hook and into the component itself are not ideal, global hook checks every request so you will need to write a lot of conditions to check if it should be 404 and window.location.href in the component creation is too late as the request has gone into the component already and then you take it out.

What I did is to have a dedicated url for 404 pages and have a path * that for everything that not found.

{ path: '/:locale/404', name: 'notFound', component: () => import('pages/Error404.vue') },
{ path: '/:locale/*', 
  beforeEnter (to) {
    window.location = `/${to.params.locale}/404`
  }
}

You can ignore the :locale as my site is using i18n so that I can make sure the 404 page is using the right language.

On the side note, I want to make sure my 404 page is returning httpheader 404 status code instead of 200 when page is not found. The solution above would just send you to a 404 page but you are still getting 200 status code. To do this, I have my nginx rule to return 404 status code on location /:locale/404

server {
    listen                      80;
    server_name                 localhost;

    error_page  404 /index.html;
    location ~ ^/.*/404$ {
      root   /usr/share/nginx/html;
      internal;
    }

    location / {
      root   /usr/share/nginx/html;
      index  index.html index.htm;
      try_files $uri $uri/ @rewrites;
    }

    location @rewrites {
      rewrite ^(.+)$ /index.html last;
    }

    location = /50x.html {
      root   /usr/share/nginx/html;
    }
}

Set background image in CSS using jquery

Use :

 $(this).parent().css("background-image", "url(/images/r-srchbg_white.png) no-repeat;");

instead of

 $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat;");

More examples you cand see here

How do I register a .NET DLL file in the GAC?

  • Run Developer Command Prompt For V2012 or any version installed in your system

  • gacutil /i pathofDll

  • Enter

Done!!!

React - Preventing Form Submission

componentDidUpdate(){               
    $(".wpcf7-submit").click( function(event) {
        event.preventDefault();
    })
}

You can use componentDidUpdate and event.preventDefault() to disable form submission.As react does not support return false.

Accessing Session Using ASP.NET Web API

one thing need to mention on @LachlanB 's answer.

protected void Application_PostAuthorizeRequest()
    {
        if (IsWebApiRequest())
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
    }

If you omit the line if (IsWebApiRequest())

The whole site will have page loading slowness issue if your site is mixed with web form pages.

How to enable assembly bind failure logging (Fusion) in .NET

For those who are a bit lazy, I recommend running this as a bat file for when ever you want to enable it:

reg add "HKLM\Software\Microsoft\Fusion" /v EnableLog /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v ForceLog /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogFailures /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogResourceBinds /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogPath /t REG_SZ /d C:\FusionLog\

if not exist "C:\FusionLog\" mkdir C:\FusionLog

How do I use the new computeIfAbsent function?

Another example. When building a complex map of maps, the computeIfAbsent() method is a replacement for map's get() method. Through chaining of computeIfAbsent() calls together, missing containers are constructed on-the-fly by provided lambda expressions:

  // Stores regional movie ratings
  Map<String, Map<Integer, Set<String>>> regionalMovieRatings = new TreeMap<>();

  // This will throw NullPointerException!
  regionalMovieRatings.get("New York").get(5).add("Boyhood");

  // This will work
  regionalMovieRatings
    .computeIfAbsent("New York", region -> new TreeMap<>())
    .computeIfAbsent(5, rating -> new TreeSet<>())
    .add("Boyhood");

Defining a HTML template to append using JQuery

Very good answer from DevWL about using the native HTML5 template element. To contribute to this good question from the OP I would like to add on how to use this template element using jQuery, for example:

$($('template').html()).insertAfter( $('#somewhere_else') );

The content of the template is not html, but just treated as data, so you need to wrap the content into a jQuery object to then access jQuery's methods.

How to sign in kubernetes dashboard?

Combining two answers: 49992698 and 47761914 :

# Create service account
kubectl create serviceaccount -n kube-system cluster-admin-dashboard-sa

# Bind ClusterAdmin role to the service account
kubectl create clusterrolebinding -n kube-system cluster-admin-dashboard-sa \
  --clusterrole=cluster-admin \
  --serviceaccount=kube-system:cluster-admin-dashboard-sa

# Parse the token
TOKEN=$(kubectl describe secret -n kube-system $(kubectl get secret -n kube-system | awk '/^cluster-admin-dashboard-sa-token-/{print $1}') | awk '$1=="token:"{print $2}')

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

Asp.net Hyperlink control equivalent to <a href="#"></a>

If you need to access this as a server-side control (e.g. you want to add data attributes to a link, as I did), then there is a way to do what you want; however, you don't use the Hyperlink or HtmlAnchor controls to do it. Create a literal control and then add in "Your Text" as the text for the literal control (or whatever else you need to do that way). It's hacky, but it works.

What is an idempotent operation?

Idempotence means that applying an operation once or applying it multiple times has the same effect.

Examples:

  • Multiplication by zero. No matter how many times you do it, the result is still zero.
  • Setting a boolean flag. No matter how many times you do it, the flag stays set.
  • Deleting a row from a database with a given ID. If you try it again, the row is still gone.

For pure functions (functions with no side effects) then idempotency implies that f(x) = f(f(x)) = f(f(f(x))) = f(f(f(f(x)))) = ...... for all values of x

For functions with side effects, idempotency furthermore implies that no additional side effects will be caused after the first application. You can consider the state of the world to be an additional "hidden" parameter to the function if you like.

Note that in a world where you have concurrent actions going on, you may find that operations you thought were idempotent cease to be so (for example, another thread could unset the value of the boolean flag in the example above). Basically whenever you have concurrency and mutable state, you need to think much more carefully about idempotency.

Idempotency is often a useful property in building robust systems. For example, if there is a risk that you may receive a duplicate message from a third party, it is helpful to have the message handler act as an idempotent operation so that the message effect only happens once.

How to add favicon.ico in ASP.NET site

    <link rel="shortcut icon" href="@Url.Content("~/images/")favicon.ico" type="image/x-icon"/ >

This works for me in MVC4 application favicon image is placed in the images folder and it will traverse from root directory to images and find favicon.ico bingo!

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

Visual Studio 2015, Windows 10, project source control was managed in TFS Online.

None of this worked form me, issue appeared after a reformat of Windows 10 and subsequent reinstall of VStudio 2015. I mapped projects to the same folder (residual folders and files were still there.)

Deleting the entire old project (specifically the .VS) and then remapping it fixed everything.

How to add header to a dataset in R?

You can do the following:

Load the data:

test <- read.csv(
          "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
          header=FALSE)

Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.

Add names to the different columns in the data.frame

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

or alternative and faster as I understand (not reloading the entire dataset):

colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

Remove last specific character in a string c#

Try string.Remove();

string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);

How do I escape spaces in path for scp copy in Linux?

Sorry for using this Linux question to put this tip for Powershell on Windows 10: the space char escaping with backslashes or surrounding with quotes didn't work for me in this case. Not efficient, but I solved it using the "?" char instead:

for the file "tasks.txt Jun-22.bkp" I downloaded it using "tasks.txt?Jun-22.bkp"

How to know which version of Symfony I have?

Use the following command in your Terminal/Command Prompt:

php bin/console --version

This will give you your Symfony Version.

What's the best way to determine the location of the current PowerShell script?

I always use this little snippet which works for PowerShell and ISE the same way:

# Set active path to script-location:
$path = $MyInvocation.MyCommand.Path
if (!$path) {
    $path = $psISE.CurrentFile.Fullpath
}
if ($path) {
    $path = Split-Path $path -Parent
}
Set-Location $path

Check if decimal value is null

You can also create a handy utility functions to handle values from DB in cases like these. Ex. Below is the function which gives you Nullable Decimal from object type.

    public static decimal? ToNullableDecimal(object val)
    {
        if (val is DBNull ||
            val == null)
        {
            return null;
        }
        if (val is string &&
            ((string)val).Length == 0)
        {
            return null;
        }
        return Convert.ToDecimal(val);
    } 

Iptables setting multiple multiports in one rule

As a workaround to this limitation, I use two rules to cover all the cases.

For example, if I want to allow or deny these 18 ports:

465,110,995,587,143,11025,20,21,22,26,80,443,3000,10000,7080,8080,3000,5666

I use the below rules:

iptables -A INPUT -p tcp -i eth0 -m multiport --dports 465,110,995,587,143,11025,20,21,22,26,80,443 -j ACCEPT

iptables -A INPUT -p tcp -i eth0 -m multiport --dports 3000,10000,7080,8080,3000,5666 -j ACCEPT

The above rules should work for your scenario also. You can create another rule if you hit 15 ports limit on both first and second rule.

Can I get "&&" or "-and" to work in PowerShell?

Very old question, but for the newcomers: maybe the PowerShell version (similar but not equivalent) that the question is looking for, is to use -and as follows:

(build_command) -and (run_tests_command)

What is the use of the JavaScript 'bind' method?

From the MDN docs on Function.prototype.bind() :

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

So, what does that mean?!

Well, let's take a function that looks like this :

var logProp = function(prop) {
    console.log(this[prop]);
};

Now, let's take an object that looks like this :

var Obj = {
    x : 5,
    y : 10
};

We can bind our function to our object like this :

Obj.log = logProp.bind(Obj);

Now, we can run Obj.log anywhere in our code :

Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10

This works, because we bound the value of this to our object Obj.


Where it really gets interesting, is when you not only bind a value for this, but also for its argument prop :

Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');

We can now do this :

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10

Unlike with Obj.log, we do not have to pass x or y, because we passed those values when we did our binding.

Concatenate multiple result rows of one column into one, group by another column

Simpler with the aggregate function string_agg() (Postgres 9.0 or later):

SELECT movie, string_agg(actor, ', ') AS actor_list
FROM   tbl
GROUP  BY 1;

The 1 in GROUP BY 1 is a positional reference and a shortcut for GROUP BY movie in this case.

string_agg() expects data type text as input. Other types need to be cast explicitly (actor::text) - unless an implicit cast to text is defined - which is the case for all other character types (varchar, character, "char"), and some other types.

As isapir commented, you can add an ORDER BY clause in the aggregate call to get a sorted list - should you need that. Like:

SELECT movie, string_agg(actor, ', ' ORDER BY actor) AS actor_list
FROM   tbl
GROUP  BY 1;

But it's typically faster to sort rows in a subquery. See:

Bring a window to the front in WPF

Remember not to put the code that shows that window inside a PreviewMouseDoubleClick handler as the active window will switch back to the window who handled the event. Just put it in the MouseDoubleClick event handler or stop bubbling by setting e.Handled to True.

In my case i was handling the PreviewMouseDoubleClick on a Listview and was not setting the e.Handled = true then it raised the MouseDoubleClick event witch sat focus back to the original window.

A Simple AJAX with JSP example

You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:

var config=document.getElementsByName('configselect').value;

because you have declared only the name attribute in your <select> tag. So you should get this element by name.

After correcting this, it will run without any JavaScript error

Calculating how many minutes there are between two times

Try this

DateTime startTime = varValue
DateTime endTime = varTime

TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (minutes): " + span.TotalMinutes );

Edit: If are you trying 'span.Minutes', this will return only the minutes of timespan [0~59], to return sum of all minutes from this interval, just use 'span.TotalMinutes'.

React Native Responsive Font Size

A slightly different approach worked for me :-

const normalize = (size: number): number => {
  const scale = screenWidth / 320;
  const newSize = size * scale;
  let calculatedSize = Math.round(PixelRatio.roundToNearestPixel(newSize))

  if (PixelRatio.get() < 3)
    return calculatedSize - 0.5
  return calculatedSize
};

Do refer Pixel Ratio as this allows you to better set up the function based on the device density.

Setting background-image using jQuery CSS property

You probably want this (to make it like a normal CSS background-image declaration):

$('myObject').css('background-image', 'url(' + imageUrl + ')');

SVN check out linux

There should be svn utility on you box, if installed:

$ svn checkout http://example.com/svn/somerepo somerepo

This will check out a working copy from a specified repository to a directory somerepo on our file system.

You may want to print commands, supported by this utility:

$ svn help

uname -a output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm or the following command:

$ sudo yum install subversion

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

In addition to @Connor Leech's answer.

If you want to create a new custom typography type of your own, define the following in your css file.

.text-foo {
  .text-emphasis-variant(#FFFFFF);
}

The mixin text-emphasis-variant is defined in Bootstrap's mixins.less file.

PHP Curl And Cookies

You can define different cookies for every user with CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR. Make different file for every user so each one would have it's own cookie-based session on remote server.

What's the difference between session.persist() and session.save() in Hibernate?

Here is the difference:

  1. save:

    1. will return the id/identifier when the object is saved to the database.
    2. will also save when the object is tried to do the same by opening a new session after it is detached.
  2. Persist:

    1. will return void when the object is saved to the database.
    2. will throw PersistentObjectException when tried to save the detached object through a new session.

How to parse SOAP XML?

In your code you are querying for the payment element in default namespace, but in the XML response it is declared as in http://apilistener.envoyservices.com namespace.

So, you are missing a namespace declaration:

$xml->registerXPathNamespace('envoy', 'http://apilistener.envoyservices.com');

Now you can use the envoy namespace prefix in your xpath query:

xpath('//envoy:payment')

The full code would be:

$xml = simplexml_load_string($soap_response);
$xml->registerXPathNamespace('envoy', 'http://apilistener.envoyservices.com');
foreach ($xml->xpath('//envoy:payment') as $item)
{
    print_r($item);
}

Note: I removed the soap namespace declaration as you do not seem to be using it (it is only useful if you would use the namespace prefix in you xpath queries).

How to execute shell command in Javascript

With NodeJS is simple like that! And if you want to run this script at each boot of your server, you can have a look on the forever-service application!

var exec = require('child_process').exec;

exec('php main.php', function (error, stdOut, stdErr) {
    // do what you want!
});

How can I make SQL case sensitive string comparison on MySQL?

mysql is not case sensitive by default, try changing the language collation to latin1_general_cs

Shell command to sum integers, one per line?

The following works in bash:

I=0

for N in `cat numbers.txt`
do
    I=`expr $I + $N`
done

echo $I

Search and get a line in Python

With regular expressions

import re
s="""
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ
"""
>>> items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
...     print x
...
token qwerty

Eclipse hangs on loading workbench

It might also help to try to load and save the workspace with a newer eclipse version:

I am using eclipse 3.8. When starting up the splash screen would hang. There were no error messages in the log. What helped was to open the workspace with eclipse 4.2.2. After opening and closing the workspace I was able to load it again with 3.8.

How to enable curl in xampp?

1) C:\Program Files\xampp\php\php.ini

2) Uncomment the following line on your php.ini file by removing the semicolon.

;extension=php_curl.dll

3) Restart your apache server.

How to open a new file in vim in a new window

If you don't mind using gVim, you can launch a single instance, so that when a new file is opened with it it's automatically opened in a new tab in the currently running instance.

to do this you can write: gVim --remote-tab-silent file

You could always make an alias to this command so that you don't have to type so many words. For example I use linux and bash and in my ~/.bashrc file I have:

alias g='gvim --remote-tab-silent'

so instead of doing $ mate file I do: $ g file

How do I set default values for functions parameters in Matlab?

I've used the inputParser object to deal with setting default options. Matlab won't accept the python-like format you specified in the question, but you should be able to call the function like this:

wave(a,b,n,k,T,f,flag,'fTrue',inline('0'))

After you define the wave function like this:

function wave(a,b,n,k,T,f,flag,varargin)

i_p = inputParser;
i_p.FunctionName = 'WAVE';

i_p.addRequired('a',@isnumeric);
i_p.addRequired('b',@isnumeric);
i_p.addRequired('n',@isnumeric);
i_p.addRequired('k',@isnumeric);
i_p.addRequired('T',@isnumeric);
i_p.addRequired('f',@isnumeric);
i_p.addRequired('flag',@isnumeric); 
i_p.addOptional('ftrue',inline('0'),1);    

i_p.parse(a,b,n,k,T,f,flag,varargin{:});

Now the values passed into the function are available through i_p.Results. Also, I wasn't sure how to validate that the parameter passed in for ftrue was actually an inline function so left the validator blank.

Extracting numbers from vectors of strings

Here's an alternative to Arun's first solution, with a simpler Perl-like regular expression:

as.numeric(gsub("[^\\d]+", "", years, perl=TRUE))

Android Studio cannot resolve R in imported project?

Here's what worked for me in IntelliJ (Not Studio), in addition to the replies presented above:

You need to attach an Android facet to an existing Android module. To do this, select the module from the module list in 'Module Settings', hit the '+' button on top and select 'Android'. See https://www.jetbrains.com/idea/webhelp/enabling-android-support.html.

How do I get specific properties with Get-AdUser

using select-object for example:

Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv" 

How to check postgres user and password?

You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.

Usually, you can login as the postgres user:

Open a Terminal and do sudo su postgres. Now, after entering your admin password, you are able to launch psql and do

CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';

This creates a new admin user. If you want to list the existing users, you could also do

\du

to list all users and then

ALTER USER yourusername WITH PASSWORD 'yournewpass';

Comparing two .jar files

Extract each jar to it's own directory using the jar command with parameters xvf. i.e. jar xvf myjar.jar for each jar.

Then, use the UNIX command diff to compare the two directories. This will show the differences in the directories. You can use diff -r dir1 dir2 two recurse and show the differences in text files in each directory(.xml, .properties, etc).

This will also show if binary class files differ. To actually compare the class files you will have to decompile them as noted by others.

Set up git to pull and push all branches

To see all the branches with out using git branch -a you should execute:

for remote in `git branch -r`; do git branch --track $remote; done
git fetch --all
git pull --all

Now you can see all the branches:

git branch

To push all the branches try:

git push --all

How can I check if a value is of type Integer?

You need to first check if it's a number. If so you can use the Math.Round method. If the result and the original value are equal then it's an integer.

Using scanner.nextLine()

or

int selection = Integer.parseInt(scanner.nextLine());

Android WSDL/SOAP service client

I have just completed a android App about wsdl,i have some tips to append:

1.the most important resource is www.wsdl2code.com

2.you can take you username and password with header, which encoded with Base64,such as :

        String USERNAME = "yourUsername";
    String PASSWORD = "yourPassWord";
    StringBuffer auth = new StringBuffer(USERNAME);
    auth.append(':').append(PASSWORD);
    byte[] raw = auth.toString().getBytes();
    auth.setLength(0);
    auth.append("Basic ");
    org.kobjects.base64.Base64.encode(raw, 0, raw.length, auth);
    List<HeaderProperty> headers = new ArrayList<HeaderProperty>();
    headers.add(new HeaderProperty("Authorization", auth.toString())); // "Basic V1M6"));

    Vectordianzhan response = bydWs.getDianzhans(headers);

3.somethimes,you are not sure either ANDROID code or webserver is wrong, then debug is important.in the sample , catching "XmlPullParserException" ,log "requestDump" and "responseDump"in the exception.additionally, you should catch the IP package with adb.

    try {
    Logg.i(TAG, "2  ");
    Object response = androidHttpTransport.call(SOAP_ACTION, envelope, headers); 
    Logg.i(TAG, "requestDump: " + androidHttpTransport.requestDump);
    Logg.i(TAG, "responseDump: "+ androidHttpTransport.responseDump);
    Logg.i(TAG, "3");
} catch (IOException e) {
    Logg.i(TAG, "IOException");
} 
catch (XmlPullParserException e) {
     Logg.i(TAG, "requestDump: " + androidHttpTransport.requestDump);
     Logg.i(TAG, "responseDump: "+ androidHttpTransport.responseDump);
     Logg.i(TAG, "XmlPullParserException");
     e.printStackTrace();
}

Why are the Level.FINE logging messages not showing?

This solution appears better to me, regarding maintainability and design for change:

  1. Create the logging property file embedding it in the resource project folder, to be included in the jar file:

    # Logging
    handlers = java.util.logging.ConsoleHandler
    .level = ALL
    
    # Console Logging
    java.util.logging.ConsoleHandler.level = ALL
    
  2. Load the property file from code:

    public static java.net.URL retrieveURLOfJarResource(String resourceName) {
       return Thread.currentThread().getContextClassLoader().getResource(resourceName);
    }
    
    public synchronized void initializeLogger() {
       try (InputStream is = retrieveURLOfJarResource("logging.properties").openStream()) {
          LogManager.getLogManager().readConfiguration(is);
       } catch (IOException e) {
          // ...
       }
    }
    

How do I use hexadecimal color strings in Flutter?

If you need Hex color desperately in your application, there is one simple step you can follow:

  1. Convert your Hex color into RGB format simply from here

2. Get your RGB values. 3. In flutter, you have an simple option to use RGB color: Color.fromRGBO(r_value, g_value, b_value, opacity) will do the job for you. 4. Go ahead and tweek O_value to get the color you want.

Class JavaLaunchHelper is implemented in two places

Same error, I upgrade my Junit and resolve it

org.junit.jupiter:junit-jupiter-api:5.0.0-M6

to

org.junit.jupiter:junit-jupiter-api:5.0.0

Java creating .jar file

Often you need to put more into the manifest than what you get with the -e switch, and in that case, the syntax is:

jar -cvfm myJar.jar myManifest.txt myApp.class

Which reads: "create verbose jarFilename manifestFilename", followed by the files you want to include.

Note that the name of the manifest file you supply can be anything, as jar will automatically rename it and put it into the right place within the jar file.

How to get equal width of input and select fields

I tried Gaby's answer (+1) above but it only partially solved my problem. Instead I used the following CSS, where content-box was changed to border-box:

input, select {
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

insert echo into the specific html element like div which has an id or class

You can write the php code in another file and include it in the proper place where you want it.

AJAX is also used to display HTML content that is formed by PHP into a specified HTML tag.

Using jQuery:

$.ajax({url: "test.php"}).done(function( html ) {
    $("#results").append(html);
});

Above code will execute test.php and result will be displayed in the element with id results.

Laravel migration default value

You can simple put the default value using default(). See the example

 $table->enum('is_approved', array('0','1'))->default('0');

I have used enum here and the default value is 0.

How do I check if an object has a specific property in JavaScript?

If the key you are checking is stored in a variable, you can check it like this:

x = {'key': 1};
y = 'key';
x[y];

to_string is not a member of std, says g++ (mingw)

to_string() is only present in c++11 so if c++ version is less use some alternate methods such as sprintf or ostringstream

Simple way to convert datarow array to datatable

For .Net Framework 3.5+

DataTable dt = new DataTable();
DataRow[] dr = dt.Select("Your string");
DataTable dt1 = dr.CopyToDataTable();

But if there is no rows in the array, it can cause the errors such as The source contains no DataRows. Therefore, if you decide to use this method CopyToDataTable(), you should check the array to know it has datarows or not.

if (dr.Length > 0)
    DataTable dt1 = dr.CopyToDataTable();

Reference available at MSDN: DataTableExtensions.CopyToDataTable Method (IEnumerable)

Get the current year in JavaScript

Take this example, you can place it wherever you want to show it without referring to script in the footer or somewhere else like other answers

<script>new Date().getFullYear()>document.write(new Date().getFullYear());</script>

Copyright note on the footer as an example

Copyright 2010 - <script>new Date().getFullYear()>document.write(new Date().getFullYear());</script>

How to install older version of node.js on Windows?

Just uninstall whatever node version you have in your system. Then go to this site https://nodejs.org/download/release/ and choose your desired version like for me its like v7.0.0/ and click on that go get .msi file of that. Finally you will get installer in your system, so install it. It will solve all your problems.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I was facing the same issue. In my case, I had a dependency of httpclient with an older version while sendgrid required a newer version of httpclient. Just make sure that the version of httpclient is correct in your dependencies and it would work fine.

Git says remote ref does not exist when I delete remote branch

git branch -a will list the branches in your local and not the branches in your remote.

And the error error: unable to delete 'remotes/origin/test': remote ref does not exist means you don't have a branch in that name in your remote but the branch exists in your local.

How to replace specific values in a oracle database column?

I'm using Version 4.0.2.15 with Build 15.21

For me I needed this:

UPDATE table_name SET column_name = REPLACE(column_name,"search str","replace str");

Putting t.column_name in the first argument of replace did not work.

What's the difference between window.location and document.location in JavaScript?

It's rare to see the difference nowadays because html 5 don't support framesets anymore. But back at the time we have frameset, document.location would redirect only the frame in which code is being executed, and window.location would redirect the entire page.

What is the difference between "expose" and "publish" in Docker?

EXPOSE is used to map local port container port ie : if you specify expose in docker file like

EXPOSE 8090

What will does it will map localhost port 8090 to container port 8090

How to set aliases in the Git Bash for Windows?

There is two easy way to set the alias.

  1. Using Bash
  2. Updating .gitconfig file

Using Bash

Open bash terminal and type git command. For instance:

$ git config --global alias.a add
$ git config --global alias.aa 'add .'
$ git config --global alias.cm 'commit -m'
$ git config --global alias.s status
---
---

It will eventually add those aliases on .gitconfig file.

Updating .gitconfig file

Open .gitconfig file located at 'C:\Users\username\.gitconfig' in Windows environment. Then add following lines:

[alias]  
a = add  
aa = add . 
cm = commit -m 
gau = add --update 
au = add --update
b = branch
---
---

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

In case you are using Eclipse you might try http4e

How to abort makefile if variable not set?

Use the shell error handling for unset variables (note the double $):

$ cat Makefile
foo:
        echo "something is set to $${something:?}"

$ make foo
echo "something is set to ${something:?}"
/bin/sh: something: parameter null or not set
make: *** [foo] Error 127


$ make foo something=x
echo "something is set to ${something:?}"
something is set to x

If you need a custom error message, add it after the ?:

$ cat Makefile
hello:
        echo "hello $${name:?please tell me who you are via \$$name}"

$ make hello
echo "hello ${name:?please tell me who you are via \$name}"
/bin/sh: name: please tell me who you are via $name
make: *** [hello] Error 127

$ make hello name=jesus
echo "hello ${name:?please tell me who you are via \$name}"
hello jesus

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

There's no reason to use setRawInputType(), just use setInputType(). However, you have to combine the class and flags with the OR operator:

edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

How can I get last characters of a string

Don't use .substr(). Use the .slice() method instead because it is cross browser compatible (see IE).

_x000D_
_x000D_
const id = "ctl03_Tabs1";_x000D_
console.log(id.slice(id.length - 5)); //Outputs: Tabs1_x000D_
console.log(id.slice(id.length - 1)); //Outputs: 1
_x000D_
_x000D_
_x000D_

substr() with negative value not working in IE

Can Android Studio be used to run standard Java projects?

I found a somewhat hacky, annoying and not-completely-sure-it-always-works solution to this. I wanted to share in case someone else finds it useful.

In Android Studio, you can right-click a class with a main method and select "Run .main()". This will create a new Run configuration for YourClass, although it won't quite work: it will be missing some classpath entries.

In order to fix the missing classpath entries, go into the Project Structure and manually add the output folder location for your module and any other module dependencies that you need, like so:

  • File -> Project Structure ...
  • Select "Modules" in the Project Settings panel on the left-column panel
  • Select your module on the list of modules in the middle-column panel
  • Select the "Dependencies" tab on the right-column panel

And then for the module where you have your Java application as well as for each of the module dependencies you need: - Click "+" -> "Jars or directories" on the far right of the right-column panel - Navigate to the output folder of the module (e.g.: my_module/build/classes/main/java) and click "OK" - On the new entry to the Dependencies list, on the far right, change the select box from "Compile" to "Runtime"

After this, you should be able to execute the Run configuration you just created to run the simple Java application.

One thing to note is that, for my particular [quite involved] Android Studio project set-up, I have to manually build the project with gradle, from outside Android Studio in order to get my simple Java Application classes to build, before I run the application - I think this is because the Run configuration of type "Application" is not triggering the corresponding Gradle build.

Finally, this was done on Android Studio 0.4.0.

I hope others find it useful. I also hope Google comes around to supporting this functionality soon.

Changing selection in a select with the Chosen plugin

Sometimes you have to remove the current options in order to manipulate the selected options.

Here is an example how to set options:

<select id="mySelectId" class="chosen-select" multiple="multiple">
  <option value=""></option>
  <option value="Argentina">Argentina</option>
  <option value="Germany">Germany</option>
  <option value="Greece">Greece</option>
  <option value="Japan">Japan</option>
  <option value="Thailand">Thailand</option>
</select>

<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);

function activateChosen($container, param) {
    param = param || {};
    $container.find('.chosen-select:visible').chosen(param);
    $container.find('.chosen-select').trigger("chosen:updated");
}

function selectChosenOptions($select, values) {
    $select.val(null);                                  //delete current options
    $select.val(values);                                //add new options
    $select.trigger('chosen:updated');
}
</script>

JSFiddle (including howto append options): https://jsfiddle.net/59x3m6op/1/

Customizing Bootstrap CSS template

Since Pabluez's answer back in December, there is now a better way to customize Bootstrap.

Use: Bootswatch to generate your bootstrap.css

Bootswatch builds the normal Twitter Bootstrap from the latest version (whatever you install in the bootstrap directory), but also imports your customizations. This makes it easy to use the the latest version of Bootstrap, while maintaining custom CSS, without having to change anything about your HTML. You can simply sway boostrap.css files.

What does %>% mean in R

The infix operator %>% is not part of base R, but is in fact defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.

What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris gets passed to head():

library(magrittr)
iris %>% head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Thus, iris %>% head() is equivalent to head(iris).

Often, %>% is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris is passed to head(), then the result of that is passed to summary().

iris %>% head() %>% summary()

Thus iris %>% head() %>% summary() is equivalent to summary(head(iris)). Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.

How to change legend title in ggplot

The way i am going to tell you, will allow you to change the labels of legend, axis, title etc with a single formula and you don't need to use memorise multiple formulas. This will not affect the font style or the design of the labels/ text of titles and axis.

I am giving the complete answer of the question below.

 library(ggplot2)
 rating <- c(rnorm(200), rnorm(200, mean=.8))
 cond <-factor(rep(c("A", "B"), each = 200))
 df <- data.frame(cond,rating 
             )

 k<- ggplot(data=df, aes(x=rating, fill=cond))+ 
 geom_density(alpha = .3) +
 xlab("NEW RATING TITLE") +
 ylab("NEW DENSITY TITLE")

 # to change the cond to a different label
 k$labels$fill="New Legend Title"

 # to change the axis titles
 k$labels$y="Y Axis"
 k$labels$x="X Axis"
 k

I have stored the ggplot output in a variable "k". You can name it anything you like. Later I have used

k$labels$fill ="New Legend Title"

to change the legend. "fill" is used for those labels which shows different colours. If you have labels that shows sizes like 1 point represent 100, other point 200 etc then you can use this code like this-

k$labels$size ="Size of points"

and it will change that label title.

Which keycode for escape key with jQuery

Your code works just fine. It's most likely the window thats not focused. I use a similar function to close iframe boxes etc.

$(document).ready(function(){

    // Set focus
    setTimeout('window.focus()',1000);

});

$(document).keypress(function(e) {

    // Enable esc
    if (e.keyCode == 27) {
      parent.document.getElementById('iframediv').style.display='none';
      parent.document.getElementById('iframe').src='/views/view.empty.black.html';
    }

});

How does one convert a grayscale image to RGB in OpenCV (Python)?

I am promoting my comment to an answer:

The easy way is:

You could draw in the original 'frame' itself instead of using gray image.

The hard way (method you were trying to implement):

backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB) is the correct syntax.

How can I protect my .NET assemblies from decompilation?

At work here we use Dotfuscator from PreEmptive Solutions.

Although it's impossible to protect .NET assemblies 100% Dotfuscator makes it hard enough I think. I comes with a lot of obfuscation techniques;

Cross Assembly Renaming
Renaming Schemes
Renaming Prefix
Enhanced Overload Induction
Incremental Obfuscation
HTML Renaming Report
Control Flow
String Encryption

And it turned out that they're not very expensive for small companies. They have a special pricing for small companies.

(No I'm not working for PreEmptive ;-))

There are freeware alternatives of course;

A server with the specified hostname could not be found

If the problem occured in a MacOS project, as @nstein commented in this answer just go to your Target's Signing & Capabilities and allow Incoming and Outgoing network options.

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

how to make window.open pop up Modal?

I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.

In parent window use:

<head>    
<style>
.disableWin{
     pointer-events: none;
}
</style>
<script type="text/javascript">
    function openPopUp(url) {
      disableParentWin(); 
      var win = window.open(url);
      win.focus();
      checkPopUpClosed(win);
    }
    /*Function to detect pop up is closed and take action to enable parent window*/
   function checkPopUpClosed(win) {
         var timer = setInterval(function() {
              if(win.closed) {
                  clearInterval(timer);                  
                  enableParentWin();
              }
          }, 1000);
     }
     /*Function to enable parent window*/ 
     function enableParentWin() {
          window.document.getElementById('mainDiv').class="";
     }
     /*Function to enable parent window*/ 
     function disableParentWin() {
          window.document.getElementById('mainDiv').class="disableWin";
     }

</script>
</head>

<body>
<div id="mainDiv class="">
</div>
</body>    

Disable back button in android

If you want to disable your app while logging out, you can pop up a non-cancellable dialog.

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Those error messages

CMake Error at ... (project):
    No CMAKE_C_COMPILER could be found.
-- Configuring incomplete, errors occurred!
See also ".../CMakeFiles/CMakeOutput.log".
See also ".../CMakeFiles/CMakeError.log".

or

CMake Error: your CXX compiler: "CMAKE_CXX_COMPILER-NOTFOUND" was not found.
Please set CMAKE_CXX_COMPILER to a valid compiler path or name.
...
-- Configuring incomplete, errors occurred!

just mean that CMake was unable to find your C/CXX compiler to compile a simple test program (one of the first things CMake tries while detecting your build environment).

The steps to find your problem are dependent on the build environment you want to generate. The following tutorials are a collection of answers here on Stack Overflow and some of my own experiences with CMake on Microsoft Windows 7/8/10 and Ubuntu 14.04.

Preconditions

  • You have installed the compiler/IDE and it was able to once compile any other program (directly without CMake)
  • You have the latest CMake version
  • You have access rights on the drive you want CMake to generate your build environment
  • You have a clean build directory (because CMake does cache things from the last try) e.g. as sub-directory of your source tree

    Windows cmd.exe

    > rmdir /s /q VS2015
    > mkdir VS2015
    > cd VS2015
    

    Bash shell

    $ rm -rf MSYS
    $ mkdir MSYS
    $ cd MSYS
    

    and make sure your command shell points to your newly created binary output directory.

General things you can/should try

  1. Is CMake able find and run with any/your default compiler? Run without giving a generator

    > cmake ..
    -- Building for: Visual Studio 14 2015
    ...
    

    Perfect if it correctly determined the generator to use - like here Visual Studio 14 2015

  2. What was it that actually failed?

    In the previous build output directory look at CMakeFiles\CMakeError.log for any error message that make sense to you or try to open/compile the test project generated at CMakeFiles\[Version]\CompilerIdC|CompilerIdCXX directly from the command line (as found in the error log).

CMake can't find Visual Studio

  1. Try to select the correct generator version:

    > cmake --help
    > cmake -G "Visual Studio 14 2015" ..
    
  2. If that doesn't help, try to set the Visual Studio environment variables first (the path could vary):

    > "c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"
    > cmake ..
    

    or use the Developer Command Prompt for VS2015 short-cut in your Windows Start Menu under All Programs/Visual Studio 2015/Visual Studio Tools (thanks at @Antwane for the hint).

Background: CMake does support all Visual Studio releases and flavors (Express, Community, Professional, Premium, Test, Team, Enterprise, Ultimate, etc.). To determine the location of the compiler it uses a combination of searching the registry (e.g. at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[Version];InstallDir), system environment variables and - if none of the others did come up with something - plainly try to call the compiler.

CMake can't find GCC (MinGW/MSys)

  1. You start the MSys bash shell with msys.bat and just try to directly call gcc

    $ gcc
    gcc.exe: fatal error: no input files
    compilation terminated.
    

    Here it did find gcc and is complaining that I didn't gave it any parameters to work with.

    So the following should work:

    $ cmake -G "MSYS Makefiles" ..
    -- The CXX compiler identification is GNU 4.8.1
    ...
    $ make
    

    If GCC was not found call export PATH=... to add your compilers path (see How to set PATH environment variable in CMake script?) and try again.

  2. If it's still not working, try to set the CXX compiler path directly by exporting it (path may vary)

    $ export CC=/c/MinGW/bin/gcc.exe
    $ export CXX=/c/MinGW/bin/g++.exe
    $ cmake -G "MinGW Makefiles" ..
    -- The CXX compiler identification is GNU 4.8.1
    ...
    $ mingw32-make
    

    For more details see How to specify new GCC path for CMake

    Note: When using the "MinGW Makefiles" generator you have to use the mingw32-make program distributed with MinGW

  3. Still not working? That's weird. Please make sure that the compiler is there and it has executable rights (see also preconditions chapter above).

    Otherwise the last resort of CMake is to not try any compiler search itself and set CMake's internal variables directly by

    $ cmake -DCMAKE_C_COMPILER=/c/MinGW/bin/gcc.exe -DCMAKE_CXX_COMPILER=/c/MinGW/bin/g++.exe ..
    

    For more details see Cmake doesn't honour -D CMAKE_CXX_COMPILER=g++ and Cmake error setting compiler

    Alternatively those variables can also be set via cmake-gui.exe on Windows. See Cmake cannot find compiler

Background: Much the same as with Visual Studio. CMake supports all sorts of GCC flavors. It searches the environment variables (CC, CXX, etc.) or simply tries to call the compiler. In addition it will detect any prefixes (when cross-compiling) and tries to add it to all binutils of the GNU compiler toolchain (ar, ranlib, strip, ld, nm, objdump, and objcopy).

Delete item from array and shrink array

The size of a Java array is fixed when you allocate it, and cannot be changed.

  • If you want to "grow" or "shrink" an existing array, you have to allocate a new array of the appropriate size and copy the array elements; e.g. using System.arraycopy(...) or Arrays.copyOf(...). A copy loop works as well, though it looks a bit clunky ... IMO.

  • If you want to "delete" an item or items from an array (in the true sense ... not just replacing them with null), you need to allocate a new smaller array and copy across the elements you want to retain.

  • Finally, you can "erase" an element in an array of a reference type by assigning null to it. But this introduces new problems:

    • If you were using null elements to mean something, you can't do this.
    • All of the code that uses the array now has to deal with the possibility of a null element in the appropriate fashion. More complexity and potential for bugs1.

There are alternatives in the form of 3rd-party libraries (e.g. Apache Commons ArrayUtils), but you may want to consider whether it is worth adding a library dependency just for the sake of a method that you could implement yourself with 5-10 lines of code.


It is better (i.e. simpler ... and in many cases, more efficient2) to use a List class instead of an array. This will take care of (at least) growing the backing storage. And there are operations that take care of inserting and deleting elements anywhere in the list.

For instance, the ArrayList class uses an array as backing, and automatically grows the array as required. It does not automatically reduce the size of the backing array, but you can tell it to do this using the trimToSize() method; e.g.

ArrayList l = ...
l.remove(21);
l.trimToSize();  // Only do this if you really have to.

1 - But note that the explicit if (a[e] == null) checks themselves are likely to be "free", since they can be combined with the implicit null check that happens when you dereference the value of a[e].

2 - I say it is "more efficient in many cases" because ArrayList uses a simple "double the size" strategy when it needs to grow the backing array. This means that if grow the list by repeatedly appending to it, each element will be copied on average one extra time. By contrast, if you did this with an array you would end up copying each array element close to N/2 times on average.

How to write to Console.Out during execution of an MSTest test

You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.

Change window location Jquery

If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin

Use document.location.href to change the page location, place it in the function on a successful ajax run.

Calling Javascript from a html form

In this bit of code:

getRadioButtonValue(this["whichThing"]))

you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.

EDIT To get the value out of the radio buttons, grab the JQuery library, and then use this:

  $('input[name=whichThing]:checked').val() 

Edit 2 Due to the desire to reinvent the wheel, here's non-Jquery code:

var t = '';
for (i=0; i<document.myform.whichThing.length; i++) {
     if (document.myform.whichThing[i].checked==true) {
         t = t + document.myform.whichThing[i].value;
     }
}

or, basically, modify the original line of code to read thusly:

getRadioButtonValue(document.myform.whichThing))

Edit 3 Here's your homework:

      function handleClick() {
        alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
        //event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
    </script>
  </head>
<body>
<form name="aye" onSubmit="return handleClick()">
     <input name="Submit"  type="submit" value="Update" />
     Which of the following do you like best?
     <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
     <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
     <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>

Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.

In the function itself, I modified the how the form was being accessed. The structure is: document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.

The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.

EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.

See the difference in this method:

function handleClick() {
   alert("Direct Access: " + document.aye["whichThing"]);
   alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
   return false; // prevent further bubbling of event
}

Copying files from one directory to another in Java

    File file = fileChooser.getSelectedFile();
    String selected = fc.getSelectedFile().getAbsolutePath();
     File srcDir = new File(selected);
     FileInputStream fii;
     FileOutputStream fio;
    try {
         fii = new FileInputStream(srcDir);
         fio = new FileOutputStream("C:\\LOvE.txt");
         byte [] b=new byte[1024];
         int i=0;
        try {
            while ((fii.read(b)) > 0)
            {

              System.out.println(b);
              fio.write(b);
            }
            fii.close();
            fio.close();

When to use RDLC over RDL reports?

I have always thought the different between RDL and RDLC is that RDL are used for SQL Server Reporting Services and RDLC are used in Visual Studio for client side reporting. The implemenation and editor are almost identical. RDL stands for Report Defintion Language and RDLC Report Definition Language Client-side.

I hope that helps.

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE