Programs & Examples On #Resharper 5.1

Validating email addresses using jQuery and regex

you can use this function

 var validateEmail = function (email) {

        var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;


        if (pattern.test(email)) {
            return true;
        }
        else {
            return false;
        }
    };

Angularjs on page load call function

you can use it directly with $scope instance

     $scope.init=function()
        {
            console.log("entered");
            data={};
            /*do whatever you want such as initialising scope variable,
              using $http instance etcc..*/
        }
       //simple call init function on controller
       $scope.init();

How to resolve symbolic links in a shell script

Common shell scripts often have to find their "home" directory even if they are invoked as a symlink. The script thus have to find their "real" position from just $0.

cat `mvn`

on my system prints a script containing the following, which should be a good hint at what you need.

if [ -z "$M2_HOME" ] ; then
  ## resolve links - $0 may be a link to maven's home
  PRG="$0"

  # need this for relative symlinks
  while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
      PRG="$link"
    else
      PRG="`dirname "$PRG"`/$link"
    fi
  done

  saveddir=`pwd`

  M2_HOME=`dirname "$PRG"`/..

  # make it fully qualified
  M2_HOME=`cd "$M2_HOME" && pwd`

How do you rebase the current branch's changes on top of changes being merged in?

Another way to look at it is to consider git rebase master as:

Rebase the current branch on top of master

Here , 'master' is the upstream branch, and that explain why, during a rebase, ours and theirs are reversed.

Run ssh and immediately execute command

This isn't quite what you're looking for, but I've found it useful in similar circumstances.

I recently added the following to my $HOME/.bashrc (something similar should be possible with shells other than bash):

if [ -f $HOME/.add-screen-to-history ] ; then
    history -s 'screen -dr'
fi

I keep a screen session running on one particular machine, and I've had problems with ssh connections to that machine being dropped, requiring me to re-run screen -dr every time I reconnect.

With that addition, and after creating that (empty) file in my home directory, I automatically have the screen -dr command in my history when my shell starts. After reconnecting, I can just type Control-P Enter and I'm back in my screen session -- or I can ignore it. It's flexible, but not quite automatic, and in your case it's easier than typing tmux list-sessions.

You might want to make the history -s command unconditional.

This does require updating your $HOME/.bashrc on each of the target systems, which might or might not make it unsuitable for your purposes.

Hidden TextArea

<textarea name="hide" style="display:none;"></textarea>

This sets the css display property to none, which prevents the browser from rendering the textarea.

Using @property versus getters and setters

[TL;DR? You can skip to the end for a code example.]

I actually prefer to use a different idiom, which is a little involved for using as a one off, but is nice if you have a more complex use case.

A bit of background first.

Properties are useful in that they allow us to handle both setting and getting values in a programmatic way but still allow attributes to be accessed as attributes. We can turn 'gets' into 'computations' (essentially) and we can turn 'sets' into 'events'. So let's say we have the following class, which I've coded with Java-like getters and setters.

class Example(object):
    def __init__(self, x=None, y=None):
        self.x = x
        self.y = y

    def getX(self):
        return self.x or self.defaultX()

    def getY(self):
        return self.y or self.defaultY()

    def setX(self, x):
        self.x = x

    def setY(self, y):
        self.y = y

    def defaultX(self):
        return someDefaultComputationForX()

    def defaultY(self):
        return someDefaultComputationForY()

You may be wondering why I didn't call defaultX and defaultY in the object's __init__ method. The reason is that for our case I want to assume that the someDefaultComputation methods return values that vary over time, say a timestamp, and whenever x (or y) is not set (where, for the purpose of this example, "not set" means "set to None") I want the value of x's (or y's) default computation.

So this is lame for a number of reasons describe above. I'll rewrite it using properties:

class Example(object):
    def __init__(self, x=None, y=None):
        self._x = x
        self._y = y

    @property
    def x(self):
        return self.x or self.defaultX()

    @x.setter
    def x(self, value):
        self._x = value

    @property
    def y(self):
        return self.y or self.defaultY()

    @y.setter
    def y(self, value):
        self._y = value

    # default{XY} as before.

What have we gained? We've gained the ability to refer to these attributes as attributes even though, behind the scenes, we end up running methods.

Of course the real power of properties is that we generally want these methods to do something in addition to just getting and setting values (otherwise there is no point in using properties). I did this in my getter example. We are basically running a function body to pick up a default whenever the value isn't set. This is a very common pattern.

But what are we losing, and what can't we do?

The main annoyance, in my view, is that if you define a getter (as we do here) you also have to define a setter.[1] That's extra noise that clutters the code.

Another annoyance is that we still have to initialize the x and y values in __init__. (Well, of course we could add them using setattr() but that is more extra code.)

Third, unlike in the Java-like example, getters cannot accept other parameters. Now I can hear you saying already, well, if it's taking parameters it's not a getter! In an official sense, that is true. But in a practical sense there is no reason we shouldn't be able to parameterize an named attribute -- like x -- and set its value for some specific parameters.

It'd be nice if we could do something like:

e.x[a,b,c] = 10
e.x[d,e,f] = 20

for example. The closest we can get is to override the assignment to imply some special semantics:

e.x = [a,b,c,10]
e.x = [d,e,f,30]

and of course ensure that our setter knows how to extract the first three values as a key to a dictionary and set its value to a number or something.

But even if we did that we still couldn't support it with properties because there is no way to get the value because we can't pass parameters at all to the getter. So we've had to return everything, introducing an asymmetry.

The Java-style getter/setter does let us handle this, but we're back to needing getter/setters.

In my mind what we really want is something that capture the following requirements:

  • Users define just one method for a given attribute and can indicate there whether the attribute is read-only or read-write. Properties fail this test if the attribute writable.

  • There is no need for the user to define an extra variable underlying the function, so we don't need the __init__ or setattr in the code. The variable just exists by the fact we've created this new-style attribute.

  • Any default code for the attribute executes in the method body itself.

  • We can set the attribute as an attribute and reference it as an attribute.

  • We can parameterize the attribute.

In terms of code, we want a way to write:

def x(self, *args):
    return defaultX()

and be able to then do:

print e.x     -> The default at time T0
e.x = 1
print e.x     -> 1
e.x = None
print e.x     -> The default at time T1

and so forth.

We also want a way to do this for the special case of a parameterizable attribute, but still allow the default assign case to work. You'll see how I tackled this below.

Now to the point (yay! the point!). The solution I came up for for this is as follows.

We create a new object to replace the notion of a property. The object is intended to store the value of a variable set to it, but also maintains a handle on code that knows how to calculate a default. Its job is to store the set value or to run the method if that value is not set.

Let's call it an UberProperty.

class UberProperty(object):

    def __init__(self, method):
        self.method = method
        self.value = None
        self.isSet = False

    def setValue(self, value):
        self.value = value
        self.isSet = True

    def clearValue(self):
        self.value = None
        self.isSet = False

I assume method here is a class method, value is the value of the UberProperty, and I have added isSet because None may be a real value and this allows us a clean way to declare there really is "no value". Another way is a sentinel of some sort.

