Programs & Examples On #Reverse lookup

Many programming languages feature data structures where unique indexes are associated with a value. Reverse lookup is retrieving the index with which a given value is accessed.

Using Python's list index() method on a list of tuples or objects?

tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]

def eachtuple(tupple, pos1, val):
    for e in tupple:
        if e == val:
            return True

for e in tuple_list:
    if eachtuple(e, 1, 7) is True:
        print tuple_list.index(e)

for e in tuple_list:
    if eachtuple(e, 0, "kumquat") is True:
        print tuple_list.index(e)

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.


R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
1 20
2  0
3 30

How to get the nth element of a python list or a default if not available

   a = b[n]
except IndexError:
   a = default

Edit: I removed the check for TypeError - probably better to let the caller handle this.

In Typescript, How to check if a string is Numeric

The way to convert a string to a number is with Number, not parseFloat.

Number('1234') // 1234
Number('9BX9') // NaN

You can also use the unary plus operator if you like shorthand:

+'1234' // 1234
+'9BX9' // NaN

Be careful when checking against NaN (the operator === and !== don't work as expected with NaN). Use:

 isNaN(+maybeNumber) // returns true if NaN, otherwise false

How to compare 2 files fast using .NET?

It's getting even faster if you don't read in small 8 byte chunks but put a loop around, reading a larger chunk. I reduced the average comparison time to 1/4.

    public static bool FilesContentsAreEqual(FileInfo fileInfo1, FileInfo fileInfo2)
        bool result;

        if (fileInfo1.Length != fileInfo2.Length)
            result = false;
            using (var file1 = fileInfo1.OpenRead())
                using (var file2 = fileInfo2.OpenRead())
                    result = StreamsContentsAreEqual(file1, file2);

        return result;

    private static bool StreamsContentsAreEqual(Stream stream1, Stream stream2)
        const int bufferSize = 1024 * sizeof(Int64);
        var buffer1 = new byte[bufferSize];
        var buffer2 = new byte[bufferSize];

        while (true)
            int count1 = stream1.Read(buffer1, 0, bufferSize);
            int count2 = stream2.Read(buffer2, 0, bufferSize);

            if (count1 != count2)
                return false;

            if (count1 == 0)
                return true;

            int iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64));
            for (int i = 0; i < iterations; i++)
                if (BitConverter.ToInt64(buffer1, i * sizeof(Int64)) != BitConverter.ToInt64(buffer2, i * sizeof(Int64)))
                    return false;

Reason: no suitable image found

you probably don't have the correct arch in that lib, you can do a

file /private/var/mobile/Containers/Bundle/Application/3FC2DC5C-A908-42C4-8508-1320E01E0D5B/

and it should show you the arch's that are in that library... I am not sure how you are linking, but it probably isn't the right way (if libswiftcore is a factory library, if it is some add on library then it probably isn't compiled correctly)

How to open .dll files to see what is written inside?

I use the Jetbrains Dot peek Software , you can try that too

Java, return if trimmed String in List contains String

You can do it in a single line by using regex:

if (myList.toString().matches(".*\\bA\\b.*"))

This code should perform quite well.

BTW, you could build the regex from a variable, like this:

.matches("\\[.*\\b" + word + "\\b.*]")

I added [ and ] to each end to prevent a false positive match when the search term contains an open/close square bracket at the start/end.

Best way to encode Degree Celsius symbol into web page?

  1. The degree sign belongs to the number, and not to the "C". You can regard the degree sign as a number symbol, just like the minus sign.
  2. There shall not be any space between the digits and the degree sign.
  3. There shall be a non-breaking space between the degree sign and the "C".

Spark specify multiple column conditions for dataframe join


    Leaddetails("LeadSource") <=> Utm_Master("LeadSource")
        && Leaddetails("Utm_Source") <=> Utm_Master("Utm_Source")
        && Leaddetails("Utm_Medium") <=> Utm_Master("Utm_Medium")
        && Leaddetails("Utm_Campaign") <=> Utm_Master("Utm_Campaign"),

To make it case insensitive,

import org.apache.spark.sql.functions.{lower, upper}

then just use lower(value) in the condition of the join method.

Eg: dataFrame.filter(lower(dataFrame.col("vendor")).equalTo("fortinet"))

Hidden Features of Java

How about Properties files in your choice of encodings? Used to be, when you loaded your Properties, you provided an InputStream and the load() method decoded it as ISO-8859-1. You could actually store the file in some other encoding, but you had to use a disgusting hack like this after loading to properly decode the data:

String realProp = new String(prop.getBytes("ISO-8859-1"), "UTF-8");

But, as of JDK 1.6, there's a load() method that takes a Reader instead of an InputStream, which means you can use the correct encoding from the beginning (there's also a store() method that takes a Writer). This seems like a pretty big deal to me, but it appears to have been snuck into the JDK with no fanfare at all. I only stumbled upon it a few weeks ago, and a quick Google search turned up just one passing mention of it.

How do you format an unsigned long long int using printf?

Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).

printf("%llu", 285212672);