This basically gives us an object that can do what we want, but how do we actually put it on our class? Well, properties use decorators; why can't we? Let's see how it might look (from here on I'm going to stick to using just a single 'attribute', x).

class Example(object):

    @uberProperty
    def x(self):
        return defaultX()

This doesn't actually work yet, of course. We have to implement uberProperty and make sure it handles both gets and sets.

Let's start with gets.

My first attempt was to simply create a new UberProperty object and return it:

def uberProperty(f):
    return UberProperty(f)

I quickly discovered, of course, that this doens't work: Python never binds the callable to the object and I need the object in order to call the function. Even creating the decorator in the class doesn't work, as although now we have the class, we still don't have an object to work with.

So we're going to need to be able to do more here. We do know that a method need only be represented the one time, so let's go ahead and keep our decorator, but modify UberProperty to only store the method reference:

class UberProperty(object):

    def __init__(self, method):
        self.method = method

It is also not callable, so at the moment nothing is working.

How do we complete the picture? Well, what do we end up with when we create the example class using our new decorator:

class Example(object):

    @uberProperty
    def x(self):
        return defaultX()

print Example.x     <__main__.UberProperty object at 0x10e1fb8d0>
print Example().x   <__main__.UberProperty object at 0x10e1fb8d0>

in both cases we get back the UberProperty which of course is not a callable, so this isn't of much use.

What we need is some way to dynamically bind the UberProperty instance created by the decorator after the class has been created to an object of the class before that object has been returned to that user for use. Um, yeah, that's an __init__ call, dude.

Let's write up what we want our find result to be first. We're binding an UberProperty to an instance, so an obvious thing to return would be a BoundUberProperty. This is where we'll actually maintain state for the x attribute.

class BoundUberProperty(object):
    def __init__(self, obj, uberProperty):
        self.obj = obj
        self.uberProperty = uberProperty
        self.isSet = False

    def setValue(self, value):
        self.value = value
        self.isSet = True

    def getValue(self):
        return self.value if self.isSet else self.uberProperty.method(self.obj)

    def clearValue(self):
        del self.value
        self.isSet = False

Now we the representation; how do get these on to an object? There are a few approaches, but the easiest one to explain just uses the __init__ method to do that mapping. By the time __init__ is called our decorators have run, so just need to look through the object's __dict__ and update any attributes where the value of the attribute is of type UberProperty.

Now, uber-properties are cool and we'll probably want to use them a lot, so it makes sense to just create a base class that does this for all subclasses. I think you know what the base class is going to be called.

class UberObject(object):
    def __init__(self):
        for k in dir(self):
            v = getattr(self, k)
            if isinstance(v, UberProperty):
                v = BoundUberProperty(self, v)
                setattr(self, k, v)

We add this, change our example to inherit from UberObject, and ...

e = Example()
print e.x               -> <__main__.BoundUberProperty object at 0x104604c90>

After modifying x to be:

@uberProperty
def x(self):
    return *datetime.datetime.now()*

We can run a simple test:

print e.x.getValue()
print e.x.getValue()
e.x.setValue(datetime.date(2013, 5, 31))
print e.x.getValue()
e.x.clearValue()
print e.x.getValue()

And we get the output we wanted:

2013-05-31 00:05:13.985813
2013-05-31 00:05:13.986290
2013-05-31
2013-05-31 00:05:13.986310

(Gee, I'm working late.)

Note that I have used getValue, setValue, and clearValue here. This is because I haven't yet linked in the means to have these automatically returned.

But I think this is a good place to stop for now, because I'm getting tired. You can also see that the core functionality we wanted is in place; the rest is window dressing. Important usability window dressing, but that can wait until I have a change to update the post.

I'll finish up the example in the next posting by addressing these things:

  • We need to make sure UberObject's __init__ is always called by subclasses.

    • So we either force it be called somewhere or we prevent it from being implemented.
    • We'll see how to do this with a metaclass.
  • We need to make sure we handle the common case where someone 'aliases' a function to something else, such as:

      class Example(object):
          @uberProperty
          def x(self):
              ...
    
          y = x
    
  • We need e.x to return e.x.getValue() by default.

    • What we'll actually see is this is one area where the model fails.
    • It turns out we'll always need to use a function call to get the value.
    • But we can make it look like a regular function call and avoid having to use e.x.getValue(). (Doing this one is obvious, if you haven't already fixed it out.)
  • We need to support setting e.x directly, as in e.x = <newvalue>. We can do this in the parent class too, but we'll need to update our __init__ code to handle it.

  • Finally, we'll add parameterized attributes. It should be pretty obvious how we'll do this, too.

Here's the code as it exists up to now:

import datetime

class UberObject(object):
    def uberSetter(self, value):
        print 'setting'

    def uberGetter(self):
        return self

    def __init__(self):
        for k in dir(self):
            v = getattr(self, k)
            if isinstance(v, UberProperty):
                v = BoundUberProperty(self, v)
                setattr(self, k, v)


class UberProperty(object):
    def __init__(self, method):
        self.method = method

class BoundUberProperty(object):
    def __init__(self, obj, uberProperty):
        self.obj = obj
        self.uberProperty = uberProperty
        self.isSet = False

    def setValue(self, value):
        self.value = value
        self.isSet = True

    def getValue(self):
        return self.value if self.isSet else self.uberProperty.method(self.obj)

    def clearValue(self):
        del self.value
        self.isSet = False

    def uberProperty(f):
        return UberProperty(f)

class Example(UberObject):

    @uberProperty
    def x(self):
        return datetime.datetime.now()

[1] I may be behind on whether this is still the case.

Callback when CSS3 transition finishes

Another option would be to use the jQuery Transit Framework to handle your CSS3 transitions. The transitions/effects perform well on mobile devices and you don't have to add a single line of messy CSS3 transitions in your CSS file in order to do the animation effects.

Here is an example that will transition an element's opacity to 0 when you click on it and will be removed once the transition is complete:

$("#element").click( function () {
    $('#element').transition({ opacity: 0 }, function () { $(this).remove(); });
});

JS Fiddle Demo

Getting last month's date in php

The best solution I have found is this:

function subtracMonth($currentMonth, $monthsToSubtract){
        $finalMonth = $currentMonth;
        for($i=0;$i<$monthsToSubtract;$i++) {
            $finalMonth--;
            if ($finalMonth=='0'){
                $finalMonth = '12';
            }

        }
        return $finalMonth;

    }

So if we are in 3(March) and we want to subtract 5 months that would be

subtractMonth(3,5);

which would give 10(October). If the year is also desired, one could do this:

function subtracMonth($currentMonth, $monthsToSubtract){
    $finalMonth = $currentMonth;
    $totalYearsToSubtract = 0;
    for($i=0;$i<$monthsToSubtract;$i++) {
        $finalMonth--;
        if ($finalMonth=='0'){
            $finalMonth = '12';
            $totalYearsToSubtract++;
        }

    }
    //Get $currentYear
    //Calculate $finalYear = $currentYear - $totalYearsToSubtract 
    //Put resulting $finalMonth and $finalYear into an object as attributes
    //Return the object

}

How do the post increment (i++) and pre increment (++i) operators work in Java?

Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.

Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.

Is there a vr (vertical rule) in html?

I find it easy to make an image of a line, and then insert it into the code as a "rule", setting the width and/or height as needed. These have all been horizontal-rule images, but there's nothing stopping me (or you) from using a "vertical-rule" image.

This is cool for many reasons; you can use different lines, colors, or patterns easily as "rules", and since they would have no text, even if you had done it the "normal" way using hr in HTML, it shouldn't impact SEO or other stuff like that. And the image file would/should be very tiny (1 or 2KB at most).

How to unmount a busy device

Just in case someone has the same pb. :

I couldn't unmount the mount point (here /mnt) of a chroot jail.

Here are the commands I typed to investigate :

$ umount /mnt
umount: /mnt: target is busy.
$ df -h | grep /mnt
/dev/mapper/VGTout-rootFS  4.8G  976M  3.6G  22% /mnt
$ fuser -vm /mnt/
                     USER        PID ACCESS COMMAND
/mnt:                root     kernel mount /mnt
$ lsof +f -- /dev/mapper/VGTout-rootFS
$

As you can notice, even lsof returns nothing.

Then I had the idea to type this :

$ df -ah | grep /mnt
/dev/mapper/VGTout-rootFS  4.8G  976M  3.6G  22% /mnt
dev                        2.9G     0  2.9G   0% /mnt/dev
$ umount /mnt/dev
$ umount /mnt
$ df -ah | grep /mnt
$

Here it was a /mnt/dev bind to /dev that I had created to be able to repair my system inside from the chroot jail.

After umounting it, my pb. is now solved.

PHP: convert spaces in string into %20?

The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode() function.

That same page contains the answer you need - use rawurlencode() instead to get RFC 3986 compatible encoding.

curl posting with header application/x-www-form-urlencoded

<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://xxxxxxxx.xxx/xx/xx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "dispnumber=567567567&extension=6");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));


// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($server_output == "OK") { ... } else { ... }

?>

Rounding up to next power of 2

If you need it for OpenGL related stuff:

/* Compute the nearest power of 2 number that is 
 * less than or equal to the value passed in. 
 */
static GLuint 
nearestPower( GLuint value )
{
    int i = 1;

    if (value == 0) return -1;      /* Error! */
    for (;;) {
         if (value == 1) return i;
         else if (value == 3) return i*4;
         value >>= 1; i *= 2;
    }
}

Calculating distance between two geographic locations

I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.

C# example

    /// <summary>
    /// Calculates the distance between two locations using the Great Circle Distance algorithm
    /// <see cref="https://en.wikipedia.org/wiki/Great-circle_distance"/>
    /// </summary>
    /// <param name="first"></param>
    /// <param name="second"></param>
    /// <returns></returns>
    private static double DistanceBetween(GeoLocation first, GeoLocation second)
    {
        double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));

        double centralAngleBetweenLocationsInRadians = Math.Acos(
            Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
            Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *
            Math.Cos(longitudeDifferenceInRadians));

        const double earthRadiusInMeters = 6357 * 1000;

        return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;
    }

    private static double ToRadians(double degrees)
    {
        return degrees * Math.PI / 180;
    }

Searching a string in eclipse workspace

Press Ctrl + H, should bring up the search that will include options to search via project, directory, etc.

Ctrl + Alt + G can be used to find selected text across a workspace in eclipse.

How to force IE10 to render page in IE9 document mode

You should be able to do it using the X-UA meta tag:

<meta http-equiv="X-UA-Compatible" content="IE=9" />

However, if you find yourself having to do this, you're probably doing something wrong and should take a look at what you're doing and see if you can do it a different/better way.

How to auto-size an iFrame?

On any other element, I would use the scrollHeight of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try.

Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the offsetHeight:

function setHeight() {
    parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';
}

And attach that to run with the iframe-body's onLoad event.

What is the Linux equivalent to DOS pause?

Try this:

function pause(){
   read -p "$*"
}

Iterating through a range of dates in Python

This function has some extra features:

  • can pass a string matching the DATE_FORMAT for start or end and it is converted to a date object
  • can pass a date object for start or end
  • error checking in case the end is older than the start

    import datetime
    from datetime import timedelta
    
    
    DATE_FORMAT = '%Y/%m/%d'
    
    def daterange(start, end):
          def convert(date):
                try:
                      date = datetime.datetime.strptime(date, DATE_FORMAT)
                      return date.date()
                except TypeError:
                      return date
    
          def get_date(n):
                return datetime.datetime.strftime(convert(start) + timedelta(days=n), DATE_FORMAT)
    
          days = (convert(end) - convert(start)).days
          if days <= 0:
                raise ValueError('The start date must be before the end date.')
          for n in range(0, days):
                yield get_date(n)
    
    
    start = '2014/12/1'
    end = '2014/12/31'
    print list(daterange(start, end))
    
    start_ = datetime.date.today()
    end = '2015/12/1'
    print list(daterange(start, end))
    

React JS - Uncaught TypeError: this.props.data.map is not a function

what worked for me is converting the props.data to an array using data = Array.from(props.data); then I could use the data.map() function

Finding the average of an array using JS

The MacGyver way,just for lulz

_x000D_
_x000D_
var a = [80, 77, 88, 95, 68];_x000D_
_x000D_
console.log(eval(a.join('+'))/a.length)
_x000D_
_x000D_
_x000D_

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

Java count occurrence of each item in an array

Using HashMap it is walk in the park.

main(){
    String[] array ={"a","ab","a","abc","abc","a","ab","ab","a"};
    Map<String,Integer> hm = new HashMap();

    for(String x:array){

        if(!hm.containsKey(x)){
            hm.put(x,1);
        }else{
            hm.put(x, hm.get(x)+1);
        }
    }
    System.out.println(hm);
}

bower command not found

Just like in this question (npm global path prefix) all you need is to set proper npm prefix.

UNIX:

$ npm config set prefix /usr/local
$ npm install -g bower

$ which bower
>> /usr/local/bin/bower

Windows ans NVM:

$ npm config set prefix /c/Users/xxxxxxx/AppData/Roaming/nvm/v8.9.2
$ npm install -g bower

Then bower should be located just in your $PATH.

how to save canvas as png image?

I had this problem and this is the best solution without any external or additional script libraries: In Javascript tags or file create this function: We assume here that canvas is your canvas:

function download(){
        var download = document.getElementById("download");
        var image = document.getElementById("canvas").toDataURL("image/png")
                    .replace("image/png", "image/octet-stream");
        download.setAttribute("href", image);

    }

In the body part of your HTML specify the button:

<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>

This is working and download link looks like a button. Tested in Firefox and Chrome.

How to close a Tkinter window by pressing a Button?

You can associate directly the function object window.destroy to the command attribute of your button:

button = Button (frame, text="Good-bye.", command=window.destroy)

This way you will not need the function close_window to close the window for you.

MySQL: Convert INT to DATETIME

SELECT  FROM_UNIXTIME(mycolumn)
FROM    mytable

Upgrade to python 3.8 using conda

Now that the new anaconda individual edition 2020 distribution is out, the procedure that follows is working:

Update conda in your base env:

conda update conda

Create a new environment for Python 3.8, specifying anaconda for the full distribution specification, not just the minimal environment:

conda create -n py38 python=3.8 anaconda

Activate the new environment:

conda activate py38

python --version
Python 3.8.1

Number of packages installed: 303

Or you can do:

conda create -n py38 anaconda=2020.02 python=3.8

--> UPDATE: Finally, Anaconda3-2020.07 is out with core Python 3.8.3

You can download Anaconda with Python 3.8 from https://www.anaconda.com/products/individual

sql: check if entry in table A exists in table B

SELECT *
FROM   B
WHERE  NOT EXISTS (SELECT 1 
                   FROM   A 
                   WHERE  A.ID = B.ID)

Generate fixed length Strings filled with whitespaces

public static String padString(String word, int length) {
    String newWord = word;
    for(int count = word.length(); count < length; count++) {
        newWord = " " + newWord;
    }
    return newWord;
}

How to use sed to remove the last n lines of a file

Just for completeness I would like to add my solution. I ended up doing this with the standard ed:

ed -s sometextfile <<< $'-2,$d\nwq'

This deletes the last 2 lines using in-place editing (although it does use a temporary file in /tmp !!)

Send PHP variable to javascript function

Just write:

<script>
    var my_variable_name = "<?php echo $php_string; ?>";
</script>

Now it's available as a JavaScript variable by the name of my_variable_name at any point below the above code.

Changing the URL in react-router v4 without using Redirect or Link

React Router v4

There's a couple of things that I needed to get this working smoothly.

The doc page on auth workflow has quite a lot of what is required.

However I had three issues

  1. Where does the props.history come from?
  2. How do I pass it through to my component which isn't directly inside the Route component
  3. What if I want other props?

I ended up using:

  1. option 2 from an answer on 'Programmatically navigate using react router' - i.e. to use <Route render> which gets you props.history which can then be passed down to the children.
  2. Use the render={routeProps => <MyComponent {...props} {routeProps} />} to combine other props from this answer on 'react-router - pass props to handler component'

N.B. With the render method you have to pass through the props from the Route component explicitly. You also want to use render and not component for performance reasons (component forces a reload every time).

const App = (props) => (
    <Route 
        path="/home" 
        render={routeProps => <MyComponent {...props} {...routeProps}>}
    />
)

const MyComponent = (props) => (
    /**
     * @link https://reacttraining.com/react-router/web/example/auth-workflow
     * N.B. I use `props.history` instead of `history`
     */
    <button onClick={() => {
        fakeAuth.signout(() => props.history.push('/foo'))
    }}>Sign out</button>
)

One of the confusing things I found is that in quite a few of the React Router v4 docs they use MyComponent = ({ match }) i.e. Object destructuring, which meant initially I didn't realise that Route passes down three props, match, location and history

I think some of the other answers here are assuming that everything is done via JavaScript classes.

Here's an example, plus if you don't need to pass any props through you can just use component

class App extends React.Component {
    render () {
        <Route 
            path="/home" 
            component={MyComponent}
        />
    }
}

class MyComponent extends React.Component {
    render () {
        /**
         * @link https://reacttraining.com/react-router/web/example/auth-workflow
         * N.B. I use `props.history` instead of `history`
         */
        <button onClick={() => {
            this.fakeAuth.signout(() => this.props.history.push('/foo'))
        }}>Sign out</button>
    }
}

Pandas: ValueError: cannot convert float NaN to integer

if you have null value then in doing mathematical operation you will get this error to resolve it use df[~df['x'].isnull()]df[['x']].astype(int) if you want your dataset to be unchangeable.

Oracle copy data to another table

Creating a table and copying the data in a single command:

create table T_NEW as
  select * from T;

* This will not copy PKs, FKs, Triggers, etc.

How can Print Preview be called from Javascript?

It can be done using javascript. Say your html/aspx code goes this way:

<span>Main heading</span>
<asp:Label ID="lbl1" runat="server" Text="Contents"></asp:Label>
<asp:Label Text="Contractor Name" ID="lblCont" runat="server"></asp:Label>
<div id="forPrintPreview">
  <asp:Label Text="Company Name" runat="server"></asp:Label>
  <asp:GridView runat="server">

      //GridView Content goes here

  </asp:GridView
</div>

<input type="button" onclick="PrintPreview();" value="Print Preview" />

Here on click of "Print Preview" button we will open a window with data for print. Observe that 'forPrintPreview' is the id of a div. The function for Print preview goes this way:

function PrintPreview() {
 var Contractor= $('span[id*="lblCont"]').html();
 printWindow = window.open("", "", "location=1,status=1,scrollbars=1,width=650,height=600");
 printWindow.document.write('<html><head>');
 printWindow.document.write('<style type="text/css">@media print{.no-print, .no-print *{display: none !important;}</style>');
 printWindow.document.write('</head><body>');
 printWindow.document.write('<div style="width:100%;text-align:right">');

  //Print and cancel button
 printWindow.document.write('<input type="button" id="btnPrint" value="Print" class="no-print" style="width:100px" onclick="window.print()" />');
 printWindow.document.write('<input type="button" id="btnCancel" value="Cancel" class="no-print"  style="width:100px" onclick="window.close()" />');

 printWindow.document.write('</div>');

 //You can include any data this way.
 printWindow.document.write('<table><tr><td>Contractor name:'+ Contractor +'</td></tr>you can include any info here</table');

 printWindow.document.write(document.getElementById('forPrintPreview').innerHTML);
 //here 'forPrintPreview' is the id of the 'div' in current page(aspx).
 printWindow.document.write('</body></html>');
 printWindow.document.close();
 printWindow.focus();
}

Observe that buttons 'print' and 'cancel' has the css class 'no-print', So these buttons will not appear in the print.

How can you use php in a javascript function

I think you're confusing server code with client code.

JavaScript runs on the client after it has received data from the server (like a webpage).

PHP runs on the server before it sends the data.

So there are two ways with interacting with JavaScript with php.

Like above, you can generate javascript with php in the same fashion you generate HTML with php.

Or you can use an AJAX request from javascript to interact with the server. The server can respond with data and the javascript can receive that and do something with it.

I'd recommend going back to the basics and studying how HTTP works in the server-client relationship. Then study the concept of server side languages and client side languages.

Then take a tutorial with ajax, and you will start getting the concept.

Good luck, google is your friend.

What is the difference between user and kernel modes in operating systems?

What

Basically the difference between kernel and user modes is not OS dependent and is achieved only by restricting some instructions to be run only in kernel mode by means of hardware design. All other purposes like memory protection can be done only by that restriction.

How

It means that the processor lives in either the kernel mode or in the user mode. Using some mechanisms the architecture can guarantee that whenever it is switched to the kernel mode the OS code is fetched to be run.

Why

Having this hardware infrastructure these could be achieved in common OSes:

  • Protecting user programs from accessing whole the memory, to not let programs overwrite the OS for example,
  • preventing user programs from performing sensitive instructions such as those that change CPU memory pointer bounds, to not let programs break their memory bounds for example.

Perl: Use s/ (replace) and return new string

If you wanted to make your own (for semantic reasons or otherwise), see below for an example, though s/// should be all you need:

#!/usr/bin/perl -w    

use strict;     

   main();   

   sub main{    
      my $foo = "blahblahblah";          
      print '$foo: ' , replace("lah","ar",$foo) , "\n";  #$foo: barbarbar

   }        

   sub replace {
      my ($from,$to,$string) = @_;
      $string =~s/$from/$to/ig;                          #case-insensitive/global (all occurrences)

      return $string;
   }

How can I move all the files from one folder to another using the command line?

You can use the command move

move <source directory> <destination directory>

Reference

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

converting multiple columns from character to numeric format in r

like this?

DF <- data.frame("a" = as.character(0:5),
             "b" = paste(0:5, ".1", sep = ""),
             "c" = paste(10:15),
             stringsAsFactors = FALSE)

DF <- apply(DF, 2, as.numeric)

If there are "real" characters in dataframe like 'a' 'b' 'c', i would recommend answer from davsjob.

RichTextBox (WPF) does not have string property "Text"

Using two extension methods, this becomes very easy:

public static class Ext
{
    public static void SetText(this RichTextBox richTextBox, string text)
    {
        richTextBox.Document.Blocks.Clear();
        richTextBox.Document.Blocks.Add(new Paragraph(new Run(text)));
    }

    public static string GetText(this RichTextBox richTextBox)
    {
        return new TextRange(richTextBox.Document.ContentStart,
            richTextBox.Document.ContentEnd).Text;
    }
}

Multi-gradient shapes

You CAN do it using only xml shapes - just use layer-list AND negative padding like this:

    <layer-list>

        <item>
            <shape>
                <solid android:color="#ffffff" />

                <padding android:top="20dp" />
            </shape>
        </item>

        <item>
            <shape>
                <gradient android:endColor="#ffffff" android:startColor="#efefef" android:type="linear" android:angle="90" />

                <padding android:top="-20dp" />
            </shape>
        </item>

    </layer-list>

SELECT query with CASE condition and SUM()

Use an "Or"

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

or an "IN"

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

How to make JQuery-AJAX request synchronous

Instead of adding onSubmit event, you can prevent the default action for submit button.

So, in the following html:

<form name="form" action="insert.php" method="post">
    <input type='submit' />
</form>?

first, prevent submit button action. Then make the ajax call asynchronously, and submit the form when the password is correct.

$('input[type=submit]').click(function(e) {
    e.preventDefault(); //prevent form submit when button is clicked

    var password = $.trim($('#employee_password').val());

     $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(html) {
            var arr=$.parseJSON(html);
            var $form = $('form');
            if(arr == "Successful")
            {    
                $form.submit(); //submit the form if the password is correct
            }
        }
    });
});????????????????????????????????

Unit test naming best practices

the name of the the test case for class Foo should be FooTestCase or something like it (FooIntegrationTestCase or FooAcceptanceTestCase) - since it is a test case. see http://xunitpatterns.com/ for some standard naming conventions like test, test case, test fixture, test method, etc.

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

Installing Oracle Instant Client

If you want to use SQL Server Management Studio, you want to install the full Oracle client, not the Instant Client. The full Oracle client is on the same download page as the Oracle database. Assuming that you are installing on a 64-bit version of Windows, I expect you want the "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)" download. This is several hundred MB rather than a couple of MB for the Instant Client.

How to remove the default link color of the html hyperlink 'a' tag?

This will work

    a:hover, a:focus, a:active {
        outline: none;
    }

What this does is removes the outline for all the three pseudo-classes.

Writing an Excel file in EPPlus

It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

.. which will produce a beautiful excelsheet with a nice table!

Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..

Response.Clear();

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);

Response.BinaryWrite(pck.GetAsByteArray());
Response.End();

Python Sets vs Lists

Set wins due to near instant 'contains' checks: https://en.wikipedia.org/wiki/Hash_table

List implementation: usually an array, low level close to the metal good for iteration and random access by element index.

Set implementation: https://en.wikipedia.org/wiki/Hash_table, it does not iterate on a list, but finds the element by computing a hash from the key, so it depends on the nature of the key elements and the hash function. Similar to what is used for dict. I suspect list could be faster if you have very few elements (< 5), the larger element count the better the set will perform for a contains check. It is also fast for element addition and removal. Also always keep in mind that building a set has a cost !

NOTE: If the list is already sorted, searching the list could be quite fast on small lists, but with more data a set is faster for contains checks.

How to generate a random number between a and b in Ruby?

See this answer: there is in Ruby 1.9.2, but not in earlier versions. Personally I think rand(8) + 3 is fine, but if you're interested check out the Random class described in the link.

how to get last insert id after insert query in codeigniter active record

**Inside Model**
function add_info($data){
   $this->db->insert('tbl_user_info',$data);
   $last_id = $this->db->insert_id();
   return  $last_id;
}

**Inside Controller**
public function save_user_record() {
  $insertId =  $this->welcome_model->save_user_info($data);
  echo $insertId->id;
}

connecting to phpMyAdmin database with PHP/MySQL

The database is a MySQL database, not a phpMyAdmin database. phpMyAdmin is only PHP code that connects to the DB.

mysql_connect('localhost', 'username', 'password') or die (mysql_error());
mysql_select_database('db_name') or die (mysql_error());

// now you are connected

Check if a input box is empty

If your textbox is a Required field and have some regex pattern to match and has minlength and maxlength

TestBox code

<input type="text" name="myfieldname" ng-pattern="/^[ A-Za-z0-9_@./#&+-]*$/" ng-minlength="3" ng-maxlength="50" class="classname" ng-model="model.myfieldmodel">

Ng-Class to Add

ng-class="{ 'err' :  myform.myfieldname.$invalid || (myform.myfieldname.$touched && !model.myfieldmodel.length) }"

Add column to SQL Server

Adding a column using SSMS or ALTER TABLE .. ADD will not drop any existing data.

How to convert hex to ASCII characters in the Linux shell?

echo 5a | python -c "import sys; print chr(int(sys.stdin.read(),base=16))"

Removing double quotes from a string in Java

You can just go for String replace method.-

line1 = line1.replace("\"", "");

How to read the value of a private field from a different class in Java?

You need to do the following:

private static Field getField(Class<?> cls, String fieldName) {
    for (Class<?> c = cls; c != null; c = c.getSuperclass()) {
        try {
            final Field field = c.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (final NoSuchFieldException e) {
            // Try parent
        } catch (Exception e) {
            throw new IllegalArgumentException(
                    "Cannot access field " + cls.getName() + "." + fieldName, e);
        }
    }
    throw new IllegalArgumentException(
            "Cannot find field " + cls.getName() + "." + fieldName);
}

Of Countries and their Cities

From all my searching around, I strongly say that the most practical, accurate and free data source is provided by GeoNames.

You can access their data in 2 ways:

  1. The easy way through their free web services.
  2. Import their free text files into Database tables and use the data in any way you wish. This method offers much greater flexibility and have found that this method is better.

Converting List<String> to String[] in Java

String[] strarray = strlist.toArray(new String[0]);

if u want List convert to string use StringUtils.join(slist, '\n');

PSQLException: current transaction is aborted, commands ignored until end of transaction block

I just encounter the same error. I was able to figure out the root cause by enabling the log_statement and log_min_error_statement in my local PostgreSQL.

I Referred this

Determine if two rectangles overlap each other?

If the rectangles overlap then the overlap area will be greater than zero. Now let us find the overlap area:

If they overlap then the left edge of overlap-rect will be the max(r1.x1, r2.x1) and right edge will be min(r1.x2, r2.x2). So the length of the overlap will be min(r1.x2, r2.x2) - max(r1.x1, r2.x1)

So the area will be:

area = (max(r1.x1, r2.x1) - min(r1.x2, r2.x2)) * (max(r1.y1, r2.y1) - min(r1.y2, r2.y2))

If area = 0 then they don't overlap.

Simple isn't it?

Convert a matrix to a 1 dimensional array

From ?matrix: "A matrix is the special case of a two-dimensional 'array'." You can simply change the dimensions of the matrix/array.

Elts_int <- as.matrix(tmp_int)  # read.table returns a data.frame as Brandon noted
dim(Elts_int) <- (maxrow_int*maxcol_int,1)

Android Facebook style slide

I've implemented facebook-like slideout navigation in this library project.

You can easy built it into your application, your UI and navigation. You will need to implement only one Activity and one Fragment, let library know about it - and library will provide all wanted animations and navigation.

Inside the repo you can find demo-project, with how to use the lib to implement facebook-like navigation. Here is short video with record of demo project.

Also this lib should be compatible this ActionBar pattern, because is based on Activities transactions and TranslateAnimations (not Fragments transactions and custom Views).

Right now, the most problem is to make it work well for application, which support both portrait and landscape mode. If you have any feedback, please provide it via github.

All the best,
Alex

Hidden Features of Xcode

In PyObjC, you can do the equivalent of #pragma mark for the symbols dropdown:

#MARK: Foo

and

#MARK: -

Generate .pem file used to set up Apple Push Notifications

Apple have changed the name of the certificate that is issued. You can now use the same certificate for both development and production. While you can still request a development only certificate you can no longer request a production only certificate.

please see below screnshot

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

MySQL root access from all hosts

Update the bind-address = 0.0.0.0 in the /etc/mysql/mysql.conf.d/mysqld.cnf and from the mysql command line allow the root user to connect from any Ip.

Below was the only commands worked for mysql-8.0 as other were failing with error syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'abcd'' at line 1

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
UPDATE mysql.user SET host='%' WHERE user='root';

Restart the mysql client

sudo service mysql restart

How to add multiple files to Git at the same time

If you want to stage and commit all your files on Github do the following;

git add -A                                                                                
git commit -m "commit message"
git push origin master

ctypes - Beginner

The answer by Chinmay Kanchi is excellent but I wanted an example of a function which passes and returns a variables/arrays to a C++ code. I though I'd include it here in case it is useful to others.

Passing and returning an integer

The C++ code for a function which takes an integer and adds one to the returned value,

extern "C" int add_one(int i)
{
    return i+1;
}

Saved as file test.cpp, note the required extern "C" (this can be removed for C code). This is compiled using g++, with arguments similar to Chinmay Kanchi answer,

g++ -shared -o testlib.so -fPIC test.cpp

The Python code uses load_library from the numpy.ctypeslib assuming the path to the shared library in the same directory as the Python script,

import numpy.ctypeslib as ctl
import ctypes

libname = 'testlib.so'
libdir = './'
lib=ctl.load_library(libname, libdir)

py_add_one = lib.add_one
py_add_one.argtypes = [ctypes.c_int]
value = 5
results = py_add_one(value)
print(results)

This prints 6 as expected.

Passing and printing an array

You can also pass arrays as follows, for a C code to print the element of an array,

extern "C" void print_array(double* array, int N)
{
    for (int i=0; i<N; i++) 
        cout << i << " " << array[i] << endl;
}

which is compiled as before and the imported in the same way. The extra Python code to use this function would then be,

import numpy as np

py_print_array = lib.print_array
py_print_array.argtypes = [ctl.ndpointer(np.float64, 
                                         flags='aligned, c_contiguous'), 
                           ctypes.c_int]
A = np.array([1.4,2.6,3.0], dtype=np.float64)
py_print_array(A, 3)

where we specify the array, the first argument to print_array, as a pointer to a Numpy array of aligned, c_contiguous 64 bit floats and the second argument as an integer which tells the C code the number of elements in the Numpy array. This then printed by the C code as follows,

1.4
2.6
3.0

Install .ipa to iPad with or without iTunes

You can install your iOS app without iTunes, App store, or third party sites.

When you build the archive in xcode you can select for adhoc distribution. xcode will bring you through a dialogue where you enter the URL location where your app will be along with the urls for a 57x57 pixel png and a 512x512 pixel png. It will create a bundle with your ipa and manifest.plist

Upload your ipa and the two png files whereever you plan to host them. It has to have an SSL certificate and be served over https. You may want to upload your manifest.plist there as well, but technically I'm pretty sure you can have it somewhere else.

Next, somewhere, in a text, or a webpage or email, or whereever share your link as:

<a href="itms-services://?action=download-manifest&url=https://URL/path/manifest.plist">Download anchor text</a>

For a longer, better, more detailed answer click here.

As I understand, if this is a dev app, only devices that have been added to your device profile in the app store will be able to install the app.

Cannot stop or restart a docker container

in my case, i couldn't delete container created with nomad jobs, there's no output for the docker logs <ContainerID> and, in general, it looks like frozen.

until now the solution is: sudo service docker restart, may someone suggest better one?

How to display HTML tags as plain text

To display HTML tags within a browser, surround the output with < xmp> and < / xmp> tags

How can I find all *.js file in directory recursively in Linux?

If you just want the list, then you should ask here: http://unix.stackexchange.com

The answer is: cd / && find -name *.js

If you want to implement this, you have to specify the language.

Prevent linebreak after </div>

I have many times succeeded to get div's without line breaks after them, by playing around with the float css attribute and the width css attribute.
Of course after working out the solution you have to test it in all browsers, and in each browser you have to re-size the windows to make sure that it works in all circumstances.

How to change the style of a DatePicker in android?

To change DatePicker colors (calendar mode) at application level define below properties.

<style name="MyAppTheme" parent="Theme.AppCompat.Light">
    <item name="colorAccent">#ff6d00</item>
    <item name="colorControlActivated">#33691e</item>
    <item name="android:selectableItemBackgroundBorderless">@color/colorPrimaryDark</item>
    <item name="colorControlHighlight">#d50000</item>
</style>

See http://www.zoftino.com/android-datepicker-example for other DatePicker custom styles

zoftino DatePicker examples

Error:(23, 17) Failed to resolve: junit:junit:4.12

Just connect to Internet and start Android Studio and open your project. While Gradle Sync it will download the dependencies from Internet(All JAR Files). This solved it for me. No Editing in Gradle file ,all was done by Android Studio Automatically. Using Android Studio 2.2 :)

Also don't forget to install Java JDK 1.x(7 or 8 all works fine).

What's the difference between %s and %d in Python string formatting?

They are format specifiers. They are used when you want to include the value of your Python expressions into strings, with a specific format enforced.

See Dive into Python for a relatively detailed introduction.

BAT file to open CMD in current directory

A bit late to the game but if I'm understanding your needs correctly this will help people with the same issue.

Two solutions with the same first step: First navigate to the location you keep your scripts in and copy the filepath to that directory.

First Solution:

  • Click "Start"
  • Right-click "Computer" (or "My Computer)
  • Click "Properties"
  • On the left, click "Advanced System Settings"
  • Click "Environment Variables"
  • In the "System Variables" Box, scroll down and select "PATH"
  • Click "Edit"
  • In the "Variable Value" field, scroll all the way to the right
  • If there isn't a semi-colon (;) there yet, add it.
  • Paste in the filepath you copied earlier.
  • End with a semi-colon.
  • Click "OK"
  • Click "OK" again
  • Click "OK" one last time

You can now use any of your scripts as if you were already that folder.

Second Solution: (can easily be paired with the first for extra usefulness)

On your desktop create a batch file with the following content.

@echo off
cmd /k cd "C:\your\file\path"

This will open a command window like what you tried to do.


For tons of info on windows commands check here: http://ss64.com/nt/

Send email from localhost running XAMMP in PHP using GMAIL mail server

Simplest way is to use PHPMailer and Gmail SMTP. The configuration would be like the below.

require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;

$mail->isSMTP();                            
$mail->Host = 'smtp.gmail.com';            
$mail->SMTPAuth = true;                     
$mail->Username = 'Email Address';          
$mail->Password = 'Email Account Password'; 
$mail->SMTPSecure = 'tls';               
$mail->Port = 587;                  

Example script and full source code can be found from here - How to Send Email from Localhost in PHP

Remove ':hover' CSS behavior from element

Use the :not pseudo-class to exclude the classes you don't want the hover to apply to:

FIDDLE

<div class="test"> blah </div>
<div class="test"> blah </div>
<div class="test nohover"> blah </div>

.test:not(.nohover):hover {  
    border: 1px solid red; 
}

This does what you want in one css rule!

Java correct way convert/cast object to Double

If your Object represents a number, eg, such as an Integer, you can cast it to a Number then call the doubleValue() method.

Double asDouble(Object o) {
    Double val = null;
    if (o instanceof Number) {
        val = ((Number) o).doubleValue();
    }
    return val;
}

referenced before assignment error in python

I found this post through the fact that I had this error myself in my own code and I know that it has been a while since this was posted and you already got some answers and fixed issue for that situation but just wanted to explain how I fixed it just in case it could help someone else!! Basically what I thought at first was that the code editor as was using REPL.it as was making something for a friend and knew that she wouldn't want to have to download like a code editor anyways the point is I thought that it couldn't handle the code because the complexity was at 139 at that point got even higher afterwards, but then I began experimenting and realized that within my set of functions just outside of a true loop within my a_loop function for that letter to register it needed to define it! So basically I wasn't defining the Value in this case a counting feature actually within the code! I would share my code here but it's kind of personal as in the print statements and also it's 2349 lines long and yeah anyway hope this helps! Also recommend using if you can in my case for some of the code I could, putting it into way more scripts if you can to make it easier on your brain! Once again hope this helps, if you have any questions, please feel free to ask and I will answer to the best of my ability! I hope this helps!!!

-Sam

Bootstrap modal: is not a function

This warning may also be shown if jQuery is declared more than once in your code. The second jQuery declaration prevents bootstrap.js from working correctly.

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
...
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

How to merge multiple lists into one list in python?

import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)

Just another method....

gson throws MalformedJsonException

In the debugger you don't need to add back slashes, the input field understands the special chars.

In java code you need to escape the special chars

C++ Convert string (or char*) to wstring (or wchar_t*)

If you are using Windows/Visual Studio and need to convert a string to wstring you could use:

#include <AtlBase.h>
#include <atlconv.h>
...
string s = "some string";
CA2W ca2w(s.c_str());
wstring w = ca2w;
printf("%s = %ls", s.c_str(), w.c_str());

Same procedure for converting a wstring to string (sometimes you will need to specify a codepage):

#include <AtlBase.h>
#include <atlconv.h>
...
wstring w = L"some wstring";
CW2A cw2a(w.c_str());
string s = cw2a;
printf("%s = %ls", s.c_str(), w.c_str());