Maven parent pom vs modules pom

  1. An independent parent is the best practice for sharing configuration and options across otherwise uncoupled components. Apache has a parent pom project to share legal notices and some common packaging options.

  2. If your top-level project has real work in it, such as aggregating javadoc or packaging a release, then you will have conflicts between the settings needed to do that work and the settings you want to share out via parent. A parent-only project avoids that.

  3. A common pattern (ignoring #1 for the moment) is have the projects-with-code use a parent project as their parent, and have it use the top-level as a parent. This allows core things to be shared by all, but avoids the problem described in #2.

  4. The site plugin will get very confused if the parent structure is not the same as the directory structure. If you want to build an aggregate site, you'll need to do some fiddling to get around this.

  5. Apache CXF is an example the pattern in #2.

When to use 'raise NotImplementedError'?

As the documentation states [docs],

In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added.

Note that although the main stated use case this error is the indication of abstract methods that should be implemented on inherited classes, you can use it anyhow you'd like, like for indication of a TODO marker.

How to create a thread?

The method that you want to run must be a ThreadStart Delegate. Please consult the Thread documentation on MSDN. Note that you can sort of create your two-parameter start with a closure. Something like:

var t = new Thread(() => Startup(port, path));

Note that you may want to revisit your method accessibility. If I saw a class starting a thread on its own public method in this manner, I'd be a little surprised.

Flexbox and Internet Explorer 11 (display:flex in <html>?)

Here is an example of using flex that also works in Internet Explorer 11 and Chrome.


<!DOCTYPE html>_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >_x000D_
<title>Flex Test</title>_x000D_
html, body {_x000D_
    margin: 0px;_x000D_
    padding: 0px;_x000D_
    height: 100vh;_x000D_
.main {_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -ms-flex-direction: row;_x000D_
    flex-direction: row;_x000D_
    align-items: stretch;_x000D_
    min-height: 100vh;_x000D_
.main::after {_x000D_
  content: '';_x000D_
  height: 100vh;_x000D_
  width: 0;_x000D_
  overflow: hidden;_x000D_
  visibility: hidden;_x000D_
  float: left;_x000D_
.left {_x000D_
    width: 200px;_x000D_
    background: #F0F0F0;_x000D_
    flex-shrink: 0;_x000D_
.right {_x000D_
    flex-grow: 1;_x000D_
    background: yellow;_x000D_
<div class="main">_x000D_
    <div class="left">_x000D_
        <div style="height: 300px;">_x000D_
    <div class="right">_x000D_
        <div style="height: 1000px;">_x000D_
            test test test_x000D_

Case objects vs Enumerations in Scala

I have a nice simple lib here that allows you to use sealed traits/classes as enum values without having to maintain your own list of values. It relies on a simple macro that is not dependent on the buggy knownDirectSubclasses.

Passing an array as a function parameter in JavaScript

As @KaptajnKold had answered

var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);

And you don't need to define every parameters for call_me function either. You can just use arguments

function call_me () {
    // arguments is a array consisting of params.
    // arguments[0] == 'p0',
    // arguments[1] == 'p1',
    // arguments[2] == 'p2'

PHP Fatal error: Cannot access empty property

You access the property in the wrong way. With the $this->$my_value = .. syntax, you set the property with the name of the value in $my_value. What you want is $this->my_value = ..

$var = "my_value";
$this->$var = "test";

is the same as

$this->my_value = "test";

To fix a few things from your example, the code below is a better aproach

class my_class {

    public  $my_value = array();

    function __construct ($value) {
        $this->my_value[] = $value;

    function set_value ($value) {
        if (!is_array($value)) {
            throw new Exception("Illegal argument");

        $this->my_value = $value;

    function add_value($value) {
        $this->my_value = $value;

$a = new my_class ('a');
$a->my_value[] = 'b';

This ensures, that my_value won't change it's type to string or something else when you call set_value. But you can still set the value of my_value direct, because it's public. The final step is, to make my_value private and only access my_value over getter/setter methods

How to do a scatter plot with empty circles in Python?

In matplotlib 2.0 there is a parameter called fillstyle which allows better control on the way markers are filled. In my case I have used it with errorbars but it works for markers in general

fillstyle accepts the following values: [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]

There are two important things to keep in mind when using fillstyle,

1) If mfc is set to any kind of value it will take priority, hence, if you did set fillstyle to 'none' it would not take effect. So avoid using mfc in conjuntion with fillstyle

2) You might want to control the marker edge width (using markeredgewidth or mew) because if the marker is relatively small and the edge width is thick, the markers will look like filled even though they are not.

Following is an example using errorbars:

myplot.errorbar(x=myXval, y=myYval, yerr=myYerrVal, fmt='o', fillstyle='none', ecolor='blue',  mec='blue')

How to make PDF file downloadable in HTML link?

This is a common issue but few people know there's a simple HTML 5 solution:

<a href="./directory/yourfile.pdf" download="newfilename">Download the pdf</a>

Where newfilename is the suggested filename for the user to save the file. Or it will default to the filename on the serverside if you leave it empty, like this:

<a href="./directory/yourfile.pdf" download>Download the pdf</a>

Compatibility: I tested this on Firefox 21 and Iron, both worked fine. It might not work on HTML5-incompatible or outdated browsers. The only browser I tested that didn't force download is IE...

Check compatibility here:

Create folder in Android

Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
if (success) {
    // Do something on success
} else {
    // Do something else on failure 

when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder

Can the :not() pseudo-class have multiple arguments?

Why :not just use two :not:


Yes, it is intentional

Export/import jobs in Jenkins

In my Jenkins instance (version 1.548) the configuration file is at:


Owned by jenkins user and jenkins group with 644 permissions. Copying the file to and from here should work. I haven't tried changing it directly but have backed-up the config from this spot in case the project needs to be setup again.

Start service in Android

I like to make it more dynamic

Class<?> serviceMonitor = MyService.class; 

private void startMyService() { context.startService(new Intent(context, serviceMonitor)); }
private void stopMyService()  { context.stopService(new Intent(context, serviceMonitor));  }

do not forget the Manifest

<service android:enabled="true" android:name=".MyService.class" />

How do I get a string format of the current date time, in python?


import datetime
    '1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( )

d =
print( "2a: {:%B %d, %Y}".format(d))

# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")

print(f"3: Today is {} yay")

1: test-2018-02-14_16:40:52.txt

2a: March 04, 2018

2b: March 04, 2018

3: Today is 2018-11-11 yay


Using the new string format to inject value into a string at placeholder {}, value is the current time.

Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.

Golang read request body

Inspecting and mocking request body

When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.

One option is to read the whole body using ioutil.ReadAll(), which gives you the body as a byte slice.

You may use bytes.NewBuffer() to obtain an io.Reader from a byte slice.

The last missing piece is to make the io.Reader an io.ReadCloser, because bytes.Buffer does not have a Close() method. For this you may use ioutil.NopCloser() which wraps an io.Reader, and returns an io.ReadCloser, whose added Close() method will be a no-op (does nothing).

Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.

Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!

Inspecting / modifying response body

If you also want to read the response body, then you have to wrap the http.ResponseWriter you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).

Here's a simple ResponseWriter wrapper, which just caches the data, so it'll be available after the subsequent handler returns:

type MyResponseWriter struct {
    buf *bytes.Buffer

func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
    return mrw.buf.Write(p)

Note that MyResponseWriter.Write() just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write() method) and write the data immediately to the wrapped / embedded ResponseWriter. You may even modify the data. You have full control.

Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.

Full example

Putting the pieces together, here's a full working example:

func loginmw(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            log.Printf("Error reading body: %v", err)
            http.Error(w, "can't read body", http.StatusBadRequest)

        // Work / inspect body. You may even modify it!

        // And now set a new body, which will simulate the same data we read:
        r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

        // Create a response wrapper:
        mrw := &MyResponseWriter{
            ResponseWriter: w,
            buf:            &bytes.Buffer{},

        // Call next handler, passing the response wrapper:
        handler.ServeHTTP(mrw, r)

        // Now inspect response, and finally send it out:
        // (You can also modify it before sending it out!)
        if _, err := io.Copy(w, mrw.buf); err != nil {
            log.Printf("Failed to send out response: %v", err)

Accessing a class' member variables in Python?

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"

theExample = Example()

But if you want a true class variable, then use the class name directly:

class Example(object):
    itsProblem = "problem"

theExample = Example()
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 



Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"

theExample = Example()


class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"

theExample = Example()

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
    itsProblem = "problem"

theExample = Example()

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

"No cached version... available for offline mode."

Just happened to me after upgrading to Android Studio 3.1. The Offline Work checkbox was unchecked, so no luck there.

I went to Settings > Build, Execution, Deployment > Compiler and the Command-line Options textfield contained --offline, so I just deleted that and everything worked.

setting screenshot

Using File.listFiles with FileNameExtensionFilter

The FileNameExtensionFilter class is intended for Swing to be used in a JFileChooser.

Try using a FilenameFilter instead. For example:

File dir = new File("/users/blah/dirname");
File[] files = dir.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");

React: how to update state.item[1] in state using setState?

You could use the update immutability helper for this:

  items: update(this.state.items, {1: {name: {$set: 'updated field name'}}})

Or if you don't care about being able to detect changes to this item in a shouldComponentUpdate() lifecycle method using ===, you could edit the state directly and force the component to re-render - this is effectively the same as @limelights' answer, as it's pulling an object out of state and editing it.

this.state.items[1].name = 'updated field name'

Post-edit addition:

Check out the Simple Component Communication lesson from react-training for an example of how to pass a callback function from a state-holding parent to a child component which needs to trigger a state change.

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
  alert("Hi. Variable is defined.");

Auto Increment after delete in MySQL

I got a very simple but tricky method.

While deleting a row, you can preserve the IDs into another temporary table. After that, when you will insert new data into the main table then you can search and pick IDs from the temporary table. So use a checking here. If the temporary table has no IDs then calculate maximum ID into the main table and set the new ID as: new_ID = old_max_ID+1.

NB: You can not use auto-increment feature here.

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

For those who are trying to use gulp for swagger local deployment, following code will help

var gulp = require("gulp");
var yaml = require("js-yaml");
var path = require("path");
var fs = require("fs");

//Converts yaml to json
gulp.task("swagger", done => {
    var doc = yaml.safeLoad(fs.readFileSync(path.join(__dirname,"api/swagger/swagger.yaml")));
        JSON.stringify(doc, null, " ")

//Watches for changes    
gulp.task('watch', function() {'api/swagger/swagger.yaml', gulp.series('swagger'));  

Get exit code for command in bash/ksh

Below is the fixed code:

safeRunCommand() {
  typeset cmnd="$*"
  typeset ret_code

  echo cmnd=$cmnd
  eval $cmnd
  if [ $ret_code != 0 ]; then
    printf "Error : [%d] when executing command: '$cmnd'" $ret_code
    exit $ret_code

command="ls -l | grep p"
safeRunCommand "$command"

Now if you look into this code few things that I changed are:

  • use of typeset is not necessary but a good practice. It make cmnd and ret_code local to safeRunCommand
  • use of ret_code is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
  • pass the command with quotes surrounding the command like safeRunCommand "$command". If you dont then cmnd will get only the value ls and not ls -l. And it is even more important if your command contains pipes.
  • you can use typeset cmnd="$*" instead of typeset cmnd="$1" if you want to keep the spaces. You can try with both depending upon how complex is your command argument.
  • eval is used to evaluate so that command containing pipes can work fine

NOTE: Do remember some commands give 1 as return code even though there is no error like grep. If grep found something it will return 0 else 1.

I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.

Java HashMap: How to get a key and value by index?

A solution is already selected. However, I post this solution for those who want to use an alternative approach:

// use LinkedHashMap if you want to read values from the hashmap in the same order as you put them into it
private ArrayList<String> getMapValueAt(LinkedHashMap<String, ArrayList<String>> hashMap, int index)
    Map.Entry<String, ArrayList<String>> entry = (Map.Entry<String, ArrayList<String>>) hashMap.entrySet().toArray()[index];
    return entry.getValue();

Redirect form to different URL based on select option element

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value="">Gmail</option>
    <option value="">Youtube</option>

Does hosts file exist on the iPhone? How to change it?

I just edited my iPhone's 'hosts' file successfully (on Jailbroken iOS 4.0).

  • Installed OpenSSH onto iPhone via Cydia
  • Using a SFTP client like FileZilla on my computer, I connected to my iPhone
    • Address: [use your phone's IP address or hostname, eg. simophone.local]
    • Username: root
    • Password: alpine
  • Located the /etc/hosts file
  • Made a backup on my computer (in case I want to revert my changes later)
  • Edited the hosts file in a decent text editor (such as Notepad++). See here for an explanation of the hosts file.
  • Uploaded the changes, overwriting the hosts file on the iPhone

The phone does cache some webpages and DNS queries, so a reboot or clearing the cache may help. Hope that helps someone.


Alternative Windows shells, besides CMD.EXE?

  1. Hard to copy and paste.

    Not true. Enable QuickEdit, either in the properties of the shortcut, or in the properties of the CMD window (right-click on the title bar), and you can mark text directly. Right-click copies marked text into the clipboard. When no text is marked, a right-click pastes text from the clipboard.

    enter image description here

  2. Hard to resize the window.

    True. Console2 (see below) does not have this limitation.

  3. Hard to open another window (no menu options do this).

    Not true. Use start cmd or define an alias if that's too much hassle:

    doskey nw=start cmd /k $*
  4. Seems to always start in C:\Windows\System32, which is super useless.

    Not true. Or rather, not true if you define a start directory in the properties of the shortcut

    enter image description here

    or by modifying the AutoRun registry value. Shift-right-click on a folder allows you to launch a command prompt in that folder.

  5. Weird scrolling. Sometimes it scrolls down really far into blank space, and you have to scroll up to where the window is actually populated

    Never happened to me.

An alternative to plain CMD is Console2, which uses CMD under the hood, but provides a lot more configuration options.

What is the difference between call and apply?

Here's a good mnemonic. Apply uses Arrays and Always takes one or two Arguments. When you use Call you have to Count the number of arguments.

How to send 100,000 emails weekly?

Here is what I did recently in PHP on one of my bigger systems:

  1. User inputs newsletter text and selects the recipients (which generates a query to retrieve the email addresses for later).

  2. Add the newsletter text and recipients query to a row in mysql table called *email_queue*

    • (The table email_queue has the columns "to" "subject" "body" "priority")
  3. I created another script, which runs every minute as a cron job. It uses the SwiftMailer class. This script simply:

    • during business hours, sends all email with priority == 0

    • after hours, send other emails by priority

Depending on the hosts settings, I can now have it throttle using standard swiftmailers plugins like antiflood and throttle...

$mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(50, 30));


$mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin( 100, Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE ));

etc, etc..

I have expanded it way beyond this pseudocode, with attachments, and many other configurable settings, but it works very well as long as your server is setup correctly to send email. (Probably wont work on shared hosting, but in theory it should...) Swiftmailer even has a setting


Which I now use to track bounces...

Happy Trails! (Happy Emails?)

How to write ternary operator condition in jQuery?

I think Dan and Nicola have suitable corrected code, however you may not be clear on why the original code didn't work.

What has been called here a "ternary operator" is called a conditional operator in ECMA-262 section 11.12. It has the form:

LogicalORExpression ? AssignmentExpression : AssignmentExpression

The LogicalORExpression is evaluated and the returned value converted to Boolean (just like an expression in an if condition). If it evaluates to true, then the first AssignmentExpression is evaluated and the returned value returned, otherwise the second is evaluated and returned.

The error in the original code is the extra semi-colons that change the attempted conditional operator into a series of statements with syntax errors.

How to completely uninstall Android Studio from windows(v10)?

First go to android studio folder on location that you installed it ( It’s usually in this path by default ; C:\Program Files\Android\Android Studio, unless you change it when you install Android Studio). Find and run uninstall.exe file.

Wait until uninstallation complete successfully, just few minutes, and after click the close.

To delete any remains of Android Studio setting files, in File Explorer, go to C:\Users\%username%, and delete .android, .AndroidStudio(#version-number) and also .gradle, AndroidStudioProjects if they exist. If you want remain your projects, you’d like to keep AndroidStudioProjects folder.

Then, go to C:\Users\%username%\AppData\Roaming and delete the JetBrains directory.

Note that AppData folder is hidden by default, to make visible it go to view tab and check hidden items in windows8 and10 ( in windows7 Select Folder Options, then select the View tab. Under Advanced settings, select Show hidden files, folders, and drives, and then select OK.

Done, you can remove Android Studio successfully, if you plan to delete SDK tools too, it is enough to remove SDK folder completely.

JavaScript to scroll long page to DIV

There is a jQuery plugin for the general case of scrolling to a DOM element, but if performance is an issue (and when is it not?), I would suggest doing it manually. This involves two steps:

  1. Finding the position of the element you are scrolling to.
  2. Scrolling to that position.

quirksmode gives a good explanation of the mechanism behind the former. Here's my preferred solution:

function absoluteOffset(elem) {
    return elem.offsetParent && elem.offsetTop + absoluteOffset(elem.offsetParent);

It uses casting from null to 0, which isn't proper etiquette in some circles, but I like it :) The second part uses window.scroll. So the rest of the solution is:

function scrollToElement(elem) {


Spring MVC: Complex object as GET @RequestParam

Accepted answer works like a charm but if the object has a list of objects it won't work as expected so here is my solution after some digging.

Following this thread advice, here is how I've done.

  • Frontend: stringify your object than encode it in base64 for submission.
  • Backend: decode base64 string then convert the string json into desired object.

It isn't the best for debugging your API with postman but it is working as expected for me.

Original object: { page: 1, size: 5, filters: [{ field: "id", value: 1, comparison: "EQ" }

Encoded object: eyJwYWdlIjoxLCJzaXplIjo1LCJmaWx0ZXJzIjpbeyJmaWVsZCI6ImlkUGFyZW50IiwiY29tcGFyaXNvbiI6Ik5VTEwifV19

fun list(@RequestParam search: String?): ResponseEntity<ListDTO> {
    val filter: SearchFilterDTO = decodeSearchFieldDTO(search)

private fun decodeSearchFieldDTO(search: String?): SearchFilterDTO {
    if (search.isNullOrEmpty()) return SearchFilterDTO()
    return Gson().fromJson(String(Base64.getDecoder().decode(search)),

And here the SearchFilterDTO and FilterDTO

class SearchFilterDTO(
    var currentPage: Int = 1,
    var pageSize: Int = 10,
    var sort: Sort? = null,
    var column: String? = null,
    var filters: List<FilterDTO> = ArrayList<FilterDTO>(),
    var paged: Boolean = true

class FilterDTO(
    var field: String,
    var value: Any,
    var comparison: Comparison

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Alternatively, you could use a class for it and an instance for the check.

function A() {_x000D_
    var value = 0;_x000D_
    this.valueOf = function () { return ++value; };_x000D_
var a = new A;_x000D_
if (a == 1 && a == 2 && a == 3) {_x000D_


Using ES6 classes it would look like this

class A {_x000D_
  constructor() {_x000D_
    this.value = 0;_x000D_
  valueOf() {_x000D_
    return this.value++;_x000D_
let a = new A;_x000D_
if (a == 1 && a == 2 && a == 3) {_x000D_

Laravel - Pass more than one variable to view

Please try this,

$ms = Person::where('name', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return View::make('viewname')->with(compact('persons','ms'));

Convert from enum ordinal to enum type

Safety first (with Kotlin):

// Default to null

// Default to a value
EnumName.values().getOrElse(ordinal) { EnumName.MyValue }

How to set Python's default version to 3.x on OS X?

If you are using macports, that has a easier way to do:


port install python37

after install, set default:

sudo port select --set python python37

sudo port select --set python3 python37

restart your cmd window, finished.

Global javascript variable inside document.ready

If you're declaring a global variable, you might want to use a namespace of some kind. Just declare the namespace outside, then you can throw whatever you want into it. Like this...

var MyProject = {};
$(document).ready(function() {
    MyProject.intro = "";

    MyProject.intro = "something";

console.log(MyProject.intro); // "something"

Creating Threads in python

You can use the target argument in the Thread constructor to directly pass in a function that gets called instead of run.

How to compare two files in Notepad++ v6.6.8


  • for Notepad++ 7.5 and above use Compare v2.0.0
  • for Notepad++ 7.7 and above use Compare v2.0.0 for Notepad++ 7.7, if you need to install manually follow the description below, otherwise use "Plugin Admin".

I use Compare plugin 2 for notepad++ 7.5 and newer versions. Notepad++ 7.5 and newer versions does not have plugin manager. You have to download and install plugins manually. And YES it matters if you use 64bit or 32bit (86x).

So Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin, and the same valid for 32bit.

I wrote a guideline how to install it:

  1. Start your Notepad++ as administrator mode.
  2. Press F1 to find out if your Notepad++ is 64bit or 32bit (86x), hence you need to download the correct plugin version. Download Compare-plugin 2.
  3. Unzip Compare-plugin in temporary folder.
  4. Import plugin from the temporary folder.
  5. The plugin should appear under Plugins menu.

It is also possible to drag and drop the plugin .dll file directly in plugin folder.
64bit: %programfiles%\Notepad++\plugins
32bit: %programfiles(x86)%\Notepad++\plugins

Update Thanks to @TylerH with this update: Notepad++ Now has "Plugin Admin" as a replacement for the old Plugin Manager. But this method (answer) is still valid for adding plugins manually for almost any Notepad++ plugins.

Disclaimer: the link of this guideline refer to my personal web site.

How to compare two Carbon Timestamps?

Carbon has a bunch of comparison functions with mnemonic names:

  • equalTo()
  • notEqualTo()
  • greaterThan()
  • greaterThanOrEqualTo()
  • lessThan()
  • lessThanOrEqualTo()


     // edited at is newer than created at

Valid for nesbot/carbon 1.36.2

if you are not sure what Carbon version you are on, run this

$composer show "nesbot/carbon"


MySQL selecting yesterday's date

Query for the last weeks:

FROM dual

Entity Framework : How do you refresh the model when the db changes?

Update CodeFirst Model is not possible automatically. I don't recommend either. Because one of the benefits of code first is you can work with POCO classes. If you changed this POCO classes you don't want some auto generated code to destroy your work.

But you can create some template solution add your updated/added entity to the new model. then collect and move your new cs file to your working project. this way you will not have a conflict if it is a new entity you can simply adding related cs file to the existing project. if it is an update just add a new property from the file. If you just adding some couple of columns to one or two of your tables you can manually add them to your POCO class you don't need any extra works and that is the beauty of Working with Code-First and POCO classes.

Exception in thread "main" java.util.NoSuchElementException

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results.

The solution: For console apps, use a single Scanner to read from

Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine().

See: Do not create multiple buffered wrappers on a single InputStream

EF Migrations: Rollback last applied migration?

Additional reminder:

If you have multiple configuration type, you need to specify the [ConfigurationName]

Update-Database -Configurationtypename [ConfigurationName] -TargetMigration [MigrationName]

What are the alternatives now that the Google web search API has been deprecated?

Here is an option at the bottom of the Custom Search Control Panel: "Sites to search", you can choose "Search the entire web but emphasize included sites"

Custom Search Control Panel - Sites to search

Pure CSS animation visibility with delay

You can play with delay prop of animation, just set visibility:visible after a delay, demo:

@keyframes delayedShow {_x000D_
  to {_x000D_
    visibility: visible;_x000D_
  visibility: hidden;_x000D_
  animation: 0s linear 2.3s forwards delayedShow ;_x000D_
So, Where are you?_x000D_
<div class="delayedShow">_x000D_
  Hey, I'm here!_x000D_

How do I access store state in React Redux?

You need to use Store.getState() to get current state of your Store.

For more information about getState() watch this short video.

Multiple Where clauses in Lambda expressions

You can include it in the same where statement with the && operator...

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty 
    && l.InternalName != String.Empty)

You can use any of the comparison operators (think of it like doing an if statement) such as...

List<Int32> nums = new List<int>();


var results = nums.Where(x => x == 3 || x == 10);

...would bring back 3 and 10.

How to find time complexity of an algorithm

Loosely speaking, time complexity is a way of summarising how the number of operations or run-time of an algorithm grows as the input size increases.

Like most things in life, a cocktail party can help us understand.


When you arrive at the party, you have to shake everyone's hand (do an operation on every item). As the number of attendees N increases, the time/work it will take you to shake everyone's hand increases as O(N).

Why O(N) and not cN?

There's variation in the amount of time it takes to shake hands with people. You could average this out and capture it in a constant c. But the fundamental operation here --- shaking hands with everyone --- would always be proportional to O(N), no matter what c was. When debating whether we should go to a cocktail party, we're often more interested in the fact that we'll have to meet everyone than in the minute details of what those meetings look like.


The host of the cocktail party wants you to play a silly game where everyone meets everyone else. Therefore, you must meet N-1 other people and, because the next person has already met you, they must meet N-2 people, and so on. The sum of this series is x^2/2+x/2. As the number of attendees grows, the x^2 term gets big fast, so we just drop everything else.


You have to meet everyone else and, during each meeting, you must talk about everyone else in the room.


The host wants to announce something. They ding a wineglass and speak loudly. Everyone hears them. It turns out it doesn't matter how many attendees there are, this operation always takes the same amount of time.

O(log N)

The host has laid everyone out at the table in alphabetical order. Where is Dan? You reason that he must be somewhere between Adam and Mandy (certainly not between Mandy and Zach!). Given that, is he between George and Mandy? No. He must be between Adam and Fred, and between Cindy and Fred. And so on... we can efficiently locate Dan by looking at half the set and then half of that set. Ultimately, we look at O(log_2 N) individuals.

O(N log N)

You could find where to sit down at the table using the algorithm above. If a large number of people came to the table, one at a time, and all did this, that would take O(N log N) time. This turns out to be how long it takes to sort any collection of items when they must be compared.

Best/Worst Case

You arrive at the party and need to find Inigo - how long will it take? It depends on when you arrive. If everyone is milling around you've hit the worst-case: it will take O(N) time. However, if everyone is sitting down at the table, it will take only O(log N) time. Or maybe you can leverage the host's wineglass-shouting power and it will take only O(1) time.

Assuming the host is unavailable, we can say that the Inigo-finding algorithm has a lower-bound of O(log N) and an upper-bound of O(N), depending on the state of the party when you arrive.

Space & Communication

The same ideas can be applied to understanding how algorithms use space or communication.

Knuth has written a nice paper about the former entitled "The Complexity of Songs".

Theorem 2: There exist arbitrarily long songs of complexity O(1).

PROOF: (due to Casey and the Sunshine Band). Consider the songs Sk defined by (15), but with

V_k = 'That's the way,' U 'I like it, ' U
U   = 'uh huh,' 'uh huh'

for all k.

How to set app icon for Electron / Atom Shell App

Updated package.json:

"build": {
  "appId": "",
  "productName": "MyApp",
  "copyright": "Copyright © 2019 ${author}",
  "mac": {
    "icon": "./public/icons/mac/icon.icns",     <---------- set Mac Icons
    "category": ""
  "win": {
    "icon": "./public/icons/png/256x256.png" <---------- set Win Icon
  "files": [
    "./public/**/*",       <---------- need for get access to icons
  "directories": {
    "buildResources": "public" <---------- folder where placed icons

After build application you can see icons. This solution don't show icons in developer mode. I don't setup icons in new BrowserWindow().

Why is Dictionary preferred over Hashtable in C#?

FYI: In .NET, Hashtable is thread safe for use by multiple reader threads and a single writing thread, while in Dictionary public static members are thread safe, but any instance members are not guaranteed to be thread safe.

We had to change all our Dictionaries back to Hashtable because of this.

jQuery change input text value

When set the new value of element, you need call trigger change.


git clone from another directory

cd /d c:\
git clone C:\folder1 folder2

From the documentation for git clone:

For local repositories, also supported by git natively, the following syntaxes may be used:



These two syntaxes are mostly equivalent, except the former implies --local option.

PDO with INSERT INTO through prepared statements

Please add try catch also in your code so that you can be sure that there in no exception.

try {
    $hostname = "servername";
    $dbname = "dbname";
    $username = "username";
    $pw = "password";
    $pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";

Python Pandas counting and summing specific conditions

I usually use numpy sum over the logical condition column:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)

This seems to me slightly shorter than the solution presented above

"X does not name a type" error in C++

It is always encouraged in C++ that you have one class per header file, see this discussion in SO [1]. GManNickG answer's tells why this happen. But the best way to solve this is to put User class in one header file (User.h) and MyMessageBox class in another header file (MyMessageBox.h). Then in your User.h you include MyMessageBox.h and in MyMessageBox.h you include User.h. Do not forget "include gaurds" [2] so that your code compiles successfully.

Are the decimal places in a CSS width respected?

They seem to round up the values to the closest integer; but Iam seeing inconsistency in chrome,safari and firefox.

For e.g if 33.3% converts to 420.945px

chrome and firexfox show it as 421px. while safari shows its as 420px.

This seems like chrome and firefox follow the floor and ceil logic while safari doesn't. This page seems to discuss the same problem

Concatenating Column Values into a Comma-Separated List

If you are running on SQL Server 2017 or Azure SQL Database you do something like this :

 SELECT STRING_AGG(CarName,',') as CarNames

AngularJS ui-router login authentication

First you'll need a service that you can inject into your controllers that has some idea of app authentication state. Persisting auth details with local storage is a decent way to approach it.

Next, you'll need to check the state of auth right before state changes. Since your app has some pages that need to be authenticated and others that don't, create a parent route that checks auth, and make all other pages that require the same be a child of that parent.

Finally, you'll need some way to tell if your currently logged in user can perform certain operations. This can be achieved by adding a 'can' function to your auth service. Can takes two parameters: - action - required - (ie 'manage_dashboards' or 'create_new_dashboard') - object - optional - object being operated on. For example, if you had a dashboard object, you may want to check to see if dashboard.ownerId === (Of course, information passed from the client should never be trusted and you should always verify this on the server before writing it to your database).

angular.module('myApp', ['ngStorage']).config([
) {
     .state('home', {...}) //not authed
     .state('sign-up', {...}) //not authed
     .state('login', {...}) //not authed
     .state('authed', {...}) //authed, make all authed states children
     .state('authed.dashboard', {...})
.service('context', [
) {
   var _user = $localStorage.get('user');
   return {
      getUser: function() {
         return _user;
      authed: function() {
         return (_user !== null);
      // server should return some kind of token so the app 
      // can continue to load authenticated content without having to
      // re-authenticate each time
      login: function() {
         return $'/login.json').then(function(reply) {
            if (reply.authenticated === true) {
               $localStorage.set(_userKey, reply.user);
      // this request should expire that token, rendering it useless
      // for requests outside of this session
      logout: function() {
         return $'logout.json').then(function(reply) {
            if (reply.authenticated === true) {
               $localStorage.set(_userKey, reply.user);
      can: function(action, object) {
         if (!this.authed()) {
            return false;

         var user = this.getUser();

         if (user && user.type === 'admin') {
             return true;

         switch(action) {
            case 'manage_dashboards':
               return (user.type === 'manager');

         return false;

.controller('AuthCtrl', [
) {
   $scope.$root.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
      //only require auth if we're moving to another authed page
      if (toState &&'authed') > -1) {

   function requireAuth() {
      if (!context.authed()) {

** DISCLAIMER: The above code is pseudo-code and comes with no guarantees **

Center a DIV horizontally and vertically

Here's a demo:

A method (JSFiddle example)


html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
#content {
    display: table-cell;
    text-align: center;
    vertical-align: middle;


<div id="content">
    Content goes here

Another method (JSFiddle example)


body, html, #wrapper {
    width: 100%;
    height: 100%
#wrapper {
    display: table
#main {
    display: table-cell;
    vertical-align: middle;


<div id="wrapper">
<div id="main">
    Content goes here

Clear form fields with jQuery

Add hidden reset button as follows

<input id="resetBtn" type="reset" value="reset" style="display:none" />
// Call reset buttons click event
// Similar to ClearInputs('resetBtn');
function ClearInputs(btnSelector) {
     var btn = $("#" + btnSelector);;

How can I delete using INNER JOIN with SQL Server?

Here is my SQL Server version

DECLARE @ProfileId table(Id bigint)

OUTPUT deleted.ProfileId INTO @ProfileId
WHERE Email = @email

DELETE FROM UserProfiles    
WHERE Id = (Select Id FROM @ProfileId)

Java: how to represent graphs?

A simple representation written by 'Robert Sedgwick' and 'Kevin Wayne' is available at

Explanation copied from the above page.

The Graph class represents an undirected graph of vertices named 0 through V - 1.

It supports the following two primary operations: add an edge to the graph, iterate over all of the vertices adjacent to a vertex. It also provides methods for returning the number of vertices V and the number of edges E. Parallel edges and self-loops are permitted. By convention, a self-loop v-v appears in the adjacency list of v twice and contributes two to the degree of v.

This implementation uses an adjacency-lists representation, which is a vertex-indexed array of Bag objects. All operations take constant time (in the worst case) except iterating over the vertices adjacent to a given vertex, which takes time proportional to the number of such vertices.

Compiler error: "class, interface, or enum expected"

Look at your function s definition. If you forget using "()" after function declaration somewhere, you ll get plenty of errors with the same format:

 ... ??: class, interface, or enum expected ...

And also you have forgot closing bracket after your class or function definition ends. But note that these missing bracket, is not the only reason for this type of error.

How to include file in a bash shell script

Syntax is source <file-name>

ex. source

script -

EMAIL="[email protected]"

calling script -

echo Welcome ${USERNAME}!
echo Your email is ${EMAIL}.

You can learn to include a bash script in another bash script here.

How to import spring-config.xml of one project into spring-config.xml of another project?

A small variation of Sean's answer:

<import resource="classpath*:spring-config.xml" />

With the asterisk in order to spring search files 'spring-config.xml' anywhere in the classpath.

Another reference: Divide Spring configuration across multiple projects

Spring classpath prefix difference

What does "&" at the end of a linux command mean?

When not told otherwise commands take over the foreground. You only have one "foreground" process running in a single shell session. The & symbol instructs commands to run in a background process and immediately returns to the command line for additional commands.

sh &

A background process will not stay alive after the shell session is closed. SIGHUP terminates all running processes. By default anyway. If your command is long-running or runs indefinitely (ie: microservice) you need to pr-pend it with nohup so it remains running after you disconnect from the session:

nohup sh &

EDIT: There does appear to be a gray area regarding the closing of background processes when & is used. Just be aware that the shell may close your process depending on your OS and local configurations (particularly on CENTOS/RHEL):

Import SQL file by command line in Windows 7

mysql : < (for import) > (for export)

in windows, you want to take backup or import the sql file, then goto cmd prompt type the address were the mysql is installed eg:C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin> after this

C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin> mysql -u UserName -p Password DatabaseName < FileName.sql (import)

C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin> mysql -u UserName -p Password DatabaseName > FileName.sql (export)

Filtering DataGridView without changing datasource

A simpler way is to transverse the data, and hide the lines with the Visible property.

// Prevent exception when hiding rows out of view
CurrencyManager currencyManager = (CurrencyManager)BindingContext[dataGridView3.DataSource];

// Show all lines
for (int u = 0; u < dataGridView3.RowCount; u++)
    dataGridView3.Rows[u].Visible = true;

// Hide the ones that you want with the filter you want.
for (int u = 0; u < dataGridView3.RowCount; u++)
    if (dataGridView3.Rows[u].Cells[4].Value == "The filter string")
        dataGridView3.Rows[u].Visible = true;
        dataGridView3.Rows[u].Visible = false;

// Resume data grid view binding

Just an idea... it works for me.

Decode UTF-8 with Javascript

To answer the original question: here is how you decode utf-8 in javascript:


function encode_utf8(s) {
  return unescape(encodeURIComponent(s));

function decode_utf8(s) {
  return decodeURIComponent(escape(s));

We have been using this in our production code for 6 years, and it has worked flawlessly.

Note, however, that escape() and unescape() are deprecated. See this.

Select columns from result set of stored procedure

Here's a link to a pretty good document explaining all the different ways to solve your problem (although a lot of them can't be used since you can't modify the existing stored procedure.)

How to Share Data Between Stored Procedures

Gulzar's answer will work (it is documented in the link above) but it's going to be a hassle to write (you'll need to specify all 80 column names in your @tablevar(col1,...) statement. And in the future if a column is added to the schema or the output is changed it will need to be updated in your code or it will error out.

Creating a Shopping Cart using only HTML/JavaScript

For a project this size, you should stop writing pure JavaScript and turn to some of the libraries available. I'd recommend jQuery (, which allows you to select elements by css-selectors, which I recon should speed up your development quite a bit.

Example of your code then becomes;

function AddtoCart() {
  var len = $("#Items tr").length, $row, $inp1, $inp2, $cells;

  $row = $("#Items td:first").clone(true);
  $cells = $row.find("td");

  $cells.get(0).html( len );

  $inp1 = $cells.get(1).find("input:first");
  $inp1.attr("id", $inp1.attr("id") + len).val("");

  $inp2 = $cells.get(2).find("input:first");
  $inp2.attr("id", $inp2.attr("id") + len).val("");


I can see that you might not understand that code yet, but take a look at jQuery, it's easy to learn and will make this development way faster.

I would use the libraries already created specifically for js shopping carts if I were you though.

To your problem; If i look at your jsFiddle, it doesn't even seem like you have defined a table with the id Items? Maybe that's why it doesn't work?

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Look in HTML output for actual client ID

You need to look in the generated HTML output to find out the right client ID. Open the page in browser, do a rightclick and View Source. Locate the HTML representation of the JSF component of interest and take its id as client ID. You can use it in an absolute or relative way depending on the current naming container. See following chapter.

Note: if it happens to contain iteration index like :0:, :1:, etc (because it's inside an iterating component), then you need to realize that updating a specific iteration round is not always supported. See bottom of answer for more detail on that.

Memorize NamingContainer components and always give them a fixed ID

If a component which you'd like to reference by ajax process/execute/update/render is inside the same NamingContainer parent, then just reference its own ID.

<h:form id="form">
    <p:commandLink update="result"> <!-- OK! -->
    <h:panelGroup id="result" />

If it's not inside the same NamingContainer, then you need to reference it using an absolute client ID. An absolute client ID starts with the NamingContainer separator character, which is by default :.

<h:form id="form">
    <p:commandLink update="result"> <!-- FAIL! -->
<h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":result"> <!-- OK! -->
<h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":result"> <!-- FAIL! -->
<h:form id="otherform">
    <h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":otherform:result"> <!-- OK! -->
<h:form id="otherform">
    <h:panelGroup id="result" />

NamingContainer components are for example <h:form>, <h:dataTable>, <p:tabView>, <cc:implementation> (thus, all composite components), etc. You recognize them easily by looking at the generated HTML output, their ID will be prepended to the generated client ID of all child components. Note that when they don't have a fixed ID, then JSF will use an autogenerated ID in j_idXXX format. You should absolutely avoid that by giving them a fixed ID. The OmniFaces NoAutoGeneratedIdViewHandler may be helpful in this during development.

If you know to find the javadoc of the UIComponent in question, then you can also just check in there whether it implements the NamingContainer interface or not. For example, the HtmlForm (the UIComponent behind <h:form> tag) shows it implements NamingContainer, but the HtmlPanelGroup (the UIComponent behind <h:panelGroup> tag) does not show it, so it does not implement NamingContainer. Here is the javadoc of all standard components and here is the javadoc of PrimeFaces.

Solving your problem

So in your case of:

<p:tabView id="tabs"><!-- This is a NamingContainer -->
    <p:tab id="search"><!-- This is NOT a NamingContainer -->
        <h:form id="insTable"><!-- This is a NamingContainer -->
            <p:dialog id="dlg"><!-- This is NOT a NamingContainer -->
                <h:panelGrid id="display">

The generated HTML output of <h:panelGrid id="display"> looks like this:

<table id="tabs:insTable:display">

You need to take exactly that id as client ID and then prefix with : for usage in update:

<p:commandLink update=":tabs:insTable:display">

Referencing outside include/tagfile/composite

If this command link is inside an include/tagfile, and the target is outside it, and thus you don't necessarily know the ID of the naming container parent of the current naming container, then you can dynamically reference it via UIComponent#getNamingContainer() like so:

<p:commandLink update=":#{component.namingContainer.parent.namingContainer.clientId}:display">

Or, if this command link is inside a composite component and the target is outside it:

<p:commandLink update=":#{cc.parent.namingContainer.clientId}:display">

Or, if both the command link and target are inside same composite component:

<p:commandLink update=":#{cc.clientId}:display">

See also Get id of parent naming container in template for in render / update attribute

How does it work under the covers

This all is specified as "search expression" in the UIComponent#findComponent() javadoc:

A search expression consists of either an identifier (which is matched exactly against the id property of a UIComponent, or a series of such identifiers linked by the UINamingContainer#getSeparatorChar character value. The search algorithm should operates as follows, though alternate alogrithms may be used as long as the end result is the same:

  • Identify the UIComponent that will be the base for searching, by stopping as soon as one of the following conditions is met:
    • If the search expression begins with the the separator character (called an "absolute" search expression), the base will be the root UIComponent of the component tree. The leading separator character will be stripped off, and the remainder of the search expression will be treated as a "relative" search expression as described below.
    • Otherwise, if this UIComponent is a NamingContainer it will serve as the basis.
    • Otherwise, search up the parents of this component. If a NamingContainer is encountered, it will be the base.
    • Otherwise (if no NamingContainer is encountered) the root UIComponent will be the base.
  • The search expression (possibly modified in the previous step) is now a "relative" search expression that will be used to locate the component (if any) that has an id that matches, within the scope of the base component. The match is performed as follows:
    • If the search expression is a simple identifier, this value is compared to the id property, and then recursively through the facets and children of the base UIComponent (except that if a descendant NamingContainer is found, its own facets and children are not searched).
    • If the search expression includes more than one identifier separated by the separator character, the first identifier is used to locate a NamingContainer by the rules in the previous bullet point. Then, the findComponent() method of this NamingContainer will be called, passing the remainder of the search expression.

Note that PrimeFaces also adheres the JSF spec, but RichFaces uses "some additional exceptions".

"reRender" uses UIComponent.findComponent() algorithm (with some additional exceptions) to find the component in the component tree.

Those additional exceptions are nowhere in detail described, but it's known that relative component IDs (i.e. those not starting with :) are not only searched in the context of the closest parent NamingContainer, but also in all other NamingContainer components in the same view (which is a relatively expensive job by the way).

Never use prependId="false"

If this all still doesn't work, then verify if you aren't using <h:form prependId="false">. This will fail during processing the ajax submit and render. See also this related question: UIForm with prependId="false" breaks <f:ajax render>.

Referencing specific iteration round of iterating components

It was for long time not possible to reference a specific iterated item in iterating components like <ui:repeat> and <h:dataTable> like so:

<h:form id="form">
    <ui:repeat id="list" value="#{['one','two','three']}" var="item">
        <h:outputText id="item" value="#{item}" /><br/>

    <h:commandButton value="Update second item">
        <f:ajax render=":form:list:1:item" />

However, since Mojarra 2.2.5 the <f:ajax> started to support it (it simply stopped validating it; thus you would never face the in the question mentioned exception anymore; another enhancement fix is planned for that later).

This only doesn't work yet in current MyFaces 2.2.7 and PrimeFaces 5.2 versions. The support might come in the future versions. In the meanwhile, your best bet is to update the iterating component itself, or a parent in case it doesn't render HTML, like <ui:repeat>.

When using PrimeFaces, consider Search Expressions or Selectors

PrimeFaces Search Expressions allows you to reference components via JSF component tree search expressions. JSF has several builtin:

  • @this: current component
  • @form: parent UIForm
  • @all: entire document
  • @none: nothing

PrimeFaces has enhanced this with new keywords and composite expression support:

  • @parent: parent component
  • @namingcontainer: parent UINamingContainer
  • @widgetVar(name): component as identified by given widgetVar

You can also mix those keywords in composite expressions such as @form:@parent, @this:@parent:@parent, etc.

PrimeFaces Selectors (PFS) as in @(.someclass) allows you to reference components via jQuery CSS selector syntax. E.g. referencing components having all a common style class in the HTML output. This is particularly helpful in case you need to reference "a lot of" components. This only prerequires that the target components have all a client ID in the HTML output (fixed or autogenerated, doesn't matter). See also How do PrimeFaces Selectors as in update="@(.myClass)" work?

Seeking useful Eclipse Java code templates

The following code templates will both create a logger and create the right imports, if needed.


private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class);

Log4J 2

private static final Logger LOG = LogManager.getLogger(${enclosing_type}.class); 


private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);



private static final Logger LOG = Logger.getLogger(${enclosing_type}.class.getName());

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

Here is a simple approach based on @benmcdonald and others, more than one line though...

let K = [];_x000D_
for (i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {_x000D_

AngularJS Directive Restrict A vs E


  1. Using your own html element like <my-directive></my-directive> wont work on IE8 without workaround (
  2. Using your own html elements will make html validation fail.
  3. Directives with equal one parameter can done like this:

<div data-my-directive="ValueOfTheFirstParameter"></div>

Instead of this:

<my-directive my-param="ValueOfTheFirstParameter"></my-directive>

We dont use custom html elements, because if this 2 facts.

Every directive by third party framework can be written in two ways:



<div data-my-directive></div>

does the same.

Efficient evaluation of a function at every cell of a NumPy array

All above answers compares well, but if you need to use custom function for mapping, and you have numpy.ndarray, and you need to retain the shape of array.

I have compare just two, but it will retain the shape of ndarray. I have used the array with 1 million entries for comparison. Here I use square function. I am presenting the general case for n dimensional array. For two dimensional just make iter for 2D.

import numpy, time

def A(e):
    return e * e

def timeit():
    y = numpy.arange(1000000)
    now = time.time()
    numpy.array([A(x) for x in y.reshape(-1)]).reshape(y.shape)        
    print(time.time() - now)
    now = time.time()
    numpy.fromiter((A(x) for x in y.reshape(-1)), y.dtype).reshape(y.shape)
    print(time.time() - now)
    now = time.time()
    print(time.time() - now)


>>> timeit()
1.162431240081787    # list comprehension and then building numpy array
1.0775556564331055   # from numpy.fromiter
0.002948284149169922 # using inbuilt function

here you can clearly see numpy.fromiter user square function, use any of your choice. If you function is dependent on i, j that is indices of array, iterate on size of array like for ind in range(arr.size), use numpy.unravel_index to get i, j, .. based on your 1D index and shape of array numpy.unravel_index

This answers is inspired by my answer on other question here

how to log in to mysql and query the database from linux terminal

To stop or start mysql on most linux systems the following should work:

/etc/init.d/mysqld stop

/etc/init.d/mysqld start

The other answers look good for accessing the mysql client from the command line.

Good luck!

Select tableview row programmatically

Use this category to select a table row and execute a given segue after a delay.
Call this within your viewDidAppear method:

[tableViewController delayedSelection:withSegueIdentifier:]

@implementation UITableViewController (TLUtils)

-(void)delayedSelection:(NSIndexPath *)idxPath withSegueIdentifier:(NSString *)segueID {
    if (!idxPath) idxPath = [NSIndexPath indexPathForRow:0 inSection:0];                                                                                                                                                                 
    [self performSelector:@selector(selectIndexPath:) withObject:@{@"NSIndexPath": idxPath, @"UIStoryboardSegue": segueID } afterDelay:0];                                                                                               

-(void)selectIndexPath:(NSDictionary *)args {
    NSIndexPath *idxPath = args[@"NSIndexPath"];                                                                                                                                                                                         
    [self.tableView selectRowAtIndexPath:idxPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];                                                                                                                            

    if ([self.tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)])
        [self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:idxPath];                                                                                                                                              

    [self performSegueWithIdentifier:args[@"UIStoryboardSegue"] sender:self];                                                                                                                                                            


Thread-safe List<T> property

Even as it got the most votes, one usually can't take System.Collections.Concurrent.ConcurrentBag<T> as a thread-safe replacement for System.Collections.Generic.List<T> as it is (Radek Stromský already pointed it out) not ordered.

But there is a class called System.Collections.Generic.SynchronizedCollection<T> that is already since .NET 3.0 part of the framework, but it is that well hidden in a location where one does not expect it that it is little known and probably you have never ever stumbled over it (at least I never did).

SynchronizedCollection<T> is compiled into assembly System.ServiceModel.dll (which is part of the client profile but not of the portable class library).

Copy all values in a column to a new column in a pandas dataframe

You can simply assign the B to the new column , Like -

df['D'] = df['B']

Example/Demo -

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([['a.1','b.1','c.1'],['a.2','b.2','c.2'],['a.3','b.3','c.3']],columns=['A','B','C'])

In [3]: df
     A    B    C
0  a.1  b.1  c.1
1  a.2  b.2  c.2
2  a.3  b.3  c.3

In [4]: df['D'] = df['B']                  #<---What you want.

In [5]: df
     A    B    C    D
0  a.1  b.1  c.1  b.1
1  a.2  b.2  c.2  b.2
2  a.3  b.3  c.3  b.3

In [6]: df.loc[0,'D'] = 'd.1'

In [7]: df
     A    B    C    D
0  a.1  b.1  c.1  d.1
1  a.2  b.2  c.2  b.2
2  a.3  b.3  c.3  b.3

How can I center text (horizontally and vertically) inside a div block?

# Parent

# Child
  display: table-cell;
  width: 100%; // As large as its parent to center the text horizontally
  text-align: center;
  vertical-align: middle; // Vertically align this element on its parent

Touch move getting stuck Ignored attempt to cancel a touchmove

Calling preventDefault on touchmove while you're actively scrolling is not working in Chrome. To prevent performance issues, you cannot interrupt a scroll.

Try to call preventDefault() from touchstart and everything should be ok.

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

I also had this issue. I'm using IntelliJ IDEA. I was using src/main/java for configuration files and src/test/java for test files.
Because of this testNG couldn't find the class path. To prevent getting that error need to move all the files from src/main/java to src/test/java or vice versa.

How can I revert a single file to a previous version?

You can take a diff that undoes the changes you want and commit that.

E.g. If you want to undo the changes in the range, do the following

git diff to..from > foo.diff  # get a reverse diff
patch < foo.diff
git commit -a -m "Undid changes".

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

React.js: Wrapping one component into another

Using children

const Wrapper = ({children}) => (

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = ({name}) => (
    <App name={name}/>

render(<WrappedApp name="toto"/>,node);

This is also known as transclusion in Angular.

children is a special prop in React and will contain what is inside your component's tags (here <App name={name}/> is inside Wrapper, so it is the children

Note that you don't necessarily need to use children, which is unique for a component, and you can use normal props too if you want, or mix props and children:

const AppLayout = ({header,footer,children}) => (
  <div className="app">
    <div className="header">{header}</div>
    <div className="body">{children}</div>
    <div className="footer">{footer}</div>

const appElement = (


This is simple and fine for many usecases, and I'd recommend this for most consumer apps.

render props

It is possible to pass render functions to a component, this pattern is generally called render prop, and the children prop is often used to provide that callback.

This pattern is not really meant for layout. The wrapper component is generally used to hold and manage some state and inject it in its render functions.

Counter example:

const Counter = () => (
  <State initial={0}>
    {(val, set) => (
      <div onClick={() => set(val + 1)}>  
        clicked {val} times

You can get even more fancy and even provide an object

<Promise promise={somePromise}>
    loading: () => <div>...</div>,
    success: (data) => <div>{data.something}</div>,
    error: (e) => <div>{e.message}</div>,

Note you don't necessarily need to use children, it is a matter of taste/API.

  renderLoading={() => <div>...</div>}
  renderSuccess={(data) => <div>{data.something}</div>}
  renderError={(e) => <div>{e.message}</div>}

As of today, many libraries are using render props (React context, React-motion, Apollo...) because people tend to find this API more easy than HOC's. react-powerplug is a collection of simple render-prop components. react-adopt helps you do composition.

Higher-Order Components (HOC).

const wrapHOC = (WrappedComponent) => {
  class Wrapper extends React.PureComponent {
    render() {
      return (
          <div><WrappedComponent {...this.props}/></div>
  return Wrapper;

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = wrapHOC(App);

render(<WrappedApp name="toto"/>,node);

An Higher-Order Component / HOC is generally a function that takes a component and returns a new component.

Using an Higher-Order Component can be more performant than using children or render props, because the wrapper can have the ability to short-circuit the rendering one step ahead with shouldComponentUpdate.

Here we are using PureComponent. When re-rendering the app, if the WrappedApp name prop does not change over time, the wrapper has the ability to say "I don't need to render because props (actually, the name) are the same as before". With the children based solution above, even if the wrapper is PureComponent, it is not the case because the children element is recreated everytime the parent renders, which means the wrapper will likely always re-render, even if the wrapped component is pure. There is a babel plugin that can help mitigate this and ensure a constant children element over time.


Higher-Order Components can give you better performance. It's not so complicated but it certainly looks unfriendly at first.

Don't migrate your whole codebase to HOC after reading this. Just remember that on critical paths of your app you might want to use HOCs instead of runtime wrappers for performance reasons, particularly if the same wrapper is used a lot of times it's worth considering making it an HOC.

Redux used at first a runtime wrapper <Connect> and switched later to an HOC connect(options)(Comp) for performance reasons (by default, the wrapper is pure and use shouldComponentUpdate). This is the perfect illustration of what I wanted to highlight in this answer.

Note if a component has a render-prop API, it is generally easy to create a HOC on top of it, so if you are a lib author, you should write a render prop API first, and eventually offer an HOC version. This is what Apollo does with <Query> render-prop component, and the graphql HOC using it.

Personally, I use both, but when in doubt I prefer HOCs because:

  • It's more idiomatic to compose them (compose(hoc1,hoc2)(Comp)) compared to render props
  • It can give me better performances
  • I'm familiar with this style of programming

I don't hesitate to use/create HOC versions of my favorite tools:

  • React's Context.Consumer comp
  • Unstated's Subscribe
  • using graphql HOC of Apollo instead of Query render prop

In my opinion, sometimes render props make the code more readable, sometimes less... I try to use the most pragmatic solution according to the constraints I have. Sometimes readability is more important than performances, sometimes not. Choose wisely and don't bindly follow the 2018 trend of converting everything to render-props.

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
    // ...

How to Convert double to int in C?

main() {
    double a;
    int b;
    printf("b is %d",b);

output is :b is 3669

when you write b=a; then its automatically converted in int

see on-line compiler result :

This is called Implicit Type Conversion Read more here

How to use XPath in Python?

Another library is 4Suite:

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

How to check if a string contains only numbers?

You may just remove all spaces and leverage LINQ All:

Determines whether all elements of a sequence satisfy a condition.

Use it as shown below:

Dim number As String = "077 234 211"
If number.Replace(" ", "").All(AddressOf Char.IsDigit) Then
    Console.WriteLine("The string is all numeric (spaces ignored)!")
    Console.WriteLine("The string contains a char that is not numeric and space!")
End If

To only check if a string consists of only digits use:

If number.All(AddressOf Char.IsDigit) Then

Replace Div Content onclick

Try This:

I think that you want something like this.


<div id="1">
    My Content 1

<div id="2" style="display:none;">
    My Dynamic Content
<button id="btnClick">Click me!</button>


}else if($('#2').css('display')!='none'){

JsFiddle: <--- see this I hope You want something like this.

User GETDATE() to put current date into SQL variable

DECLARE @LastChangeDate as date 
SET @LastChangeDate = GETDATE() 

Need to perform Wildcard (*,?, etc) search on a string using Regex

You must escape special Regex symbols in input wildcard pattern (for example pattern *.txt will equivalent to ^.*\.txt$) So slashes, braces and many special symbols must be replaced with @"\" + s, where s - special Regex symbol.

Converting byte array to String (Java)

The previous answer from Andreas_D is good. I'm just going to add that wherever you are displaying the output there will be a font and a character encoding and it may not support some characters.

To work out whether it is Java or your display that is a problem, do this:

    for(int i=0;i<str.length();i++) {
        char ch = str.charAt(i);
        System.out.println(i+" : "+ch+" "+Integer.toHexString(ch)+((ch=='\ufffd') ? " Unknown character" : ""));

Java will have mapped any characters it cannot understand to 0xfffd the official character for unknown characters. If you see a '?' in the output, but it is not mapped to 0xfffd, it is your display font or encoding that is the problem, not Java.

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

Your Custom AuthenticationProvider class should be annotated with the following:


This will make sure the presence of the hibernate session there as well.

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

the below lines would also work


Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

How to make zsh run as a login shell on Mac OS X (in iTerm)?

In iTerm -> Preferences -> Profiles Tab -> General section set Command to: /bin/zsh --login

/bin/zsh --login

How do I convert a IPython Notebook into a Python file via commandline?

Here is a quick and dirty way to extract the code from V3 or V4 ipynb without using ipython. It does not check cell types, etc.

import sys,json

f = open(sys.argv[1], 'r') #input.ipynb
j = json.load(f)
of = open(sys.argv[2], 'w')
if j["nbformat"] >=4:
        for i,cell in enumerate(j["cells"]):
                of.write("#cell "+str(i)+"\n")
                for line in cell["source"]:
        for i,cell in enumerate(j["worksheets"][0]["cells"]):
                of.write("#cell "+str(i)+"\n")
                for line in cell["input"]:


how to redirect to external url from c# controller

Try this:

return Redirect("");

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

Javascript onload not working

You can try use in javascript:

window.onload = function() {
 alert("let's go!");

Its a good practice separate javascript of html

Best way to do multiple constructors in PHP

This question has already been answered with very smart ways to fulfil the requirement but I am wondering why not take a step back and ask the basic question of why do we need a class with two constructors? If my class needs two constructors then probably the way I am designing my classes needs little more consideration to come up with a design that is cleaner and more testable.

We are trying to mix up how to instantiate a class with the actual class logic.

If a Student object is in a valid state, then does it matter if it was constructed from the row of a DB or data from a web form or a cli request?

Now to answer the question that that may arise here that if we don't add the logic of creating an object from db row, then how do we create an object from the db data, we can simply add another class, call it StudentMapper if you are comfortable with data mapper pattern, in some cases you can use StudentRepository, and if nothing fits your needs you can make a StudentFactory to handle all kinds of object construction tasks.

Bottomline is to keep persistence layer out of our head when we are working on the domain objects.

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

This post is right from SAP on Sep 20, 2012.

In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.

If you want to download that version you can find it here.

Further, service packs etc. when released can be found here.

I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.

How can I find out what version of git I'm running?

If you're using the command-line tools, running git --version should give you the version number.

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

How to debug when Kubernetes nodes are in 'Not Ready' state

I recently started using VMWare Octant This is a better UI than the Kubernetes Dashboard. You can view the Kubernetes cluster and look at the details of the cluster and the PODS. This will allow you to check the logs and open a terminal into the POD(s).

Add zero-padding to a string

"1".PadLeft(4, '0');

What is the optimal algorithm for the game 2048?

I'm the author of the AI program that others have mentioned in this thread. You can view the AI in action or read the source.

Currently, the program achieves about a 90% win rate running in javascript in the browser on my laptop given about 100 milliseconds of thinking time per move, so while not perfect (yet!) it performs pretty well.

Since the game is a discrete state space, perfect information, turn-based game like chess and checkers, I used the same methods that have been proven to work on those games, namely minimax search with alpha-beta pruning. Since there is already a lot of info on that algorithm out there, I'll just talk about the two main heuristics that I use in the static evaluation function and which formalize many of the intuitions that other people have expressed here.


This heuristic tries to ensure that the values of the tiles are all either increasing or decreasing along both the left/right and up/down directions. This heuristic alone captures the intuition that many others have mentioned, that higher valued tiles should be clustered in a corner. It will typically prevent smaller valued tiles from getting orphaned and will keep the board very organized, with smaller tiles cascading in and filling up into the larger tiles.

Here's a screenshot of a perfectly monotonic grid. I obtained this by running the algorithm with the eval function set to disregard the other heuristics and only consider monotonicity.

A perfectly monotonic 2048 board


The above heuristic alone tends to create structures in which adjacent tiles are decreasing in value, but of course in order to merge, adjacent tiles need to be the same value. Therefore, the smoothness heuristic just measures the value difference between neighboring tiles, trying to minimize this count.

A commenter on Hacker News gave an interesting formalization of this idea in terms of graph theory.

Here's a screenshot of a perfectly smooth grid, courtesy of this excellent parody fork.

A perfectly smooth 2048 board

Free Tiles

And finally, there is a penalty for having too few free tiles, since options can quickly run out when the game board gets too cramped.

And that's it! Searching through the game space while optimizing these criteria yields remarkably good performance. One advantage to using a generalized approach like this rather than an explicitly coded move strategy is that the algorithm can often find interesting and unexpected solutions. If you watch it run, it will often make surprising but effective moves, like suddenly switching which wall or corner it's building up against.


Here's a demonstration of the power of this approach. I uncapped the tile values (so it kept going after reaching 2048) and here is the best result after eight trials.


Yes, that's a 4096 alongside a 2048. =) That means it achieved the elusive 2048 tile three times on the same board.

How to toggle font awesome icon on click?

You can change the code by using class definition for the i element:

<a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>

Then you can switch the classes rapresenting the plus/minus state using toggleClass with multiple classes:

$('#category-tabs li a').click(function(){
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle');


How to create a timer using tkinter?

I just created a simple timer using the MVP pattern (however it may be overkill for that simple project). It has quit, start/pause and a stop button. Time is displayed in HH:MM:SS format. Time counting is implemented using a thread that is running several times a second and the difference between the time the timer has started and the current time.

Source code on github

Why can't overriding methods throw exceptions broader than the overridden method?

say you have super class A with method M1 throwin E1 and class B deriving from A with method M2 overriding M1. M2 can not throw anything DIFFERENT or LESS SPECIALIZED than E1.

Because of polymorphism, the client using class A should be able to treat B as if it were A. Inharitance ===> Is-a (B is-a A). What if this code dealing with class A was handling exception E1, as M1 declares it throws this checked exception, but then different type of exception was thrown? If M1 was throwing IOException M2 could well throw FileNotFoundException, as it is-a IOException. Clients of A could handle this without a problem. If the exception thrown was wider, clients of A would not have a chance of knowing about this and therefore would not have a chance to catch it.

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

How to set base url for rest in spring boot?

I might be a bit late, BUT... I believe it is the best solution. Set it up in your application.yml (or analogical config file):

            basePath: /api

As I can remember that's it - all of your repositories will be exposed beneath this URI.

Double quotes within php script echo

You need to escape ", so it won't be interpreted as end of string. Use \ to escape it:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

Read more: strings and escape sequences

What are these ^M's that keep showing up in my files in emacs?

^M is 0x0d, i.e. the carriage return character. If your display looks like

line 1^M
line 2^M

then the file must have come from Windows because the standard newline sequence on Windows is CR LF (0x0d 0x0a) whereas the standard newline sequence consists solely of LF on Unices.

If the file had come from a Mac OS 9 or earlier system, you would see it as

line 1^Mline 2^M

because there would be no line feeds following the carriage returns.

Display back button on action bar

Add below code in the onCreate function:


And then override: @Override public boolean onOptionsItemSelected(MenuItem item){ onBackPressed(); return true; }

How Best to Compare Two Collections in Java and Act on Them?

public static boolean doCollectionsContainSameElements(
        Collection<Integer> c1, Collection<Integer> c2){

    if (c1 == null || c2 == null) {
        return false;
    else if (c1.size() != c2.size()) {
        return false;
    } else {    
        return c1.containsAll(c2) && c2.containsAll(c1);

iterating over each character of a String in ruby 1.8.6 (each_char)

I have the same problem. I usually resort to String#split:

"ABCDEFG".split("").each do |i|
  puts i

I guess you could also implement it yourself like this:

class String
  def each_char
    self.split("").each { |i| yield i }

Edit: yet another alternative is String#each_byte, available in Ruby 1.8.6, which returns the ASCII value of each char in an ASCII string:

"ABCDEFG".each_byte do |i|
  puts i.chr # Fixnum#chr converts any number to the ASCII char it represents

MVC razor form with multiple different submit buttons?

As well as @Pablo's answer, for newer versions you can also use the asp-page-handler tag helper.

In the page:

<button asp-page-handler="Action1" type="submit">Action 1</button>
<button asp-page-handler="Action2" type="submit">Action 2</button>

then in the controller:

    public async Task OnPostAction1Async() {...}
    public async Task OnPostAction2Async() {...}

Export HTML table to pdf using jspdf

Here is working example:

in head

<script type="text/javascript" src="jspdf.debug.js"></script>


<script type="text/javascript">
        function demoFromHTML() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            // source can be HTML-formatted string, or a reference
            // to an actual DOM element from which the text will be scraped.
            source = $('#customers')[0];

            // we support special element handlers. Register them with jQuery-style 
            // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
            // There is no support for any other type of selectors 
            // (class, of compound) at this time.
            specialElementHandlers = {
                // element with id of "bypass" - jQuery style selector
                '#bypassme': function(element, renderer) {
                    // true = "handled elsewhere, bypass text extraction"
                    return true
            margins = {
                top: 80,
                bottom: 60,
                left: 40,
                width: 522
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
                    source, // HTML string or DOM elem ref.
                    margins.left, // x coord
          , {// y coord
                        'width': margins.width, // max width of content on PDF
                        'elementHandlers': specialElementHandlers
            function(dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
            , margins);

and table:

<div id="customers">
        <table id="tab_customers" class="table table-striped" >
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <tr class='warning'>
                    <td>March 24, 2014</td>
                    <td>March 24, 2014</td>
                    <td>United States</td>
                    <td>March 24, 2014</td>
                    <td>July 1, 2013</td>
                    <td>July 1, 2013</td>

and button to run:

<button onclick="javascript:demoFromHTML()">PDF</button>

and working example online:

tabel to pdf jspdf

or try this: HTML Table Export

How do I get the offset().top value of an element without using jQuery?

use getBoundingClientRect if $el is the actual DOM object:

var top = $el.getBoundingClientRect().top;


Fiddle will show that this will get the same value that jquery's offset top will give you

Edit: as mentioned in comments this does not account for scrolled content, below is the code that jQuery uses (5/13/2015)

offset: function( options ) {

    var docElem, win, rect, doc,
        elem = this[ 0 ];

    if ( !elem ) {

    rect = elem.getBoundingClientRect();

    // Make sure element is not hidden (display: none) or disconnected
    if ( rect.width || rect.height || elem.getClientRects().length ) {
        doc = elem.ownerDocument;
        win = getWindow( doc );
        docElem = doc.documentElement;

        return {
            top: + win.pageYOffset - docElem.clientTop,
            left: rect.left + win.pageXOffset - docElem.clientLeft

How to prevent rm from reporting that a file was not found?

\rm -f file will never report not found.

What is the easiest way to clear a database from the CLI with in Django?

If you don't care about data:

Best way would be to drop the database and run syncdb again. Or you can run:

For Django >= 1.5

python flush

For Django < 1.5

python reset appname

(you can add --no-input to the end of the command for it to skip the interactive prompt.)

If you do care about data:

From the docs:

syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.

If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.

Reference: FAQ -

People also recommend South ( ), but I haven't tried it.

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

Simple solution is to run this query: mysql -h yourhostname -u username -p databasename < yoursqlfile.sql

And if you want to import with progress bar, try this: pv yoursqlfile.sql | mysql -uxxx -pxxxx databasename

Bootstrap button - remove outline on Chrome OS X

If the above answers still do not work, add this:

    outline: none!important;

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions


Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....

    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

jQuery hyperlinks - href value?

Add return false to the end of your click handler, this prevents the browser default handler occurring which attempts to redirect the page:

$('a').click(function() {
// do stuff
return false;

How to iterate through a table rows and get the cell values using jQuery

You got your answer, but why iterate over the tr when you can go straight for the inputs? That way you can store them easier into an array and it reduce the number of CSS queries. Depends what you want to do of course, but for collecting data it is a more flexible approach.

var array = [];

$("tr.item input").each(function() {
        name: $(this).attr('class'),
        value: $(this).val()


How to keep Docker container running after starting services?


There is nothing wrong in running multiple processes inside of a docker container. If one likes to use docker as a light weight VM - so be it. Others like to split their applications into micro services. Me thinks: A LAMP stack in one container? Just great.

The answer:

Stick with a good base image like the phusion base image. There may be others. Please comment.

And this is yet just another plead for supervisor. Because the phusion base image is providing supervisor besides of some other things like cron and locale setup. Stuff you like to have setup when running such a light weight VM. For what it's worth it also provides ssh connections into the container.

The phusion image itself will just start and keep running if you issue this basic docker run statement:

moin@stretchDEV:~$ docker run -d phusion/baseimage
moin@stretchDEV:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS
521e8a12f6ff        phusion/baseimage   "/sbin/my_init"     12 seconds ago      Up 11 seconds

Or dead simple:

If a base image is not for you... For the quick CMD to keep it running I would suppose something like this for bash:

CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"

Or this for busybox:

CMD exec /bin/sh -c "trap : TERM INT; (while true; do sleep 1000; done) & wait"

This is nice, because it will exit immediately on a docker stop. Just plain sleep or cat will take a few seconds before the container exits.

Returning an array using C

You can do it using heap memory (through malloc() invocation) like other answers reported here, but you must always manage the memory (use free() function everytime you call your function). You can also do it with a static array:

char* returnArrayPointer() 
static char array[SIZE];

// do something in your array here

return array; 

You can than use it without worrying about memory management.

int main() 
char* myArray = returnArrayPointer();
/* use your array here */
/* don't worry to free memory here */

In this example you must use static keyword in array definition to set to application-long the array lifetime, so it will not destroyed after return statement. Of course, in this way you occupy SIZE bytes in your memory for the entire application life, so size it properly!

Could not reserve enough space for object heap to start JVM

It looks like the machine you're trying to run this on has only 256 MB memory.

Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.

Try starting your Java program with a smaller heap size, for example:

java -Xms16m ...

Manifest Merger failed with multiple errors in Android Studio

In addition to available solutions, please check this also.
If you have set android:allowBackup="false" in your AndroidManifest.xml then there may be a conflict for android:allowBackup="true" in other dependencies.

As suggested by @CLIFFORD P Y, switch to Merged Manifest in your AndroidManifest.xml. Android Studio will suggest to add tools:replace="android:allowBackup" in <application /> in your AndroidManifest.xml.

Convert String To date in PHP

If you're up for it, use the DateTime class

Encoding Javascript Object to Json string

Unless the variable k is defined, that's probably what's causing your trouble. Something like this will do what you want:

var new_tweets = { };

new_tweets.k = { };

new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875; = { }; = 'other_user'; = 'tweet text';

// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);

You can also do it all at once:

var new_tweets = {
  k: {
    tweet_id: 98745521,
    user_id: 54875,
    data: {
      in_reply_to_screen_name: 'other_user',
      text: 'tweet_text'

How to remove a file from the index in git?

According to my humble opinion and my work experience with git, staging area is not the same as index. I may be wrong of course, but as I said, my experience in using git and my logic tell me, that index is a structure that follows your changes to your working area(local repository) that are not excluded by ignoring settings and staging area is to keep files that are already confirmed to be committed, aka files in index on which add command was run on. You don't notice and realize that "slight" difference, because you use git commit -a -m "comment" adding indexed and cached files to stage area and committing in one command or using IDEs like IDEA for that too often. And cache is that what keeps changes in indexed files. If you want to remove file from index that has not been added to staging area before, options proposed before match for you, but... If you have done that already, you will need to use

Git restore --staged <file>

And, please, don't ask me where I was 10 years ago... I missed you, this answer is for further generations)

How do I download NLTK data?

I think you must have named the file as (or the folder consists of a file with that name) so change it to any other name and try executing it....

PHP preg_replace special characters

$newstr = preg_replace('/[^a-zA-Z0-9\']/', '_', "There wouldn't be any");
$newstr = str_replace("'", '', $newstr);

I put them on two separate lines to make the code a little more clear.

Note: If you're looking for Unicode support, see Filip's answer below. It will match all characters that register as letters in addition to A-z.

SOAP PHP fault parsing WSDL: failed to load external entity?

If anyone has the same problem, one possible solution is to set the bindto stream context configuration parameter (assuming you're connecting from to

$context = [
    'socket' => [
        'bindto' => ''

$options = [
    'soapVersion' => SOAP_1_1,
    'stream_context' => stream_context_create($context)

$client = new Client('', $options);

How do you check what version of SQL Server for a database using TSQL?

The KB article linked in Joe's post is great for determining which service packs have been installed for any version. Along those same lines, this KB article maps version numbers to specific hotfixes and cumulative updates, but it only applies to SQL05 SP2 and up.

Lollipop : draw behind statusBar with its color set to transparent

All you need to do is set these properties in your theme

<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>

How to get the concrete class name as a string?

you can also create a dict with the classes themselves as keys, not necessarily the classnames

    int:lambda x: x*2,
    str:lambda s:'(*(%s)*)'%s

def transform (param):
    print typefunc[type(param)](param)

transform (1)
>>> 2
transform ("hi")
>>> (*(hi)*)

here typefunc is a dict that maps a function for each type. transform gets that function and applies it to the parameter.

of course, it would be much better to use 'real' OOP

How to change workspace and build record Root Directory on Jenkins?

By default, Jenkins stores all of its data in this directory on the file system.

There are a few ways to change the Jenkins home directory:

  • Edit the JENKINS_HOME variable in your Jenkins configuration file (e.g. /etc/sysconfig/jenkins on Red Hat Linux).
  • Use your web container's admin tool to set the JENKINS_HOME environment variable.
  • Set the environment variable JENKINS_HOME before launching your web container, or before launching Jenkins directly from the WAR file.
  • Set the JENKINS_HOME Java system property when launching your web container, or when launching Jenkins directly from the WAR file.
  • Modify web.xml in jenkins.war (or its expanded image in your web container). This is not recommended. This value cannot be changed while Jenkins is running. It is shown here to help you ensure that your configuration is taking effect.

complex if statement in python

It is possible to write like this:

elif var1 in [80, 443] or 1024 < var1 < 65535

This way you check if var1 appears in that a list, then you make just 1 check, didn't repeat the "var1" one extra time, and looks clear:

if var1 in [80, 443] or 1024 < var1 < 65535: print 'good' else: print 'bad' ....:

Errors: Data path ".builders['app-shell']" should have required property 'class'

I also faced this issue and struggled hours to solve it, I have tried all of the above options but nothing solved my problem. This issue occurs due to version mismatch of angular/cli and angular-devkit, so I did the following :

  1. Manually changed version of files:

    @angular-devkit/build-angular": "^0.13.9",

    @angular/cli": "~7.0.3", //This is for Angular7, for Angular8 : 0.803.23

  2. Deleted package-lock.json

  3. Executed : npm install

It solved my problem.

Wildcards in jQuery selectors

Since the title suggests wildcard you could also use this:

<script src=""></script>_x000D_
<div id="jander1"></div>_x000D_
<div id="jander2"></div>

This will select the given string anywhere in the id.

How to create a custom attribute in C#

While the code to create a custom Attribute is fairly simple, it's very important that you understand what attributes are:

Attributes are metadata compiled into your program. Attributes themselves do not add any functionality to a class, property or module - just data. However, using reflection, one can leverage those attributes in order to create functionality.

So, for instance, let's look at the Validation Application Block, from Microsoft's Enterprise Library. If you look at a code example, you'll see:

    /// <summary>
    /// blah blah code.
    /// </summary>
    [StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
    public string Code { get; set; }

From the snippet above, one might guess that the code will always be validated, whenever changed, accordingly to the rules of the Validator (in the example, have at least 8 characters and at most 8 characters). But the truth is that the Attribute does nothing; as mentioned previously, it only adds metadata to the property.

However, the Enterprise Library has a Validation.Validate method that will look into your object, and for each property, it'll check if the contents violate the rule informed by the attribute.

So, that's how you should think about attributes -- a way to add data to your code that might be later used by other methods/classes/etc.

How to justify a single flexbox item (override justify-content)

For those situations where width of the items you do want to flex-end is known, you can set their flex to "0 0 ##px" and set the item you want to flex-start with flex:1

This will cause the pseudo flex-start item to fill the container, just format it to text-align:left or whatever.

Positioning <div> element at center of screen

Alternative solution that doesn't use position absolute:
I see a lot of position absolute answers. I couldn't use position absolute without breaking something else. So for those that couldn't as well, here is what I did: (posted in response to another question).

The solution only focuses on vertically centering because my children elements were already horizontally centered but same could be applied if you couldn't horizontally center them in another way.

How does internationalization work in JavaScript?

Mozilla recently released the awesome L20n or localization 2.0. In their own words L20n is

an open source, localization-specific scripting language used to process gender, plurals, conjugations, and most of the other quirky elements of natural language.

Their js implementation is on the github L20n repository.

how to convert date to a format `mm/dd/yyyy`


select convert(nvarchar(10), CREATED_TS, 101)


select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above

Move a view up only when the keyboard covers an input field

The accepted anwser is nearly perfect. But I need to use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey, because the latter return keyborad height 0. And change the hittest point to the bottom not origin.

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        var point = activeField.frame.origin
        point.y += activeField.frame.size.height
        if (!aRect.contains(point)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)

Python 'list indices must be integers, not tuple"

To create list of lists, you need to separate them with commas, like this

coin_args = [
    ["pennies", '2.5', '50.0', '.01'],
    ["nickles", '5.0', '40.0', '.05'],
    ["dimes", '2.268', '50.0', '.1'],
    ["quarters", '5.67', '40.0', '.25']

Find the division remainder of a number

26 % 7 (you will get remainder)

26 / 7 (you will get divisor can be float value )

26 // 7 (you will get divisor only integer value) )

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

How exactly does binary code get converted into letters?

To read binary ASCII characters with great speed using only your head:

Letters start with leading bits 01. Bit 3 is on (1) for lower case, off (0) for capitals. Scan the following bits 4–8 for the first that is on, and select the starting letter from the same index in this string: “PHDBA” (think P.H.D., Bachelors in Arts). E.g. 1xxxx = P, 01xxx = H, etc. Then convert the remaining bits to an integer value (e.g. 010 = 2), and count that many letters up from your starting letter. E.g. 01001010 => H+2 = J.

Calling a particular PHP function on form submit

An alternative, and perhaps a not so good procedural coding one, is to send the "function name" to a script that then executes the function. For instance, with a login form, there is typically the login, forgotusername, forgotpassword, signin activities that are presented on the form as buttons or anchors. All of these can be directed to/as, say,


And then a switch statement on the receiving page does any prep work and then dispatches or runs the (next) specified function.

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

You could checkout Moment.js, Luxon, date-fns or Day.js for nice date manipulation.

Or just extract the first part of your ISO string, it already contains what you want. Here is an example by splitting on the T:

"2013-03-10T02:00:00Z".split("T")[0] // "2013-03-10"

"installation of package 'FILE_PATH' had non-zero exit status" in R

For those of you who are using MacOS and like me perhaps have been circling the internet as to why some R packages do not install here is a possible help.

If you get a non-zero exit status first check to ensure all dependencies are installed as well. Read through the messaging. If that is checked off, then look for indications such as gfortran: No such a file or directory. That might be due to Apple OS compiler issues that some packages will not install unless you use their binary version. Look for binary zip file in the package page, download it and use the following command to get the package installed:

install.packages("/PATH/zip file ", repos = NULL, type="source")

SQL to Entity Framework Count Group-By

A useful extension is to collect the results in a Dictionary for fast lookup (e.g. in a loop):

var resultDict = _dbContext.Projects
    .Where(p => p.Status == ProjectStatus.Active)
    .GroupBy(f => f.Country)
    .Select(g => new { country = g.Key, count = g.Count() })
    .ToDictionary(k =>, i => i.count);

Originally found here:

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);



    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');

How to access your website through LAN in ASP.NET

If you use IIS Express via Visual Studio instead of the builtin host, you can achieve this.

Binding IIS Express to an IP Address

How to execute .sql file using powershell?

with 2008 Server 2008 and 2008 R2

Add-PSSnapin -Name SqlServerCmdletSnapin100, SqlServerProviderSnapin100

with 2012 and 2014

Import-Module -Name SQLPS -DisableNameChecking

Custom alert and confirm box in jquery

Try using SweetAlert its just simply the best . You will get a lot of customization and flexibility.

Confirm Example

    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",   
    showCancelButton: true,   
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!"

Sample Alert

Calculate a MD5 hash from a string

As per MSDN

Create MD5:

public static string CreateMD5(string input)
    // Use input string to calculate MD5 hash
    using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
        byte[] hashBytes = md5.ComputeHash(inputBytes);

        // Convert the byte array to hexadecimal string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hashBytes.Length; i++)
        return sb.ToString();

Could not load file or assembly 'Newtonsoft.Json, Version=, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I made a basic Demo and reproduced this problem. It seems that WinRT component failed to find the correct assembly of Newton.Json. Temporarily the workaround is to manually add the Newtonsoft.json.dll file. You can achieve this by following steps:

  1. Right click References-> Add Reference->Browse...-> Find C:\Users\.nuget\packages\Newtonsoft.Json\9.0.1\lib\portable-net45+wp80+win8+wpa81\Newtonsoft.json.dll->Click Add button.

  2. Rebuild your Runtime Component project and run. This error should be gone.

How to figure out the SMTP server host?

Email tech support at your client's hosting provider and ask for the information.

An "and" operator for an "if" statement in Bash

Try this:

if [ $STATUS -ne 200 -a "$STRING" != "$VALUE" ]; then

how to configuring a xampp web server for different root directory

For XAMMP versions >=7.5.9-0 also change the DocumentRoot in file "/opt/lampp/etc/extra/httpd-ssl.conf" accordingly.

How to move/rename a file using an Ansible task on a remote system

This may seem like overkill, but if you want to avoid using the command module (which I do, because it using command is not idempotent) you can use a combination of copy and unarchive.

  1. Use tar to archive the file(s) you will need. If you think ahead this actually makes sense. You may want a series of files in a given directory. Create that directory with all of the files and archive them in a tar.
  2. Use the unarchive module. When you do that, along with the destination: and remote_src: keyword, you can place copy all of your files to a temporary folder to start with and then unpack them exactly where you want to.

How to remove the Flutter debug banner?

The debug banner appears only while in development and is automatically removed in the release build.

To hide this there is a need to set debugShowCheckedModeBanner to false

  debugShowCheckedModeBanner: false,

enter image description here

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

How to squash all git commits into one?

Perhaps the easiest way is to just create a new repository with current state of the working copy. If you want to keep all the commit messages you could first do git log > original.log and then edit that for your initial commit message in the new repository:

rm -rf .git
git init
git add .
git commit


git log > original.log
# edit original.log as desired
rm -rf .git
git init
git add .
git commit -F original.log

How do you pull first 100 characters of a string in PHP

$small = substr($big, 0, 100);

For String Manipulation here is a page with a lot of function that might help you in your future work.

How to configure Eclipse build path to use Maven dependencies?

Maybe you could look into maven-eclipse-plugin instead of M2Eclipse.

There you basically add maven-eclipse-plugin configuration to your pom.xml and then execute mvn eclipse:eclipse which will generate the required .project and .classpath files for Eclipse. Then you'll have the correct build path in Eclipse.

Escaping quotation marks in PHP

You can use the PHP function addslashes() to any string to make it compatible

@RequestParam in Spring MVC handling optional parameters

Create 2 methods which handle the cases. You can instruct the @RequestMapping annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods.

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"logout"})
public String handleLogout(@PathVariable("id") String id, 
        @RequestParam("logout") String logout) { ... }

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"name", "password"})
public String handleLogin(@PathVariable("id") String id, @RequestParam("name") 
        String username, @RequestParam("password") String password, 
        @ModelAttribute("submitModel") SubmitModel model, BindingResult errors) 
        throws LoginException {...}

Disable-web-security in Chrome 48+

Update 2020-04-30

As of Chrome 81, it is mandatory to pass both --disable-site-isolation-trials and a non-empty profile path via --user-data-dir in order for --disable-web-security to take effect:

# MacOS
open -na Google\ Chrome --args --user-data-dir=/tmp/temporary-chrome-profile-dir --disable-web-security --disable-site-isolation-trials

(Speculation) It is likely that Chrome requires a non-empty profile path to mitigate the high security risk of launching the browser with web security disabled on the default profile. See --user-data-dir= vs --user-data-dir=/some/path for more details below.

Thanks to @Snæbjørn for the Chrome 81 tip in the comments.

Update 2020-03-06

As of Chrome 80 (possibly even earlier), the combination of flags --user-data-dir=/tmp/some-path --disable-web-security --disable-site-isolation-trials no longer disables web security.

It is unclear when the Chromium codebase regressed, but downloading an older build of Chromium (following "Not-so-easy steps" on the Chromium download page) is the only workaround I found. I ended up using Version 77.0.3865.0, which properly disables web security with these flags.

Original Post 2019-11-01

In Chrome 67+, it is necessary to pass the --disable-site-isolation-trials flag alongside arguments --user-data-dir= and --disable-web-security to truly disable web security.

On MacOS, the full command becomes:

open -na Google\ Chrome --args --user-data-dir= --disable-web-security --disable-site-isolation-trials

Regarding --user-data-dir

Per David Amey's answer, it is still necessary to specify --user-data-dir= for Chrome to respect the --disable-web-security option.

--user-data-dir= vs --user-data-dir=/some/path

Though passing in an empty path via --user-data-dir= works with --disable-web-security, it is not recommended for security purposes as it uses your default Chrome profile, which has active login sessions to email, etc. With Chrome security disabled, your active sessions are thus vulnerable to additional in-browser exploits.

Thus, it is recommended to use an alternative directory for your Chrome profile with --user-data-dir=/tmp/chrome-sesh or equivalent. Credit to @James B for pointing this out in the comments.


This fix was discoreved within the browser testing framework Cypress:

How to get the url parameters using AngularJS

When using angularjs with express

On my example I was using angularjs with express doing the routing so using $routeParams would mess up with my routing. I used the following code to get what I was expecting:

const getParameters = (temp, path) => {
  const parameters = {};
  const tempParts = temp.split('/');
  const pathParts = path.split('/');
  for (let i = 0; i < tempParts.length; i++) {
    const element = tempParts[i];
    if(element.startsWith(':')) {
      const key = element.substring(1,element.length);
      parameters[key] = pathParts[i];
  return parameters;

This receives a URL template and the path of the given location. The I just call it with:

const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $location.path()); 

Putting it all together my controller is:

.controller('TestController', ['$scope', function($scope, $window) {
  const getParameters = (temp, path) => {
    const parameters = {};
    const tempParts = temp.split('/');
    const pathParts = path.split('/');
    for (let i = 0; i < tempParts.length; i++) {
      const element = tempParts[i];
      if(element.startsWith(':')) {
        const key = element.substring(1,element.length);
        parameters[key] = pathParts[i];
    return parameters;

const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $window.location.pathname);

The result will be:

{ table: "users", id: "1", place_id: "43", interval: "week" }

Hope this helps someone out there!

How can I remove a trailing newline?

I'm bubbling up my regular expression based answer from one I posted earlier in the comments of another answer. I think using re is a clearer more explicit solution to this problem than str.rstrip.

>>> import re

If you want to remove one or more trailing newline chars:

>>> re.sub(r'[\n\r]+$', '', '\nx\r\n')

If you want to remove newline chars everywhere (not just trailing):

>>> re.sub(r'[\n\r]+', '', '\nx\r\n')

If you want to remove only 1-2 trailing newline chars (i.e., \r, \n, \r\n, \n\r, \r\r, \n\n)

>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r\n')
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r')
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n')

I have a feeling what most people really want here, is to remove just one occurrence of a trailing newline character, either \r\n or \n and nothing more.

>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n\n', count=1)
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n\r\n', count=1)
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n', count=1)
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n', count=1)

(The ?: is to create a non-capturing group.)

(By the way this is not what '...'.rstrip('\n', '').rstrip('\r', '') does which may not be clear to others stumbling upon this thread. str.rstrip strips as many of the trailing characters as possible, so a string like foo\n\n\n would result in a false positive of foo whereas you may have wanted to preserve the other newlines after stripping a single trailing one.)

Using DISTINCT inner join in SQL

  LEFT JOIN B ON = B.lookupC
  LEFT JOIN A ON = A.lookupB

I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.

EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.

There is no distinct join construct you could use so just stay with what you already have :)

How do you easily horizontally center a <div> using CSS?

The best response to this question is to use margin-auto but for using it you must know the width of your div in px or %.

CSS code:


"break;" out of "if" statement?

As already mentioned that, break-statement works only with switches and loops. Here is another way to achieve what is being asked. I am reproducing as nobody else mentioned it. It's just a trick involving the do-while loop.

do {
  // do something
  if (error) {
  // do something else
  if (error) {
  // etc..
} while (0);

Though I would prefer the use of goto-statement.

java: Class.isInstance vs Class.isAssignableFrom

clazz.isAssignableFrom(Foo.class) will be true whenever the class represented by the clazz object is a superclass or superinterface of Foo.

clazz.isInstance(obj) will be true whenever the object obj is an instance of the class clazz.

That is:

clazz.isAssignableFrom(obj.getClass()) == clazz.isInstance(obj)

is always true so long as clazz and obj are nonnull.

Code for best fit straight line of a scatter plot in python

from sklearn.linear_model import LinearRegression

X, Y = x.reshape(-1,1), y.reshape(-1,1)
plt.plot( X, LinearRegression().fit(X, Y).predict(X) )