You could specify a codepage and even UTF8 (that's pretty nice when working with JNI/Java). A standard way of converting a std::wstring to utf8 std::string is showed in this answer.

// 
// using ATL
CA2W ca2w(str, CP_UTF8);

// 
// or the standard way taken from the answer above
#include <codecvt>
#include <string>

// convert UTF-8 string to wstring
std::wstring utf8_to_wstring (const std::string& str) {
    std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
    return myconv.from_bytes(str);
}

// convert wstring to UTF-8 string
std::string wstring_to_utf8 (const std::wstring& str) {
    std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
    return myconv.to_bytes(str);
}

If you want to know more about codepages there is an interesting article on Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets.

These CA2W (Convert Ansi to Wide=unicode) macros are part of ATL and MFC String Conversion Macros, samples included.

Sometimes you will need to disable the security warning #4995', I don't know of other workaround (to me it happen when I compiled for WindowsXp in VS2012).

#pragma warning(push)
#pragma warning(disable: 4995)
#include <AtlBase.h>
#include <atlconv.h>
#pragma warning(pop)

Edit: Well, according to this article the article by Joel appears to be: "while entertaining, it is pretty light on actual technical details". Article: What Every Programmer Absolutely, Positively Needs To Know About Encoding And Character Sets To Work With Text.

How to center icon and text in a android button with width set to "fill parent"

use this android:background="@drawable/ic_play_arrow_black_24dp"

just set the background to the icon you want to center

How can I truncate a string to the first 20 words in PHP?

Something like this could probably do the trick:

<?php 
$words = implode(' ', array_slice(split($input, ' ', 21), 0, 20));

Multiline editing in Visual Studio Code

If you're using Linux, there's a possibility of a conflict with Alt + click, which is the default for "moving a window".

You can go to menu SettingsWindow BehaviorWindow BehaviorActions tab

Just remove Alt + left (hold) and it will work.

This is the best way, because you don't need to hold two + keys to do such a simple task.

Git list of staged files

The best way to do this is by running the command:

git diff --name-only --cached

When you check the manual you will likely find the following:

--name-only
    Show only names of changed files.

And on the example part of the manual:

git diff --cached
    Changes between the index and your current HEAD.

Combined together you get the changes between the index and your current HEAD and Show only names of changed files.

Update: --staged is also available as an alias for --cached above in more recent git versions.

How to put a div in center of browser using CSS?

 <center>
        <h3 > your div goes here!</h3>    
    </center>

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

I think you should not rely on the implicit conversion. It is a bad practice.

Instead you should try like this:

datenum >= to_date('11/26/2013','mm/dd/yyyy')

or like

datenum >= date '2013-09-01'

Get the Year/Month/Day from a datetime in php?

Check out the manual: http://www.php.net/manual/en/datetime.format.php

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

Will output: 2000-01-01 00:00:00

Post values from a multiple select

You need to add a name attribute.

Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3.

In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.

Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs

For PHP you can use:

<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">

How do I add a linker or compile flag in a CMake file?

The preferred way to specify toolchain-specific options is using CMake's toolchain facility. This ensures that there is a clean division between:

  • instructions on how to organise source files into targets -- expressed in CMakeLists.txt files, entirely toolchain-agnostic; and
  • details of how certain toolchains should be configured -- separated into CMake script files, extensible by future users of your project, scalable.

Ideally, there should be no compiler/linker flags in your CMakeLists.txt files -- even within if/endif blocks. And your program should build for the native platform with the default toolchain (e.g. GCC on GNU/Linux or MSVC on Windows) without any additional flags.

Steps to add a toolchain:

  1. Create a file, e.g. arm-linux-androideadi-gcc.cmake with global toolchain settings:

    set(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)
    set(CMAKE_CXX_FLAGS_INIT "-fexceptions")
    

    (You can find an example Linux cross-compiling toolchain file here.)

  2. When you want to generate a build system with this toolchain, specify the CMAKE_TOOLCHAIN_FILE parameter on the command line:

    mkdir android-arm-build && cd android-arm-build
    cmake -DCMAKE_TOOLCHAIN_FILE=$(pwd)/../arm-linux-androideadi-gcc.cmake ..
    

    (Note: you cannot use a relative path.)

  3. Build as normal:

    cmake --build .
    

Toolchain files make cross-compilation easier, but they have other uses:

  • Hardened diagnostics for your unit tests.

    set(CMAKE_CXX_FLAGS_INIT "-Werror -Wall -Wextra -Wpedantic")
    
  • Tricky-to-configure development tools.

    # toolchain file for use with gcov
    set(CMAKE_CXX_FLAGS_INIT "--coverage -fno-exceptions -g")
    
  • Enhanced safety checks.

    # toolchain file for use with gdb
    set(CMAKE_CXX_FLAGS_DEBUG_INIT "-fsanitize=address,undefined -fsanitize-undefined-trap-on-error")
    set(CMAKE_EXE_LINKER_FLAGS_INIT "-fsanitize=address,undefined -static-libasan")
    

Java 8 forEach with index

Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

IntStream.range(0, params.size())
  .forEach(idx ->
    query.bind(
      idx,
      params.get(idx)
    )
  )
;

The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

Note that if you are closing each line with ;, the SET IDENTITY_INSERT mytable ON command will not hold for the following lines.

i.e.
a query like

SET IDENTITY_INSERT mytable ON;
INSERT INTO mytable (VoucherID, name) VALUES (1, 'Cole');

Gives the error
Cannot insert explicit value for identity column in table 'mytable' when IDENTITY_INSERT is set to OFF.

But a query like this will work:

SET IDENTITY_INSERT mytable ON
INSERT INTO mytable (VoucherID, name) VALUES (1, 'Cole')
SET IDENTITY_INSERT mytable OFF;

It seems like the SET IDENTITY_INSERT command only holds for a transaction, and the ; will signify the end of a transaction.

COPYing a file in a Dockerfile, no such file or directory?

Seems that the commands:

docker build -t imagename .

and:

docker build -t imagename - < Dockerfile2

are not executed the same way. If you want to build 2 docker images from within one folder with Dockerfile and Dockerfile2, the COPY command cannot be used in the second example using stdin (< Dockerfile2). Instead you have to use:

docker build -t imagename -f Dockerfile2 .

Then COPY does work as expected.

MYSQL query between two timestamps

Try this one. It works for me.

SELECT * FROM eventList
WHERE DATE(date) 
  BETWEEN 
    '2013-03-26' 
  AND 
    '2013-03-27'

Exit single-user mode

Just in case if someone stumbles onto this thread then here is a bullet proof solution to SQL Server stuck in SINGLE USER MODE

-- Get the process ID (spid) of the connection you need to kill
-- Replace 'DBName' with the actual name of the DB

SELECT sd.[name], sp.spid, sp.login_time, sp.loginame 
FROM sysprocesses sp 
INNER JOIN sysdatabases sd on sp.dbid = sd.dbid  
WHERE sd.[name] = 'DBName'

As an alternative, you can also use the command “sp_who” to get the “spid” of the open connection:

-- Or use this SP instead

exec sp_who

-- Then Execute the following and replace the [spid] and [DBName] with correct values

KILL SpidToKillGoesHere
GO

SET DEADLOCK_PRIORITY HIGH
GO

ALTER DATABASE [DBName] SET MULTI_USER WITH ROLLBACK IMMEDIATE
GO

BehaviorSubject vs Observable?

The Observable object represents a push based collection.

The Observer and Observable interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. The Observable object represents the object that sends notifications (the provider); the Observer object represents the class that receives them (the observer).

The Subject class inherits both Observable and Observer, in the sense that it is both an observer and an observable. You can use a subject to subscribe all the observers, and then subscribe the subject to a backend data source

var subject = new Rx.Subject();

var subscription = subject.subscribe(
    function (x) { console.log('onNext: ' + x); },
    function (e) { console.log('onError: ' + e.message); },
    function () { console.log('onCompleted'); });

subject.onNext(1);
// => onNext: 1

subject.onNext(2);
// => onNext: 2

subject.onCompleted();
// => onCompleted

subscription.dispose();

More on https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md

Check if string contains only letters in javascript

Try this

var Regex='/^[^a-zA-Z]*$/';

 if(Regex.test(word))
 {
 //...
 }

I think it will be working for you.

How can I decrypt MySQL passwords

just change them to password('yourpassword')

Simple Random Samples from a Sql database

Starting with the observation that we can retrieve the ids of a table (eg. count 5) based on a set:

select *
from table_name
where _id in (4, 1, 2, 5, 3)

we can come to the result that if we could generate the string "(4, 1, 2, 5, 3)", then we would have a more efficient way than RAND().

For example, in Java:

ArrayList<Integer> indices = new ArrayList<Integer>(rowsCount);
for (int i = 0; i < rowsCount; i++) {
    indices.add(i);
}
Collections.shuffle(indices);
String inClause = indices.toString().replace('[', '(').replace(']', ')');

If ids have gaps, then the initial arraylist indices is the result of an sql query on ids.

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

If you're looking for a minimal solution that invalidates the cache, this edited version of Dr Manhattan's solution should be sufficient. Note that I'm specifying the root / directory to indicate I want the whole site refreshed.

export AWS_ACCESS_KEY_ID=<Key>
export AWS_SECRET_ACCESS_KEY=<Secret>
export AWS_DEFAULT_REGION=eu-west-1

echo "Invalidating cloudfrond distribution to get fresh cache"
aws cloudfront create-invalidation --distribution-id=<distributionId> --paths / --profile=<awsprofile>

Region Codes can be found here

You'll also need to create a profile using the aws cli. Use the aws configure --profile option. Below is an example snippet from Amazon.

$ aws configure --profile user2
AWS Access Key ID [None]: AKIAI44QH8DHBEXAMPLE
AWS Secret Access Key [None]: je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY
Default region name [None]: us-east-1
Default output format [None]: text

Sound effects in JavaScript / HTML5

Have a look at the jai (-> mirror) (javascript audio interface) site. From looking at their source, they appear to be calling play() repeatedly, and they mention that their library might be appropriate for use in HTML5-based games.

You can fire multiple audio events simultaneously, which could be used for creating Javascript games, or having a voice speaking over some background music

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

AngularJS UI Router - change url without reloading state

I don't think you need ui-router at all for this. The documentation available for the $location service says in the first paragraph, "...changes to $location are reflected into the browser address bar." It continues on later to say, "What does it not do? It does not cause a full page reload when the browser URL is changed."

So, with that in mind, why not simply change the $location.path (as the method is both a getter and setter) with something like the following:

var newPath = IdFromService;
$location.path(newPath);

The documentation notes that the path should always begin with a forward slash, but this will add it if it's missing.

Understanding generators in Python

The only thing I can add to Stephan202's answer is a recommendation that you take a look at David Beazley's PyCon '08 presentation "Generator Tricks for Systems Programmers," which is the best single explanation of the how and why of generators that I've seen anywhere. This is the thing that took me from "Python looks kind of fun" to "This is what I've been looking for." It's at http://www.dabeaz.com/generators/.

Create two-dimensional arrays and access sub-arrays in Ruby

x.transpose[6][3..8] or x[3..8].map {|r| r [6]} would give what you want.

Example:

a = [ [1,  2,  3,  4,  5],
      [6,  7,  8,  9,  10],
      [11, 12, 13, 14, 15],
      [21, 22, 23, 24, 25]
    ]

#a[1..2][2]  -> [8,13]
puts a.transpose[2][1..2].inspect   # [8,13]
puts a[1..2].map {|r| r[2]}.inspect  # [8,13]

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

To expand on others' answers, here is a compact solution that doesn't expose/add any new variables. It doesn't cover all bases, but it should suit most people who just want a single page app to remain functional (despite no data persistence after reload).

(function(){
    try {
        localStorage.setItem('_storage_test', 'test');
        localStorage.removeItem('_storage_test');
    } catch (exc){
        var tmp_storage = {};
        var p = '__unique__';  // Prefix all keys to avoid matching built-ins
        Storage.prototype.setItem = function(k, v){
            tmp_storage[p + k] = v;
        };
        Storage.prototype.getItem = function(k){
            return tmp_storage[p + k] === undefined ? null : tmp_storage[p + k];
        };
        Storage.prototype.removeItem = function(k){
            delete tmp_storage[p + k];
        };
        Storage.prototype.clear = function(){
            tmp_storage = {};
        };
    }
})();

Convert string to nullable type (int, double, etc...)

Another thing to keep in mind is that the string itself might be null.

public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
    Nullable<T> result = new Nullable<T>();
    try
    {
        if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0)
        {
            TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
            result = (T)conv.ConvertFrom(s);
        }
    }
    catch { } 
    return result;
}

How can I open a website in my web browser using Python?

I had this problem.When I define firefox path my problem had been solved.

import webbrowser
urL='https://www.python.org'
mozilla_path="C:\\Program Files\\Mozilla Firefox\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(mozilla_path))
webbrowser.get('firefox').open_new_tab(urL)

Determine Whether Two Date Ranges Overlap

Here's my solution in Java, which works on unbounded intervals too

private Boolean overlap (Timestamp startA, Timestamp endA,
                         Timestamp startB, Timestamp endB)
{
    return (endB == null || startA == null || !startA.after(endB))
        && (endA == null || startB == null || !endA.before(startB));
}

How do I correctly upgrade angular 2 (npm) to the latest version?

npm uninstall --save-dev angular-cli

npm install --save-dev @angular/cli@latest

ng update @angular/cli

ng update @angular/core --force

ng update @angular/material or npm i @angular/cdk@6 @angular/material@6 --save

npm install typescript@'>=2.7.0 <2.8.0'

How do you install an APK file in the Android emulator?

(TESTED ON MACOS)

The first step is to run the emulator

emulator -avd < avd_name>

then use adb to install the .apk

adb install < path to .apk file>

If adb throws error like APK already exists or something alike. Run the adb shell while emulator is running

adb shell

cd data/app

adb uninstall < apk file without using .apk>

If adb and emulator are commands not found do following

export PATH=$PATH://android-sdk-macosx/platform-tools://android-sdk-macosx/android-sdk-macosx/tools:

For future use put the above line at the end of .bash_profile

vi ~/.bash_profile

MySQL 'create schema' and 'create database' - Is there any difference

So, there is no difference between MySQL "database" and MySQL "schema": these are two names for the same thing - a namespace for tables and other DB objects.

For people with Oracle background: MySQL "database" a.k.a. MySQL "schema" corresponds to Oracle schema. The difference between MySQL and Oracle CREATE SCHEMA commands is that in Oracle the CREATE SCHEMA command does not actually create a schema but rather populates it with tables and views. And Oracle's CREATE DATABASE command does a very different thing than its MySQL counterpart.

Eclipse Bug: Unhandled event loop exception No more handles

It is hardware problem at all.

If you have nView, turn off Desktop Manager. In case of ATI, turn off HydraVision.

This works fine on Eclipse Kepler (Standard) and Android Developer Tools Edition.

"The import org.springframework cannot be resolved."

org.springframework.beans.factory.support.beannamegenerator , was my error. I did a maven clean, maven build etc., which was not useful and I found that my .m2 folder is not present in my eclipse installation folder. I found the .m2 folder out side of the eclipse folder which I pasted in the eclipse folder and then in eclipse I happened to do this :-

Open configure build path maven Java EE integration Select Maven archiver generates files under the build directory apply and close

My project is up and running now.

How to completely uninstall kubernetes

If you are clearing the cluster so that you can start again, then, in addition to what @rib47 said, I also do the following to ensure my systems are in a state ready for kubeadm init again:

kubeadm reset -f
rm -rf /etc/cni /etc/kubernetes /var/lib/dockershim /var/lib/etcd /var/lib/kubelet /var/run/kubernetes ~/.kube/*
iptables -F && iptables -X
iptables -t nat -F && iptables -t nat -X
iptables -t raw -F && iptables -t raw -X
iptables -t mangle -F && iptables -t mangle -X
systemctl restart docker

You then need to re-install docker.io, kubeadm, kubectl, and kubelet to make sure they are at the latest versions for your distribution before you re-initialize the cluster.

EDIT: Discovered that calico adds firewall rules to the raw table so that needs clearing out as well.

Difference between .dll and .exe?

For those looking a concise answer,

  • If an assembly is compiled as a class library and provides types for other assemblies to use, then it has the ifle extension .dll (dynamic link library), and it cannot be executed standalone.

  • Likewise, if an assembly is compiled as an application, then it has the file extension .exe (executable) and can be executed standalone. Before .NET Core 3.0, console apps were compiled to .dll fles and had to be executed by the dotnet run command or a host executable. - Source

How to get an Android WakeLock to work?

Keep the Screen On

First way:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Second way:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>

Keep the CPU On:

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

and

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();

To release the wake lock, call wakelock.release(). This releases your claim to the CPU. It's important to release a wake lock as soon as your app is finished using it to avoid draining the battery.

Docs here.

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
    

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
    

Yes!

Hope that helps. Good luck!

How to perform grep operation on all files in a directory?

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

how to hide keyboard after typing in EditText in android?

You can see marked answer on top. But i used getDialog().getCurrentFocus() and working well. I post this answer cause i cant type "this" in my oncreatedialog.

So this is my answer. If you tried marked answer and not worked , you can simply try this:

InputMethodManager inputManager = (InputMethodManager) getActivity().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getDialog().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

How to establish a connection pool in JDBC?

As answered by others, you will probably be happy with Apache Dbcp or c3p0. Both are popular, and work fine.

Regarding your doubt

Doesn't javax.sql or java.sql have pooled connection implementations? Why wouldn't it be best to use these?

They don't provide implementations, rather interfaces and some support classes, only revelant to the programmers that implement third party libraries (pools or drivers). Normally you don't even look at that. Your code should deal with the connections from your pool just as they were "plain" connections, in a transparent way.

Cannot read property 'push' of undefined when combining arrays

This error occurs in angular when you didn't intialise the array blank.
For an example:

userlist: any[ ];
this.userlist = [ ]; 

or

userlist: any = [ ];

ListView with OnItemClickListener

1) Check if you are using OnItemClickListener or OnClickListener (which is not supported for ListView)
Documentation Android Developers ListView

2) Check if you added Listener to your ListView properly. It's hooked on ListView not on ListAdapter!

ListView.setOnItemClickListener(listener);

3) If you need to use OnClickListener, check if you do use DialogInterface.OnClickListener or View.OnClickListener (they can be easily exchanged if not validated or if using both of them)

Print Currency Number Format in PHP

with the intl extension in PHP 5.3+, you can use the NumberFormatter class:

$amount = '12345.67';

$formatter = new NumberFormatter('en_GB',  NumberFormatter::CURRENCY);
echo 'UK: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;

$formatter = new NumberFormatter('de_DE',  NumberFormatter::CURRENCY);
echo 'DE: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;

which prints :

 UK: €12,345.67
 DE: 12.345,67 €

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How do I get the APK of an installed app without root access?

When you have Eclipse for Android developement installed:

  • Use your device as debugging device. On your phone: Settings > Applications > Development and enable USB debugging, see http://developer.android.com/tools/device.html
  • In Eclipse, open DDMS-window: Window > Open Perspective > Other... > DDMS, see http://developer.android.com/tools/debugging/ddms.html
  • If you can't see your device try (re)installing USB-Driver for your device
  • In middle pane select tab "File Explorer" and go to system > app
  • Now you can select one or more files and then click the "Pull a file from the device" icon at the top (right to the tabs)
  • Select target folder - tada!

How do I get the path and name of the file that is currently executing?

import os
print os.path.basename(__file__)

this will give us the filename only. i.e. if abspath of file is c:\abcd\abc.py then 2nd line will print abc.py

How to do logging in React Native?

enter image description hereUse react native debugger for logging and redux store https://github.com/jhen0409/react-native-debugg

Just download it and run as software then enable Debug mode from the simulator.

It supports other debugging feature just like element in chrome developer tools, which helps to see the styling provided to any component.

Last complete support for redux dev tools

How to avoid pressing Enter with getchar() for reading a single character only?

By default, the C library buffers the output until it sees a return. To print out the results immediately, use fflush:

while((c=getchar())!= EOF)      
{
    putchar(c);
    fflush(stdout);
}

AngularJS resource promise

/*link*/
$q.when(scope.regions).then(function(result) {
    console.log(result);
});
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
    return response;
});

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

What is the runtime performance cost of a Docker container?

Here's some more benchmarks for Docker based memcached server versus host native memcached server using Twemperf benchmark tool https://github.com/twitter/twemperf with 5000 connections and 20k connection rate

Connect time overhead for docker based memcached seems to agree with above whitepaper at roughly twice native speed.

Twemperf Docker Memcached

Connection rate: 9817.9 conn/s
Connection time [ms]: avg 341.1 min 73.7 max 396.2 stddev 52.11
Connect time [ms]: avg 55.0 min 1.1 max 103.1 stddev 28.14
Request rate: 83942.7 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 83942.7 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 28.6 min 1.2 max 65.0 stddev 0.01
Response time [ms]: p25 24.0 p50 27.0 p75 29.0
Response time [ms]: p95 58.0 p99 62.0 p999 65.0

Twemperf Centmin Mod Memcached

Connection rate: 11419.3 conn/s
Connection time [ms]: avg 200.5 min 0.6 max 263.2 stddev 73.85
Connect time [ms]: avg 26.2 min 0.0 max 53.5 stddev 14.59
Request rate: 114192.6 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 114192.6 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 17.4 min 0.0 max 28.8 stddev 0.01
Response time [ms]: p25 12.0 p50 20.0 p75 23.0
Response time [ms]: p95 28.0 p99 28.0 p999 29.0

Here's bencmarks using memtier benchmark tool

memtier_benchmark docker Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets       16821.99          ---          ---      1.12600      2271.79
Gets      168035.07    159636.00      8399.07      1.12000     23884.00
Totals    184857.06    159636.00      8399.07      1.12100     26155.79

memtier_benchmark Centmin Mod Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets       28468.13          ---          ---      0.62300      3844.59
Gets      284368.51    266547.14     17821.36      0.62200     39964.31
Totals    312836.64    266547.14     17821.36      0.62200     43808.90

CSS: center element within a <div> element

text-align:center; on the parent div Should do the trick

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

For the record only, to add to Spudley's answer, there is also the possibility to use position: absolute and margins if you know the column widths.

For me, the main issue when chossing a method is whether you need the columns to fill the whole height (equal heights), where table-cell is the easiest method (if you don't care much for older browsers).

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

Use the formatting pattern 'dd-MM-yyyy HH:mm:ss aa' to get date as 21-10-2020 20:53:42 pm

What is a Java String's default initial value?

There are three types of variables:

  • Instance variables: are always initialized
  • Static variables: are always initialized
  • Local variables: must be initialized before use

The default values for instance and static variables are the same and depends on the type:

  • Object type (String, Integer, Boolean and others): initialized with null
  • Primitive types:
    • byte, short, int, long: 0
    • float, double: 0.0
    • boolean: false
    • char: '\u0000'

An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.

Once the array is created all of its elements are assiged with the default type value. For example:

private boolean[] list; // default value is null

private Boolean[] list; // default value is null

once is initialized:

private boolean[] list = new boolean[10]; // all ten elements are assigned to false

private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)

Select Top and Last rows in a table (SQL server)

To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.

SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC

If you care for it to be in the same order as before you can use a common table expression for that:

;WITH CTE AS (
    SELECT TOP 1000 *
    FROM [SomeTable]
    ORDER BY MySortColumn DESC
)

SELECT * 
FROM CTE
ORDER BY MySortColumn

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

1) I am using WAMP.

2) I have installed Open Office (from apache http://www.openoffice.org/download/).

3) $output_dir = "C:/wamp/www/projectfolder/"; this is my project folder where i want to create output file.

4) I have already placed my input file here C:/wamp/www/projectfolder/wordfile.docx";

Then I Run My Code.. (given below)

<?php
    set_time_limit(0);
    function MakePropertyValue($name,$value,$osm){
    $oStruct = $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");
    $oStruct->Name = $name;
    $oStruct->Value = $value;
    return $oStruct;
    }
    function word2pdf($doc_url, $output_url){

    //Invoke the OpenOffice.org service manager
    $osm = new COM("com.sun.star.ServiceManager") or die ("Please be sure that OpenOffice.org is installed.\n");
    //Set the application to remain hidden to avoid flashing the document onscreen
    $args = array(MakePropertyValue("Hidden",true,$osm));
    //Launch the desktop
    $oDesktop = $osm->createInstance("com.sun.star.frame.Desktop");
    //Load the .doc file, and pass in the "Hidden" property from above
    $oWriterDoc = $oDesktop->loadComponentFromURL($doc_url,"_blank", 0, $args);
    //Set up the arguments for the PDF output
    $export_args = array(MakePropertyValue("FilterName","writer_pdf_Export",$osm));
    //print_r($export_args);
    //Write out the PDF
    $oWriterDoc->storeToURL($output_url,$export_args);
    $oWriterDoc->close(true);
    }

    $output_dir = "C:/wamp/www/projectfolder/";
    $doc_file = "C:/wamp/www/projectfolder/wordfile.docx";
    $pdf_file = "outputfile_name.pdf";

    $output_file = $output_dir . $pdf_file;
    $doc_file = "file:///" . $doc_file;
    $output_file = "file:///" . $output_file;
    word2pdf($doc_file,$output_file);
    ?>

How to print HTML content on click of a button, but not the page?

_x000D_
_x000D_
@media print {
  .noPrint{
    display:none;
  }
}
h1{
  color:#f6f6;
}
_x000D_
<h1>
print me
</h1>
<h1 class="noPrint">
no print
</h1>
<button onclick="window.print();" class="noPrint">
Print Me
</button>
_x000D_
_x000D_
_x000D_

I came across another elegant solution for this:

Place your printable part inside a div with an id like this:

<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

Now let's create a really simple javascript:

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}

SOURCE : SO Answer

Waiting till the async task finish its work

In your AsyncTask add one ProgressDialog like:

private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);

you can setMessage in onPreExecute() method like:

this.dialog.setMessage("Processing..."); 
this.dialog.show();

and in your onPostExecute(Void result) method dismiss your ProgressDialog.

MS-access reports - The search key was not found in any record - on save

I know this is a very old post but as I was searching for additional solutions to this same error while running my command (I'd previously encountered the spaces in the Excel wb headers and remedied it with VBA each time the file is updated so I knew it wasn't that). I considered the fact that the xlsm file and DB were on separate network drives but didn't want to explore moving one unless it was my last resort.

I attempted to run the save import manually and there it was right in front of my face. The folder containing the xlsm file had been renamed....I changed the name back to match my saved import and....smh, it was that all along.

Pass parameter from a batch file to a PowerShell script

The answer from @Emiliano is excellent. You can also pass named parameters like so:

powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"

Note the parameters are outside the command call, and you'll use:

[parameter(Mandatory=$false)]
  [string]$NamedParam1,
[parameter(Mandatory=$false)]
  [string]$NamedParam2

IntelliJ Organize Imports

July 2015 - I have concluded that IntelliJ does not support automatically resolving imports with a single function. "Organize imports" simply removes unused imports, it does not resolve unimported types. Control-Space resolves a single unimported type. There does not exist a single action to resolve all types' imports.

Whitespace Matching Regex - Java

For Java (not php, not javascript, not anyother):

txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

Simple JavaScript Checkbox Validation

You can do something like this:

<form action="../" onsubmit="return checkCheckBoxes(this);">
    <p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
    <p><input type="SUBMIT" value="Submit!"></p>
</form>

<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
    if (
    theForm.MyCheckbox.checked == false) 
    {
        alert ('You didn\'t choose any of the checkboxes!');
        return false;
    } else {    
        return true;
    }
}
//-->
</script> 

http://lab.artlung.com/validate-checkbox/

Although less legible imho, this can be done without a separate function definition like this:

<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
    <p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
    <p><input type="SUBMIT" value="Submit!"></p>
</form>

Instantly detect client disconnection from server socket

Expanding on comments by mbargiel and mycelo on the accepted answer, the following can be used with a non-blocking socket on the server end to inform whether the client has shut down.

This approach does not suffer the race condition that affects the Poll method in the accepted answer.

// Determines whether the remote end has called Shutdown
public bool HasRemoteEndShutDown
{
    get
    {
        try
        {
            int bytesRead = socket.Receive(new byte[1], SocketFlags.Peek);

            if (bytesRead == 0)
                return true;
        }
        catch
        {
            // For a non-blocking socket, a SocketException with 
            // code 10035 (WSAEWOULDBLOCK) indicates no data available.
        }

        return false;
    }
}

The approach is based on the fact that the Socket.Receive method returns zero immediately after the remote end shuts down its socket and we've read all of the data from it. From Socket.Receive documentation:

If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.

If you are in non-blocking mode, and there is no data available in the protocol stack buffer, the Receive method will complete immediately and throw a SocketException.

The second point explains the need for the try-catch.

Use of the SocketFlags.Peek flag leaves any received data untouched for a separate receive mechanism to read.

The above will work with a blocking socket as well, but be aware that the code will block on the Receive call (until data is received or the receive timeout elapses, again resulting in a SocketException).

Google Maps API 3 - Custom marker color for default (dot) marker

You can use this code it works fine.

 var pinImage = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/009900/");<br>

 var marker = new google.maps.Marker({
            position: yourlatlong,
            icon: pinImage,
            map: map
        });

How to transform array to comma separated words string?

Directly from the docs:

$comma_separated = implode(",", $array);

How do I initialize a dictionary of empty lists in Python?

You are populating your dictionaries with references to a single list so when you update it, the update is reflected across all the references. Try a dictionary comprehension instead. See Create a dictionary with list comprehension in Python

d = {k : v for k in blah blah blah}

ValueError: object too deep for desired array while using convolution

np.convolve needs a flattened array as one of it's inputs, you can use numpy.ndarray.flatten() which is quite fast, find it here.

Recommended website resolution (width and height)?

I would say that you should only expect users to have a monitor with 800x600 resolution. The Canadian government has standards that list this as one of the requirements. Although that may seem low to somebody with a fancy widescreen monitor, remember that not everybody has a nice monitor. I still know a lot of people running at 1024x768. And it's not at all uncommon to run into someone who's running in 800x600, especially in cheap web cafes while travelling. Also, it's nice to have to make your browser window full screen if you don't want to. You can make the site wider on wider monitors, but don't make the user scroll horizontally. Ever. Another advantage of supporting lower resolutions is that your site will work on mobile phones and Nintendo Wii's a lot easier.

A note on your at least 1280 wide, I would have to say that's way overboard. Most 17 and even my 19 inch non widescreen monitors only support a maximum resolution of 1280x1024. And the 14 inch widescreen laptop I'm typing on right now is only 1280 pixels across. I would say that the largest minimum resolution you should strive for is 1024x768, but 800x600 would be ideal.

how to get the selected index of a drop down

You can also use :checked for <select> elements

e.g.,

document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')

You don't even have to get the index and then reference the element by its sibling index.

UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

frame.origin = center - bounds.size / 2

(which is the same as)

center = frame.origin + bounds.size / 2

(and there’s also)

frame.size = bounds.size

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

Create a basic matrix in C (input by user !)

This is my answer

#include<stdio.h>
int main()
{int mat[100][100];
int row,column,i,j;
printf("enter how many row and colmn you want:\n \n");
scanf("%d",&row);
scanf("%d",&column);
printf("enter the matrix:");

for(i=0;i<row;i++){
    for(j=0;j<column;j++){
        scanf("%d",&mat[i][j]);
    }

printf("\n");
}

for(i=0;i<row;i++){
    for(j=0;j<column;j++){
        printf("%d \t",mat[i][j]);}

printf("\n");}
}

I just choose an approximate value for the row and column. My selected row or column will not cross the value.and then I scan the matrix element then make it in matrix size.

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
(?=.*\d)           // use positive look ahead to see if at least one digit exists
(?=.*\W])        // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

Create multiple threads and wait all of them to complete

If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.

Example:

List<Thread> threads = new List<Thread>();


// Start threads
for(int i = 0; i<10; i++)
{
    int tmp = i; // Copy value for closure
    Thread t = new Thread(() => Console.WriteLine(tmp));
    t.Start;
    threads.Add(t);
}

// Await threads
foreach(Thread thread in threads)
{
    thread.Join();
}

Hidden features of Windows batch files

here's one trick that I use to run My Nant Build script consecutively without having to click the batch file over and over again.

:CODELINE
NANT.EXE -buildfile:alltargets.build -l:build.log build.product
@pause
GOTO :CODELINE

What will happen is that after your solution finished building, it will be paused. And then if you press any key it will rerun the build script again. Very handy I must say.

Replace Line Breaks in a String C#

Best way to replace linebreaks safely is

yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n")             //handling mac linebreaks

that should produce a string with only \n (eg linefeed) as linebreaks. this code is usefull to fix mixed linebreaks too.

How to redirect to another page using PHP

header won't work for all

Use below simple code

<?php
        echo "<script> location.href='new_url'; </script>";
        exit;
?>

Adding space/padding to a UILabel

In Swift 3

best and simple way

class UILabelPadded: UILabel {
     override func drawText(in rect: CGRect) {
     let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
     super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }

}

scale fit mobile web content using viewport meta tag

I think this should help you.

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

Tell me if it works.

P/s: here is some media query for standard devices. http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

How to generate xsd from wsdl

Follow these steps :

  1. Create a project using the WSDL.
  2. Choose your interface and open in interface viewer.
  3. Navigate to the tab 'WSDL Content'.
  4. Use the last icon under the tab 'WSDL Content' : 'Export the entire WSDL and included/imported files to a local directory'.
  5. select the folder where you want the XSDs to be exported to.

Note: SOAPUI will remove all relative paths and will save all XSDs to the same folder. Refer the screenshot : enter image description here

Get the element triggering an onclick event in jquery?

It's top google stackoverflow question, but all answers are not jQuery related!

$(".someclass").click(
    function(event)
    {
        console.log(event, this);
    }
);

'event' contains 2 important values:

event.currentTarget - element to which event is triggered ('.someclass' element)

event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)

this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)

When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.

Converting a Uniform Distribution to a Normal Distribution

This is my JavaScript implementation of Algorithm P (Polar method for normal deviates) from Section 3.4.1 of Donald Knuth's book The Art of Computer Programming:

function normal_random(mean,stddev)
{
    var V1
    var V2
    var S
    do{
        var U1 = Math.random() // return uniform distributed in [0,1[
        var U2 = Math.random()
        V1 = 2*U1-1
        V2 = 2*U2-1
        S = V1*V1+V2*V2
    }while(S >= 1)
    if(S===0) return 0
    return mean+stddev*(V1*Math.sqrt(-2*Math.log(S)/S))
}

Android: Force EditText to remove focus?

You can avoid any focus on your elements by setting the attribute android:descendantFocusability of the parent element.

Here is an example:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/search__scroller"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ScrollView>

Here, the attribute android:descendantFocusability set to "blocksDescendants" is blocking the focus on the child elements.

You can find more info here.

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

Oops! Looks like they don't have Windows wheels on PyPI.

In the meantime, installing from source probably works or try downloading MSVC++ 14 as suggested in the error message and by others on this page.

Christoph's site also has unofficial Windows Binaries for Python Extension Packages (.whl files).

Follow steps mentioned in following links to install binaries :

  1. Directly in base python
  2. In virtual environments / Pycharm

Also check :

Which binary to download??

javax vs java package

java.* packages are the core Java language packages, meaning that programmers using the Java language had to use them in order to make any worthwhile use of the java language.

javax.* packages are optional packages, which provides a standard, scalable way to make custom APIs available to all applications running on the Java platform.

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

Run command - npm init No file directory found issue got resolved

allowing only alphabets in text box using java script

You can use HTML5 pattern attribute to do this:

<form>
    <input type='text' pattern='[A-Za-z\\s]*'/>
</form>

If the user enters an input that conflicts with the pattern, it will show an error dialogue automatically.

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

Which Radio button in the group is checked?

The OP wanted to get the checked RadioButton BY GROUP. While @SLaks' answer is excellent, it doesn't really answer the OP's main question. To improve on @SLaks' answer, just take the LINQ one step further.

Here's an example from my own working code. Per normal WPF, my RadioButtons are contained in a Grid (named "myGrid") with a bunch of other types of controls. I have two different RadioButton groups in the Grid.

To get the checked RadioButton from a particular group:

List<RadioButton> radioButtons = myGrid.Children.OfType<RadioButton>().ToList();
RadioButton rbTarget = radioButtons
      .Where(r => r.GroupName == "GroupName" && r.IsChecked)
      .Single();

If your code has the possibility of no RadioButtons being checked, then use SingleOrDefault() (If I'm not using tri-state buttons, then I always set one button "IsChecked" as a default selection.)

How to remove the last element added into the List?

I would rather use Last() from LINQ to do it.

rows = rows.Remove(rows.Last());

or

rows = rows.Remove(rows.LastOrDefault());

Bootstrap number validation

It's not Twitter bootstrap specific, it is a normal HTML5 component and you can specify the range with the min and max attributes (in your case only the first attribute). For example:

_x000D_
_x000D_
<div>                       _x000D_
    <input type="number" id="replyNumber" min="0" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'm not sure if only integers are allowed by default in the control or not, but else you can specify the step attribute:

_x000D_
_x000D_
<div>                       _x000D_
    <input type="number" id="replyNumber" min="0" step="1" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Now only numbers higher (and equal to) zero can be used and there is a step of 1, which means the values are 0, 1, 2, 3, 4, ... .

BE AWARE: Not all browsers support the HTML5 features, so it's recommended to have some kind of JavaScript fallback (and in your back-end too) if you really want to use the constraints.

For a list of browsers that support it, you can look at caniuse.com.

How to build minified and uncompressed bundle with webpack?

You can use a single config file, and include the UglifyJS plugin conditionally using an environment variable:

const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');

const PROD = JSON.parse(process.env.PROD_ENV || '0');

module.exports = {

  entry: './entry.js',
  devtool: 'source-map',
  output: {
    path: './dist',
    filename: PROD ? 'bundle.min.js' : 'bundle.js'
  },
  optimization: {
    minimize: PROD,
    minimizer: [
      new TerserPlugin({ parallel: true })
  ]
};

and then just set this variable when you want to minify it:

$ PROD_ENV=1 webpack

Edit:

As mentioned in the comments, NODE_ENV is generally used (by convention) to state whether a particular environment is a production or a development environment. To check it, you can also set const PROD = (process.env.NODE_ENV === 'production'), and continue normally.

How can I convert ArrayList<Object> to ArrayList<String>?

Here is another alternative using Guava

List<Object> lst ...    
List<String> ls = Lists.transform(lst, Functions.toStringFunction());

How can I hide select options with JavaScript? (Cross browser)

Hiding an <option> element is not in the spec. But you can disable them, which should work cross-browser.

$('option.hide').prop('disabled', true);

http://www.w3.org/TR/html401/interact/forms.html#h-17.6

Visual Studio Code - Convert spaces to tabs

In my case, the problem was JS-CSS-HTML Formatter extension installed after january update. The default indent_char property is space. I uninstalled it and the weird behavior stops.

No module named 'pymysql'

To get around the problem, find out where pymysql is installed.

If for example it is installed in /usr/lib/python3.7/site-packages, add the following code above the import pymysql command:

import sys
sys.path.insert(0,"/usr/lib/python3.7/site-packages")
import pymysql

This ensures that your Python program can find where pymysql is installed.

Executing a batch file in a remote machine through PsExec

Here's my current solution to run any code remotely on a given machine or list of machines asynchronously with logging, too!

@echo off
:: by Ralph Buchfelder, thanks to Mark Russinovich and Rob van der Woude for their work!
:: requires PsExec.exe to be in the same directory (download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx)
:: troubleshoot remote commands with PsExec arguments -i or -s if neccessary (see http://forum.sysinternals.com/pstools_forum8.html)
:: will run *in parallel* on a list of remote pcs (if given); to run serially please remove 'START "" CMD.EXE /C' from the psexec call


:: help
if '%1' =='-h' (
 echo.
 echo %~n0
 echo.
 echo Runs a command on one or many remote machines. If no input parameters
 echo are given you will be asked for a target remote machine.
 echo.
 echo You will be prompted for remote credentials with elevated privileges.
 echo.
 echo UNC paths and local paths can be supplied.
 echo Commands will be executed on the remote side just the way you typed
 echo them, so be sure to mind extensions and the path variable!
 echo.
 echo Please note that PsExec.exe must be allowed on remote machines, i.e.
 echo not blocked by firewall or antivirus solutions.
 echo.
 echo Syntax: %~n0 [^<inputfile^>]
 echo.
 echo     inputfile      = a plain text file ^(one hostname or ip address per line^)
 echo.
 echo.
 echo Example:
 echo %~n0 mylist.txt
 exit /b 0
)


:checkAdmin
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' neq '0' (
 echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
 echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
 "%temp%\getadmin.vbs"
 del "%temp%\getadmin.vbs"
 exit /B
)
set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
mkdir "%ADMINTESTDIR%" 2>NUL
if errorlevel 1 (
 cls
 echo ERROR: This script requires elevated privileges!
 echo.
 echo Launch by Right-Click / Run as Administrator ...
 pause
 exit /b 1
) else (
 rd /s /q "%ADMINTESTDIR%"
 echo Running with elevated privileges...
)
echo.


:checkRequirements
if not exist "%~dp0PsExec.exe" (
 echo PsExec.exe from Sysinternals/Microsoft not found 
 echo in %~dp0
 echo.
 echo Download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx
 echo.
 pause
 exit /B
)


:environment
setlocal
echo.
echo %~n0
echo _____________________________
echo.
echo Working directory:  %cd%\
echo Script directory:   %~dp0
echo.
SET /P REMOTE_USER=Domain\Administrator : 
SET "psCommand=powershell -Command "$pword = read-host 'Kennwort' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set REMOTE_PASS=%%p
if NOT DEFINED REMOTE_PASS SET /P REMOTE_PASS=Password             : 
echo.
if '%1' =='' goto menu
SET REMOTE_LIST=%1


:inputMultipleTargets
if not exist %REMOTE_LIST% (
 echo File %REMOTE_LIST% not found
 goto menu
)
type %REMOTE_LIST% >nul
if '%errorlevel%' neq '0' (
 echo Access denied %REMOTE_LIST%
 goto menu
)
set batchProcessing=true
echo Batch processing:   %REMOTE_LIST%   ...
ping -n 2 127.0.0.1 >nul
goto runOnce


:menu
if exist "%~dp0last.computer"  set /p LAST_COMPUTER=<"%~dp0last.computer"
if exist "%~dp0last.listing"   set /p LAST_LISTING=<"%~dp0last.listing"
if exist "%~dp0last.directory" set /p LAST_DIRECTORY=<"%~dp0last.directory"
if exist "%~dp0last.command"   set /p LAST_COMMAND=<"%~dp0last.command"
if exist "%~dp0last.timestamp" set /p LAST_TIMESTAMP=<"%~dp0last.timestamp"
echo.
echo.
echo                (1)  select target computer [default]
echo                (2)  select multiple computers
echo                     -----------------------------------
echo                     last target : %LAST_COMPUTER%
echo                     last listing: %LAST_LISTING%
echo                     last path   : %LAST_DIRECTORY%
echo                     last command: %LAST_COMMAND%
echo                     last run    : %LAST_TIMESTAMP%
echo                     -----------------------------------
echo                (0)  exit
echo.
echo ENTER your choice.
echo.
echo.
:mychoice
SET /P mychoice=(0, 1, ...): 
if NOT DEFINED mychoice  goto promptSingleTarget
if "%mychoice%"=="1"     goto promptSingleTarget
if "%mychoice%"=="2"     goto promptMultipleTargets
if "%mychoice%"=="0"     goto end
goto mychoice


:promptMultipleTargets
echo.
echo Please provide an input file
echo [one IP address or hostname per line]
SET /P REMOTE_LIST=Filename             : 
goto inputMultipleTargets


:promptSingleTarget
SET batchProcessing=
echo.
echo Please provide a hostname
SET /P REMOTE_COMPUTER=Target computer      : 
goto runOnce


:runOnce
cls
echo Note: Paths are mandatory for CMD-commands (e.g. dir,copy) to work!
echo       Paths are provided on the remote machine via PUSHD.
echo.
SET /P REMOTE_PATH=UNC-Path or folder : 
SET /P REMOTE_CMD=Command with params: 
SET REMOTE_TIMESTAMP=%DATE% %TIME:~0,8%
echo.
echo Remote command starting (%REMOTE_PATH%\%REMOTE_CMD%) on %REMOTE_TIMESTAMP%...
if not defined batchProcessing goto runOnceSingle


:runOnceMulti
REM do for each line; this circumvents PsExec's @file to have stdouts separately
SET REMOTE_LOG=%~dp0\log\%REMOTE_LIST%
if not exist %REMOTE_LOG% md %REMOTE_LOG%
for /F "tokens=*" %%A in (%REMOTE_LIST%) do (
 if "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "%REMOTE_CMD%" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
 if not "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
)
goto restart


:runOnceSingle
SET REMOTE_LOG=%~dp0\log
if not exist %REMOTE_LOG% md %REMOTE_LOG%
if "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "%REMOTE_CMD%" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
if not "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
goto restart


:restart
echo.
echo.
echo Batch completed. Finished with last errorlevel %errorlevel% .
echo All outputs have been saved to %~dp0log\%REMOTE_TIMESTAMP%\.
echo %REMOTE_PATH% >"%~dp0last.directory"
echo %REMOTE_CMD% >"%~dp0last.command"
echo %REMOTE_LIST% >"%~dp0last.listing"
echo %REMOTE_COMPUTER% >"%~dp0last.computer"
echo %REMOTE_TIMESTAMP% >"%~dp0last.timestamp"
SET REMOTE_PATH=
SET REMOTE_CMD=
SET REMOTE_LIST=
SET REMOTE_COMPUTER=
SET REMOTE_LOG=
SET REMOTE_TIMESTAMP=
ping -n 2 127.0.0.1 >nul
goto menu


:end
SET REMOTE_USER=
SET REMOTE_PASS=

Remove scrollbars from textarea

Try the following, not sure which will work for all browsers or the browser you are working with, but it would be best to try all:

<textarea style="overflow:auto"></textarea>

Or

<textarea style="overflow:hidden"></textarea>

...As suggested above

You can also try adding this, I never used it before, just saw it posted on a site today:

<textarea style="resize:none"></textarea>

This last option would remove the ability to resize the textarea. You can find more information on the CSS resize property here

BeanFactory not initialized or already closed - call 'refresh' before

I had this issue until I removed the project in question from the server's deployments (in JBoss Dev Studio, right-click the server and "Remove" the project in the Servers view), then did the following:

  1. Restarted the JBoss EAP 6.1 server without any projects deployed.
  2. Once the server had started, I then added the project in question to the server.

After this, just restart the server (in debug or run mode) by selecting the server, NOT the project itself.

This seemed to flush any previous settings/states/memory/whatever that was causing the issue, and I no longer got the error.

Convert datetime to valid JavaScript date

You can use get methods:

_x000D_
_x000D_
var fullDate = new Date();_x000D_
console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
    twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
    twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
_x000D_
_x000D_

EOFError: end of file reached issue with Net::HTTP

After doing some research, this was happening in Ruby's XMLRPC::Client library - which uses NET::HTTP. The client uses the start() method in NET::HTTP which keeps the connection open for future requests.

This happened precisely at 30 seconds after the last requests - so my assumption here is that the server it's hitting is closing requests after that time. I'm not sure what the default is for NET::HTTP to keep the request open - but I'm about to test with 60 seconds to see if that solves the issue.

Why is my Button text forced to ALL CAPS on Lollipop?

Using the android.support.v7.widget.AppCompatButton in the XML layout will allow you to avoid having to have a layout-21 or programmatically changing anything. Naturally this will also work with AppCompat v7 library.

<android.support.v7.widget.AppCompatButton
    android:id="@+id/btnOpenMainDemo"
    android:textAllCaps="false"
    style="@style/HGButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btn_main_demo"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"/>

Hope this helps.

css 100% width div not taking up full width of parent

Remove the width:100%; declarations.

Block elements should take up the whole available width by default.