Programs & Examples On #Trygetvalue

Case insensitive access for generic dictionary

Its not very elegant but in case you cant change the creation of dictionary, and all you need is a dirty hack, how about this:

var item = MyDictionary.Where(x => x.Key.ToLower() == MyIndex.ToLower()).FirstOrDefault();
    if (item != null)
    {
        TheValue = item.Value;
    }

get dictionary value by key

Dictionary<String,String> d = new Dictionary<String,String>();
        d.Add("1","Mahadev");
        d.Add("2","Mahesh");
        Console.WriteLine(d["1"]);// it will print Value of key '1'

Dictionary returning a default value if the key does not exist

I know this is an old post and I do favor extension methods, but here's a simple class I use from time to time to handle dictionaries when I need default values.

I wish this were just part of the base Dictionary class.

public class DictionaryWithDefault<TKey, TValue> : Dictionary<TKey, TValue>
{
  TValue _default;
  public TValue DefaultValue {
    get { return _default; }
    set { _default = value; }
  }
  public DictionaryWithDefault() : base() { }
  public DictionaryWithDefault(TValue defaultValue) : base() {
    _default = defaultValue;
  }
  public new TValue this[TKey key]
  {
    get { 
      TValue t;
      return base.TryGetValue(key, out t) ? t : _default;
    }
    set { base[key] = value; }
  }
}

Beware, however. By subclassing and using new (since override is not available on the native Dictionary type), if a DictionaryWithDefault object is upcast to a plain Dictionary, calling the indexer will use the base Dictionary implementation (throwing an exception if missing) rather than the subclass's implementation.

Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

how to change onclick event with jquery?

$('#id').attr('onclick', 'function()');

Right now (11 Jul 2015) this solution is still working (jquery 2.1.4); in my opinion, it is the best one to pick up.

Convert hex string to int in Python

In Python 2.7, int('deadbeef',10) doesn't seem to work.

The following works for me:

>>a = int('deadbeef',16)
>>float(a)
3735928559.0

How to generate an MD5 file hash in JavaScript?

You could use crypto-js.

I would also recommend using SHA256, rather than MD5.

To install crypto-js via NPM:

npm install crypto-js

Alternatively you can use a CDN and reference the JS file.

Then to display a MD5 and SHA256 hash, you can do the following:

<script type="text/javascript">
    var md5Hash = CryptoJS.MD5("Test");
    var sha256Hash = CryptoJS.SHA256("Test1");

    console.log(md5Hash.toString());
    console.log(sha256Hash.toString());
</script>

Working example located here, JSFiddle

There are also other JS functions that will generate an MD5 hash, outlined below.

http://www.myersdaily.org/joseph/javascript/md5-text.html

http://pajhome.org.uk/crypt/md5/md5.html

function md5cycle(x, k) {
var a = x[0], b = x[1], c = x[2], d = x[3];

a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17,  606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12,  1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7,  1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7,  1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22,  1236535329);

a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14,  643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9,  38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5,  568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20,  1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14,  1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);

a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16,  1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11,  1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4,  681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23,  76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16,  530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);

a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10,  1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6,  1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6,  1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21,  1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15,  718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);

x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);

}

function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}

function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}

function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}

function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}

function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}

function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878], i;
for (i=64; i<=s.length; i+=64) {
md5cycle(state, md5blk(s.substring(i-64, i)));
}
s = s.substring(i-64);
var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
for (i=0; i<s.length; i++)
tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3);
tail[i>>2] |= 0x80 << ((i%4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i=0; i<16; i++) tail[i] = 0;
}
tail[14] = n*8;
md5cycle(state, tail);
return state;
}

/* there needs to be support for Unicode here,
 * unless we pretend that we can redefine the MD-5
 * algorithm for multi-byte characters (perhaps
 * by adding every four 16-bit characters and
 * shortening the sum to 32 bits). Otherwise
 * I suggest performing MD-5 as if every character
 * was two bytes--e.g., 0040 0025 = @%--but then
 * how will an ordinary MD-5 sum be matched?
 * There is no way to standardize text to something
 * like UTF-8 before transformation; speed cost is
 * utterly prohibitive. The JavaScript standard
 * itself needs to look at this: it should start
 * providing access to strings as preformed UTF-8
 * 8-bit unsigned value arrays.
 */
function md5blk(s) { /* I figured global was faster.   */
var md5blks = [], i; /* Andy King said do it this way. */
for (i=0; i<64; i+=4) {
md5blks[i>>2] = s.charCodeAt(i)
+ (s.charCodeAt(i+1) << 8)
+ (s.charCodeAt(i+2) << 16)
+ (s.charCodeAt(i+3) << 24);
}
return md5blks;
}

var hex_chr = '0123456789abcdef'.split('');

function rhex(n)
{
var s='', j=0;
for(; j<4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F]
+ hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}

function hex(x) {
for (var i=0; i<x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}

function md5(s) {
return hex(md51(s));
}

/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause.  */

function add32(a, b) {
return (a + b) & 0xFFFFFFFF;
}

if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') {
function add32(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
}

Then simply use the MD5 function, as shown below:

alert(md5("Test string"));

Another working JS Fiddle here

Installation error: INSTALL_FAILED_OLDER_SDK

If you are totally new like me, you must install the minimum SDK at first. Check the link.

This worked out perfectly for me:

Same problem other post with a good solution

Regards,

Khaled.

How to rename with prefix/suffix?

You could use the rename(1) command:

rename 's/(.*)$/new.$1/' original.filename

Edit: If rename isn't available and you have to rename more than one file, shell scripting can really be short and simple for this. For example, to rename all *.jpg to prefix_*.jpg in the current directory:

for filename in *.jpg; do mv "$filename" "prefix_$filename"; done;

How can I check if a jQuery plugin is loaded?

I would strongly recommend that you bundle the DateJS library with your plugin and document the fact that you've done it. Nothing is more frustrating than having to hunt down dependencies.

That said, for legal reasons, you may not always be able to bundle everything. It also never hurts to be cautious and check for the existence of the plugin using Eran Galperin's answer.

CSS ''background-color" attribute not working on checkbox inside <div>

When you input the body tag, press space just one time without closing the tag and input bgcolor="red", just for instance. Then choose a diff color for your font.

How do I remove trailing whitespace using a regular expression?

Regex to find trailing and leading whitespaces:

^[ \t]+|[ \t]+$

raw_input function in Python

raw_input() was renamed to input() in Python 3.

From http://docs.python.org/dev/py3k/whatsnew/3.0.html

How to Implement DOM Data Binding in JavaScript

Yesterday, I started to write my own way to bind data.

It's very funny to play with it.

I think it's beautiful and very useful. At least on my tests using firefox and chrome, Edge must works too. Not sure about others, but if they support Proxy, I think it will work.

https://jsfiddle.net/2ozoovne/1/

<H1>Bind Context 1</H1>
<input id='a' data-bind='data.test' placeholder='Button Text' />
<input id='b' data-bind='data.test' placeholder='Button Text' />
<input type=button id='c' data-bind='data.test' />
<H1>Bind Context 2</H1>
<input id='d' data-bind='data.otherTest' placeholder='input bind' />
<input id='e' data-bind='data.otherTest' placeholder='input bind' />
<input id='f' data-bind='data.test' placeholder='button 2 text - same var name, other context' />
<input type=button id='g' data-bind='data.test' value='click here!' />
<H1>No bind data</H1>
<input id='h' placeholder='not bound' />
<input id='i' placeholder='not bound'/>
<input type=button id='j' />

Here is the code:

(function(){
    if ( ! ( 'SmartBind' in window ) ) { // never run more than once
        // This hack sets a "proxy" property for HTMLInputElement.value set property
        var nativeHTMLInputElementValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
        var newDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
        newDescriptor.set=function( value ){
            if ( 'settingDomBind' in this )
                return;
            var hasDataBind=this.hasAttribute('data-bind');
            if ( hasDataBind ) {
                this.settingDomBind=true;
                var dataBind=this.getAttribute('data-bind');
                if ( ! this.hasAttribute('data-bind-context-id') ) {
                    console.error("Impossible to recover data-bind-context-id attribute", this, dataBind );
                } else {
                    var bindContextId=this.getAttribute('data-bind-context-id');
                    if ( bindContextId in SmartBind.contexts ) {
                        var bindContext=SmartBind.contexts[bindContextId];
                        var dataTarget=SmartBind.getDataTarget(bindContext, dataBind);
                        SmartBind.setDataValue( dataTarget, value);
                    } else {
                        console.error( "Invalid data-bind-context-id attribute", this, dataBind, bindContextId );
                    }
                }
                delete this.settingDomBind;
            }
            nativeHTMLInputElementValue.set.bind(this)( value );
        }
        Object.defineProperty(HTMLInputElement.prototype, 'value', newDescriptor);

    var uid= function(){
           return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
               var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
               return v.toString(16);
          });
   }

        // SmartBind Functions
        window.SmartBind={};
        SmartBind.BindContext=function(){
            var _data={};
            var ctx = {
                "id" : uid()    /* Data Bind Context Id */
                , "_data": _data        /* Real data object */
                , "mapDom": {}          /* DOM Mapped objects */
                , "mapDataTarget": {}       /* Data Mapped objects */
            }
            SmartBind.contexts[ctx.id]=ctx;
            ctx.data=new Proxy( _data, SmartBind.getProxyHandler(ctx, "data"))  /* Proxy object to _data */
            return ctx;
        }

        SmartBind.getDataTarget=function(bindContext, bindPath){
            var bindedObject=
                { bindContext: bindContext
                , bindPath: bindPath 
                };
            var dataObj=bindContext;
            var dataObjLevels=bindPath.split('.');
            for( var i=0; i<dataObjLevels.length; i++ ) {
                if ( i == dataObjLevels.length-1 ) { // last level, set value
                    bindedObject={ target: dataObj
                    , item: dataObjLevels[i]
                    }
                } else {    // digg in
                    if ( ! ( dataObjLevels[i] in dataObj ) ) {
                        console.warn("Impossible to get data target object to map bind.", bindPath, bindContext);
                        break;
                    }
                    dataObj=dataObj[dataObjLevels[i]];
                }
            }
            return bindedObject ;
        }

        SmartBind.contexts={};
        SmartBind.add=function(bindContext, domObj){
            if ( typeof domObj == "undefined" ){
                console.error("No DOM Object argument given ", bindContext);
                return;
            }
            if ( ! domObj.hasAttribute('data-bind') ) {
                console.warn("Object has no data-bind attribute", domObj);
                return;
            }
            domObj.setAttribute("data-bind-context-id", bindContext.id);
            var bindPath=domObj.getAttribute('data-bind');
            if ( bindPath in bindContext.mapDom ) {
                bindContext.mapDom[bindPath][bindContext.mapDom[bindPath].length]=domObj;
            } else {
                bindContext.mapDom[bindPath]=[domObj];
            }
            var bindTarget=SmartBind.getDataTarget(bindContext, bindPath);
            bindContext.mapDataTarget[bindPath]=bindTarget;
            domObj.addEventListener('input', function(){ SmartBind.setDataValue(bindTarget,this.value); } );
            domObj.addEventListener('change', function(){ SmartBind.setDataValue(bindTarget, this.value); } );
        }

        SmartBind.setDataValue=function(bindTarget,value){
            if ( ! ( 'target' in bindTarget ) ) {
                var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
                if ( 'target' in lBindTarget ) {
                    bindTarget.target=lBindTarget.target;
                    bindTarget.item=lBindTarget.item;
                } else {
                    console.warn("Still can't recover the object to bind", bindTarget.bindPath );
                }
            }
            if ( ( 'target' in bindTarget ) ) {
                bindTarget.target[bindTarget.item]=value;
            }
        }
        SmartBind.getDataValue=function(bindTarget){
            if ( ! ( 'target' in bindTarget ) ) {
                var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
                if ( 'target' in lBindTarget ) {
                    bindTarget.target=lBindTarget.target;
                    bindTarget.item=lBindTarget.item;
                } else {
                    console.warn("Still can't recover the object to bind", bindTarget.bindPath );
                }
            }
            if ( ( 'target' in bindTarget ) ) {
                return bindTarget.target[bindTarget.item];
            }
        }
        SmartBind.getProxyHandler=function(bindContext, bindPath){
            return  {
                get: function(target, name){
                    if ( name == '__isProxy' )
                        return true;
                    // just get the value
                    // console.debug("proxy get", bindPath, name, target[name]);
                    return target[name];
                }
                ,
                set: function(target, name, value){
                    target[name]=value;
                    bindContext.mapDataTarget[bindPath+"."+name]=value;
                    SmartBind.processBindToDom(bindContext, bindPath+"."+name);
                    // console.debug("proxy set", bindPath, name, target[name], value );
                    // and set all related objects with this target.name
                    if ( value instanceof Object) {
                        if ( !( name in target) || ! ( target[name].__isProxy ) ){
                            target[name]=new Proxy(value, SmartBind.getProxyHandler(bindContext, bindPath+'.'+name));
                        }
                        // run all tree to set proxies when necessary
                        var objKeys=Object.keys(value);
                        // console.debug("...objkeys",objKeys);
                        for ( var i=0; i<objKeys.length; i++ ) {
                            bindContext.mapDataTarget[bindPath+"."+name+"."+objKeys[i]]=target[name][objKeys[i]];
                            if ( typeof value[objKeys[i]] == 'undefined' || value[objKeys[i]] == null || ! ( value[objKeys[i]] instanceof Object ) || value[objKeys[i]].__isProxy )
                                continue;
                            target[name][objKeys[i]]=new Proxy( value[objKeys[i]], SmartBind.getProxyHandler(bindContext, bindPath+'.'+name+"."+objKeys[i]));
                        }
                        // TODO it can be faster than run all items
                        var bindKeys=Object.keys(bindContext.mapDom);
                        for ( var i=0; i<bindKeys.length; i++ ) {
                            // console.log("test...", bindKeys[i], " for ", bindPath+"."+name);
                            if ( bindKeys[i].startsWith(bindPath+"."+name) ) {
                                // console.log("its ok, lets update dom...", bindKeys[i]);
                                SmartBind.processBindToDom( bindContext, bindKeys[i] );
                            }
                        }
                    }
                    return true;
                }
            };
        }
        SmartBind.processBindToDom=function(bindContext, bindPath) {
            var domList=bindContext.mapDom[bindPath];
            if ( typeof domList != 'undefined' ) {
                try {
                    for ( var i=0; i < domList.length ; i++){
                        var dataTarget=SmartBind.getDataTarget(bindContext, bindPath);
                        if ( 'target' in dataTarget )
                            domList[i].value=dataTarget.target[dataTarget.item];
                        else
                            console.warn("Could not get data target", bindContext, bindPath);
                    }
                } catch (e){
                    console.warn("bind fail", bindPath, bindContext, e);
                }
            }
        }
    }
})();

Then, to set, just:

var bindContext=SmartBind.BindContext();
SmartBind.add(bindContext, document.getElementById('a'));
SmartBind.add(bindContext, document.getElementById('b'));
SmartBind.add(bindContext, document.getElementById('c'));

var bindContext2=SmartBind.BindContext();
SmartBind.add(bindContext2, document.getElementById('d'));
SmartBind.add(bindContext2, document.getElementById('e'));
SmartBind.add(bindContext2, document.getElementById('f'));
SmartBind.add(bindContext2, document.getElementById('g'));

setTimeout( function() {
    document.getElementById('b').value='Via Script works too!'
}, 2000);

document.getElementById('g').addEventListener('click',function(){
bindContext2.data.test='Set by js value'
})

For now, I've just added the HTMLInputElement value bind.

Let me know if you know how to improve it.

How to get SLF4J "Hello World" working with log4j?

Following is an example. You can see the details http://jkssweetlife.com/configure-slf4j-working-various-logging-frameworks/ and download the full codes here.

  • Add following dependency to your pom if you are using maven, otherwise, just download the jar files and put on your classpath

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
    </dependency>
    
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
    
  • Configure log4j.properties

    log4j.rootLogger=TRACE, stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSS} %-5p [%c] - %m%n
    
  • Java example

    public class Slf4jExample {
        public static void main(String[] args) {
    
            Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
    
            final String message = "Hello logging!";
            logger.trace(message);
            logger.debug(message);
            logger.info(message);
            logger.warn(message);
            logger.error(message);
        }
    }
    

What is the worst programming language you ever worked with?

I'm not sure if you meant to include scripting languages, but I've seen TCL (which is also annoying), but... the mIRC scripting language annoys me to no end.

Because of some oversight in the parsing, it's whitespace significant when it's not supposed to be. Conditional statements will sometimes be executed when they're supposed to be skipped because of this. Opening a block statement cannot be done on a separate line, etc.

Other than that it's just full of messy, inconsistent syntax that was probably designed that way to make very basic stuff easy, but at the same time makes anything a little more complex barely readable.

I lost most of my mIRC scripts, or I could have probably found some good examples of what a horrible mess it forces you to create :(

Update Angular model after setting input value with jQuery

add .change() after setting the value.

example:('id').val.('value').change();

also don't forget to add onchange or ng-change tag in html

How can I recover a lost commit in Git?

Another way to get to the deleted commit is with the git fsck command.

git fsck --lost-found

This will output something like at the last line:

dangling commit xyz

We can check that it is the same commit using reflog as suggested in other answers. Now we can do a git merge

git merge xyz

Note:
We cannot get the commit back with fsck if we have already run a git gc command which will remove the reference to the dangling commit.

Parsing JSON in Excel VBA

Two small contributions to Codo's answer:

' "recursive" version of GetObjectProperty
Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
    Dim names() As String
    Dim i As Integer

    names = Split(propertyName, ".")

    For i = 0 To UBound(names)
        Set JsonObject = ScriptEngine.Run("getProperty", JsonObject, names(i))
    Next

    Set GetObjectProperty = JsonObject
End Function

' shortcut to object array
Public Function GetObjectArrayProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object()
    Dim a() As Object
    Dim i As Integer
    Dim l As Integer

    Set JsonObject = GetObjectProperty(JsonObject, propertyName)

    l = GetProperty(JsonObject, "length") - 1

    ReDim a(l)

    For i = 0 To l
        Set a(i) = GetObjectProperty(JsonObject, CStr(i))
    Next

    GetObjectArrayProperty = a
End Function

So now I can do stuff like:

Dim JsonObject As Object
Dim Value() As Object
Dim i As Integer
Dim Total As Double

Set JsonObject = DecodeJsonString(CStr(request.responseText))

Value = GetObjectArrayProperty(JsonObject, "d.Data")

For i = 0 To UBound(Value)
    Total = Total + Value(i).Amount
Next

WCF Service Returning "Method Not Allowed"

My case: configuring the service on new server. ASP.NET 4.0 was not installed/registered properly; svc extension was not recognized.

Swift days between two NSDates

let calendar = NSCalendar.currentCalendar();
let component1 = calendar.component(.Day, fromDate: fromDate)
let component2 = calendar.component(.Day, fromDate: toDate)
let difference  = component1 - component2

What is best tool to compare two SQL Server databases (schema and data)?

I like Open DBDiff.

While not the most complete tool, it works great, it's free, and it's very easy to use.

How to change the port of Tomcat from 8080 to 80?

Just goto conf folder of tomcat

open the server.xml file

Goto one of the connector node which look like the following

<Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Simply change the port

save and restart tomcat

'printf' vs. 'cout' in C++

More differences: "printf" returns an integer value (equal to the number of characters printed) and "cout" does not return anything

And.

cout << "y = " << 7; is not atomic.

printf("%s = %d", "y", 7); is atomic.

cout performs typechecking, printf doesn't.

There's no iostream equivalent of "% d"

python 2.7: cannot pip on windows "bash: pip: command not found"

I found this much simpler. Simply type this into the terminal:

PATH=$PATH:C:\[pythondir]\scripts 

C# : Converting Base Class to Child Class

I don't think you can downcast an object, however there is a simple way to "downcast" the object outside the box. It isn't type safe, but it works. First serialize the object into json, then deserialize it into the child class object. It works the same as if you were passing the object between apis. So, while there are some people who may say "this doesn't work or isn't good", I would argue that it is exactly the way our internet currently works, so... why not use that method? No mapping required as long as parameter names are the same, and they will be if it is a child class. Note: This will likely not copy any private fields; if you have a constructor with parameters, this probably needs to be tested as well to ensure there aren't side effects.

Here's my toolbox:

public static string ConvertToJson<T>(this T obj)
{
    return JsonConvert.SerializeObject(obj);
}
public static T ConvertToObject<T>(this string json)
{
    if (string.IsNullOrEmpty(json))
    {
        return Activator.CreateInstance<T>();
    }
    return JsonConvert.DeserializeObject<T>(json);
}

Here's how to use it:

var sfcl = networkClient.ConvertToJson().ConvertToObject<SkyfilterClient>();

Get month and year from a datetime in SQL Server 2005

cast(cast(sq.QuotaDate as date) as varchar(7))

gives "2006-04" format

Error "can't load package: package my_prog: found packages my_prog and main"

Also, if all you are trying to do is break up the main.go file into multiple files, then just name the other files "package main" as long as you only define the main function in one of those files, you are good to go.

Getting and removing the first character of a string

See ?substring.

x <- 'hello stackoverflow'
substring(x, 1, 1)
## [1] "h"
substring(x, 2)
## [1] "ello stackoverflow"

The idea of having a pop method that both returns a value and has a side effect of updating the data stored in x is very much a concept from object-oriented programming. So rather than defining a pop function to operate on character vectors, we can make a reference class with a pop method.

PopStringFactory <- setRefClass(
  "PopString",
  fields = list(
    x = "character"  
  ),
  methods = list(
    initialize = function(x)
    {
      x <<- x
    },
    pop = function(n = 1)
    {
      if(nchar(x) == 0)
      {
        warning("Nothing to pop.")
        return("")
      }
      first <- substring(x, 1, n)
      x <<- substring(x, n + 1)
      first
    }
  )
)

x <- PopStringFactory$new("hello stackoverflow")
x
## Reference class object of class "PopString"
## Field "x":
## [1] "hello stackoverflow"
replicate(nchar(x$x), x$pop())
## [1] "h" "e" "l" "l" "o" " " "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"

Java program to connect to Sql Server and running the sample query From Eclipse

Refer the below link.

There are two important changes that you should make

driver name as "com.microsoft.sqlserver.jdbc.SQLServerDriver"

& in URL "jdbc:sqlserver://localhost:1433"+";databaseName=AdventureWorks2008R2"

http://www.programcreek.com/2010/05/java-code-for-connecting-ms-sql-server-by-using-sql-server-authentication/

Is it possible to have different Git configuration for different projects?

Another way is to use direnv and to separate config files per directory. For example:

.
+-- companyA
¦  +-- .envrc
¦  +-- .gitconfig
+-- companyB
¦  +-- .envrc
¦  +-- .gitconfig
+-- personal
   +-- .envrc
   +-- .gitconfig

Each .envrc should contain something like this:

export GIT_CONFIG=$(pwd)/.gitconfig

And .gitconfig is usual gitconfig with desired values.

Datetime in where clause

You don't say which database you are using but in MS SQL Server it would be

WHERE DateField = {d '2008-12-20'}

If it is a timestamp field then you'll need a range:

WHERE DateField BETWEEN {ts '2008-12-20 00:00:00'} AND {ts '2008-12-20 23:59:59'}

Can I have multiple Xcode versions installed?

Yes, you can install multiple versions of Xcode. They will install into separate directories. I've found that the best practice is to install the version that came with your Mac first and then install downloaded versions, but it probably doesn't make a big difference. See http://developer.apple.com/documentation/Xcode/Conceptual/XcodeCoexistence/Contents/Resources/en.lproj/Details/Details.html this Apple Developer Connection page for lots of details. <- Page does not exist anymore!

Remove leading or trailing spaces in an entire column of data

Quite often the issue is a non-breaking space - CHAR(160) - especially from Web text sources -that CLEAN can't remove, so I would go a step further than this and try a formula like this which replaces any non-breaking spaces with a standard one

=TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160)," ")))

Ron de Bruin has an excellent post on tips for cleaning data here

You can also remove the CHAR(160) directly without a workaround formula by

  • Edit .... Replace your selected data,
  • in Find What hold ALT and type 0160 using the numeric keypad
  • Leave Replace With as blank and select Replace All

How can I create a link to a local file on a locally-run web page?

back to 2017:

use URL.createObjectURL( file ) to create local link to file system that user select;

don't forgot to free memory by using URL.revokeObjectURL()

CSS Calc Viewport Units Workaround?

Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.

FIDDLE (In IE10+)

Solution (for other browsers): box-sizing

1) Start of by setting your height as 100vh.

2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height.

3) Just offset the extra padding-top with a negative margin-top

FIDDLE

div
{
    /*height: calc(100vh - 75vw);*/
    height: 100vh;
    margin-top: -75vw;
    padding-top: 75vw;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background: pink;
}

How to request Location Permission at runtime

Location permission privacy change in Android 10 or Android Q.

We have to define additional ACCESS_BACKGROUND_LOCATION permission if user wants to access their current location in background so user needs to granted permission runtime also in requestPermission()

If we are using lower than Android 10 device then ACCESS_BACKGROUND_LOCATION permission allow automatically with ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission

This tabular format might be easy to understand what if we don't specify ACCESS_BACKGROUND_LOCATION in manifest file.

enter image description here

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> // here we defined ACCESS_BACKGROUND_LOCATION for Android 10 device

MainActivity.java
Call checkRunTimePermission() in onCreate() or onResume()

public void checkRunTimePermission() {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || 
             ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED||
             ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                gpsTracker = new GPSTracker(context);

        } else {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                        10);
        }
   } else {
            gpsTracker = new GPSTracker(context); //GPSTracker is class that is used for retrieve user current location
   }
}

 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 10) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            gpsTracker = new GPSTracker(context);
        } else {
            if (!ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.ACCESS_FINE_LOCATION)) {
                // If User Checked 'Don't Show Again' checkbox for runtime permission, then navigate user to Settings
                AlertDialog.Builder dialog = new AlertDialog.Builder(context);
                dialog.setTitle("Permission Required");
                dialog.setCancelable(false);
                dialog.setMessage("You have to Allow permission to access user location");
                dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package",
                                context.getPackageName(), null));
                        //i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivityForResult(i, 1001);
                    }
                });
                AlertDialog alertDialog = dialog.create();
                alertDialog.show();
            }
            //code for deny
        }
    }
}

@Override
public void startActivityForResult(Intent intent, int requestCode) {
    super.startActivityForResult(intent, requestCode);
    switch (requestCode) {
        case 1001:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
                        ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED 
                        || ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    gpsTracker = new GPSTracker(context);
                    if (gpsTracker.canGetLocation()) {
                        latitude = gpsTracker.getLatitude();
                        longitude = gpsTracker.getLongitude();
                    }
                } else {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_BACKGROUND_LOCATION},10);
                }
            }
            break;
        default:
            break;
    }
}

build.gradle (app level)

android {
    compileSdkVersion 29 //should be >= 29
    buildToolsVersion "29.0.2"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.example.runtimepermission"
        minSdkVersion 21
        targetSdkVersion 29 //should be >= 29
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
}

Here you can find GPSTracker.java file code

Refreshing all the pivot tables in my excel workbook with a macro

You have a PivotTables collection on a the VB Worksheet object. So, a quick loop like this will work:

Sub RefreshPivotTables()
    Dim pivotTable As PivotTable
    For Each pivotTable In ActiveSheet.PivotTables
        pivotTable.RefreshTable
    Next
End Sub

Notes from the trenches:

  1. Remember to unprotect any protected sheets before updating the PivotTable.
  2. Save often.
  3. I'll think of more and update in due course... :)

Good luck!

Import SQL dump into PostgreSQL database

You can do it in pgadmin3. Drop the schema(s) that your dump contains. Then right-click on the database and choose Restore. Then you can browse for the dump file.

What design patterns are used in Spring framework?

Observer-Observable: it is used in ApplicationContext's event mechanism

@angular/material/index.d.ts' is not a module

After upgrading to Angular 9 (released today), I ran into this issue as well and found that they made the breaking change mentioned in the answer. I can't find a reason for why they made this change.

I have a material.module.ts file that I import / export all the material components (not the most efficient, but useful for quick development). I went through and updated all my imports to the individual material folders, although an index.ts barrel might be better. Again, not sure why they made this change, but I'm guessing it has to do with tree-shaking efficiencies.

Including my material.module.ts below in case it helps anyone, it's inspired off other material modules I've found:

NOTE: As other blog posts have mentioned and from my personal experience, be careful when using a shared module like below. I have 5~ different feature modules (lazy loaded) in my app that I imported my material module into. Out of curiosity, I stopped using the shared module and instead only imported the individual material components each feature module needed. This reduced my bundle size quite a bit, almost a 200kb reduction. I assumed that the build optimization process would properly drop any component not used by my modules, but it doesn't seem to be the case...

// material.module.ts
import { ModuleWithProviders, NgModule} from "@angular/core";
import { MAT_LABEL_GLOBAL_OPTIONS, MatNativeDateModule, MAT_DATE_LOCALE } from '@angular/material/core';
import { MatIconRegistry } from '@angular/material/icon';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatRippleModule } from '@angular/material/core';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatTreeModule } from '@angular/material/tree';

@NgModule({
    imports: [
        MatAutocompleteModule,
        MatBadgeModule,
        MatButtonModule,
        MatButtonToggleModule,
        MatCardModule,
        MatCheckboxModule,
        MatChipsModule,
        MatStepperModule,
        MatDatepickerModule,
        MatDialogModule,
        MatExpansionModule,
        MatFormFieldModule,
        MatGridListModule,
        MatIconModule,
        MatInputModule,
        MatListModule,
        MatMenuModule,
        MatPaginatorModule,
        MatProgressBarModule,
        MatProgressSpinnerModule,
        MatRadioModule,
        MatRippleModule,
        MatSelectModule,
        MatSidenavModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatSnackBarModule,
        MatSortModule,
        MatTableModule,
        MatTabsModule,
        MatToolbarModule,
        MatTooltipModule,
        MatTreeModule,
        MatNativeDateModule
    ],
    exports: [
        MatAutocompleteModule,
        MatBadgeModule,
        MatButtonModule,
        MatButtonToggleModule,
        MatCardModule,
        MatCheckboxModule,
        MatChipsModule,
        MatStepperModule,
        MatDatepickerModule,
        MatDialogModule,
        MatExpansionModule,
        MatFormFieldModule,
        MatGridListModule,
        MatIconModule,
        MatInputModule,
        MatListModule,
        MatMenuModule,
        MatPaginatorModule,
        MatProgressBarModule,
        MatProgressSpinnerModule,
        MatRadioModule,
        MatRippleModule,
        MatSelectModule,
        MatSidenavModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatSnackBarModule,
        MatSortModule,
        MatTableModule,
        MatTabsModule,
        MatToolbarModule,
        MatTooltipModule,
        MatTreeModule,
        MatNativeDateModule
    ],
    providers: [     
    ]
})
export class MaterialModule {
    constructor(public matIconRegistry: MatIconRegistry) {
        // matIconRegistry.registerFontClassAlias('fontawesome', 'fa');
    }

    static forRoot(): ModuleWithProviders<MaterialModule> {
        return {
            ngModule: MaterialModule,
            providers: [MatIconRegistry]
        };
    }
}

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

INSTALL_FAILED_VERSION_DOWNGRADE

All Android apps have a package name. The package name uniquely identifies the app on the device. If same packageName as app that's already installed on the device then this error Showing .

  1. You can uninstall the application from your device first and then install the fresh one .
  2. You could simply increase the number by one each time a new version is released.

How to have multiple colors in a Windows batch file?

An alternative adaptation of Jebs Solution that avoids the use of call via the use of Macro arguments and variable substitution:

@Echo off
 :# Macro Definitions
    For /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set "DEL=%%a")
 :# %\C% - Color macro; No error checking. Usage:
 :# %\C:?=HEXVALUE%Output String
 :# (%\C:?=HEXVALUE%Output String) & (%\C:?=HEXVALUE%Output String)
    Set "\C=For %%o in (1 2)Do if %%o==2 (( <nul set /p ".=%DEL%" > "^^!os:\n=^^!" ) & ( findstr /v /a:? /R "^$" "^^!os:\n=^^!" nul ) & ( del "^^!os:\n=^^!" > nul 2>&1 ) & (Set "testos=^^!os:\n=^^!" & If not "^^!testos^^!" == "^^!os^^!" (Echo/)))Else Set os="
 :# Ensure macro escaping is correct depending on delayedexpansion environment type
    If Not "!![" == "[" (
     Set "\C=%\C:^^=^%"
    )
    Setlocal EnableExtensions EnableDelayedExpansion
    PUSHD "%~dp0"
 :# SCRIPT MAIN BODY
 :# To force a new line; terminate an output string with: \n
 :# Usage info:
    (%\C:?=40% This is an example of usage\n)&(%\C:?=50% Trailing whitespace and periods are removed.\n)
    (%\C:?=0e% Leading spaces and periods are retained)&(%\C:?=e0%. NOT SUPPORTED - \n)
     %\C:?=02% Colon ^& Unescaped Ampersands ^& doublequotes\n
     %\C:?=02% LSS than ^& GTR than symbols ^& foreward and backward slashes\n
    (%\C:?=02% Pipe ^& Question Mark and Asterisk characters.\n) & (%\C:?=e2%^^! Exclaimation ^^! marks must be escaped\n)
:end
    POPD
    Endlocal
Goto :Eof

What exactly is the function of Application.CutCopyMode property in Excel

There is a good explanation at https://stackoverflow.com/a/33833319/903783

The values expected seem to be xlCopy and xlCut according to xlCutCopyMode enumeration (https://msdn.microsoft.com/en-us/VBA/Excel-VBA/articles/xlcutcopymode-enumeration-excel), but the 0 value (this is what False equals to in VBA) seems to be useful to clear Excel data put on the Clipboard.

Check if a process is running or not on Windows with Python

According to the ewerybody post: https://stackoverflow.com/a/29275361/7530957

Multiple problems can arise:

  • Multiple processes with the same name
  • Name of the long process

The 'ewerybody's' code will not work if the process name is long. So there is a problem with this line:

last_line.lower().startswith(process_name.lower())

Because last_line will be shorter than the process name.

So if you just want to know if a process/processes is/are active:

from subprocess import check_output

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    if check_output(call).splitlines()[3:]:
        return True

Instead for all the information of a process/processes

from subprocess import check_output

def process_exists(process_name):
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
    processes = []
    for process in check_output(call).splitlines()[3:]:
        process = process.decode()
        processes.append(process.split())
    return processes

Android: I lost my android key store, what should I do?

You can create a new keystore, but the Android Market wont allow you to upload the apk as an update - worse still, if you try uploading the apk as a new app it will not allow it either as it knows there is a 'different' version of the same apk already in the market even if you delete your previous version from the market

Do your absolute best to find that keystore!!

When you find it, email it to yourself so you have a copy on your gmail that you can go and get in the case you loose it from your hard drive!

Prevent text selection after double click

A simple Javascript function that makes the content inside a page-element unselectable:

function makeUnselectable(elem) {
  if (typeof(elem) == 'string')
    elem = document.getElementById(elem);
  if (elem) {
    elem.onselectstart = function() { return false; };
    elem.style.MozUserSelect = "none";
    elem.style.KhtmlUserSelect = "none";
    elem.unselectable = "on";
  }
}

Get current URL from IFRAME

If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:

var currentUrl = document.referrer;

and - here you've got the main url!

Getting the text from a drop-down box

var selectoption = document.getElementById("dropdown");
var optionText = selectoption.options[selectoption.selectedIndex].text;

How to move (and overwrite) all files from one directory to another?

It's just mv srcdir/* targetdir/.

If there are too many files in srcdir you might want to try something like the following approach:

cd srcdir
find -exec mv {} targetdir/ +

In contrast to \; the final + collects arguments in an xargs like manner instead of executing mv once for every file.

Get last n lines of a file, similar to tail

Based on Eyecue answer (Jun 10 '10 at 21:28): this class add head() and tail() method to file object.

class File(file):
    def head(self, lines_2find=1):
        self.seek(0)                            #Rewind file
        return [self.next() for x in xrange(lines_2find)]

    def tail(self, lines_2find=1):  
        self.seek(0, 2)                         #go to end of file
        bytes_in_file = self.tell()             
        lines_found, total_bytes_scanned = 0, 0
        while (lines_2find+1 > lines_found and
               bytes_in_file > total_bytes_scanned): 
            byte_block = min(1024, bytes_in_file-total_bytes_scanned)
            self.seek(-(byte_block+total_bytes_scanned), 2)
            total_bytes_scanned += byte_block
            lines_found += self.read(1024).count('\n')
        self.seek(-total_bytes_scanned, 2)
        line_list = list(self.readlines())
        return line_list[-lines_2find:]

Usage:

f = File('path/to/file', 'r')
f.head(3)
f.tail(3)

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

Adding multiple columns AFTER a specific column in MySQL

ALTER TABLE listing ADD count INT(5), ADD log VARCHAR(200), ADD status VARCHAR(20) AFTER stat

It will give good results.

Are there bookmarks in Visual Studio Code?

Under the general heading of 'editors always forget to document getting out…' to toggle go to another line and press the combination ctrl+shift+'N' to erase the current bookmark do the same on marked line…

How do I assert equality on two classes without an equals method?

I stumbled on a very similar case.

I wanted to compare on a test that an object had the same attribute values as another one, but methods like is(), refEq(), etc wouldn't work for reasons like my object having a null value in its id attribute.

So this was the solution I found (well, a coworker found):

import static org.apache.commons.lang.builder.CompareToBuilder.reflectionCompare;

assertThat(reflectionCompare(expectedObject, actualObject, new String[]{"fields","to","be","excluded"}), is(0));

If the value obtained from reflectionCompare is 0, it means they are equal. If it is -1 or 1, they differ on some attribute.

Chrome not rendering SVG referenced via <img> tag

i came here because i had the same problem, when i inspect the element i can see the file, but on the site i can't (even when using localhost)

the answer to my problem was in saving the SVG file. If you saved it from illustrator make sure to click 'embed' and not 'link'. as link will just refer to your local files rather than include the data (If i understand it correctly). enter image description here

I read about it on the adobe website which has some other useful tips for exporting http://www.adobe.com/inspire/2013/09/exporting-svg-illustrator.html

This worked for me, hope it was useful.

How to change UIPickerView height

There are only three valid heights for UIPickerView (162.0, 180.0 and 216.0).

You can use the CGAffineTransformMakeTranslation and CGAffineTransformMakeScale functions to properly fit the picker to your convenience.

Example:

CGAffineTransform t0 = CGAffineTransformMakeTranslation (0, pickerview.bounds.size.height/2);
CGAffineTransform s0 = CGAffineTransformMakeScale       (1.0, 0.5);
CGAffineTransform t1 = CGAffineTransformMakeTranslation (0, -pickerview.bounds.size.height/2);
pickerview.transform = CGAffineTransformConcat          (t0, CGAffineTransformConcat(s0, t1));

The above code change the height of picker view to half and re-position it to the exact (Left-x1, Top-y1) position.

Efficiently counting the number of lines of a text file. (200mb+)

If you're running this on a Linux/Unix host, the easiest solution would be to use exec() or similar to run the command wc -l $path. Just make sure you've sanitized $path first to be sure that it isn't something like "/path/to/file ; rm -rf /".

What is the string concatenation operator in Oracle?

It is ||, for example:

select 'Mr ' || ename from emp;

The only "interesting" feature I can think of is that 'x' || null returns 'x', not null as you might perhaps expect.

What's the difference between nohup and ampersand

The nohup command is a signal masking utility and catches the hangup signal. Where as ampersand doesn’t catch the hang up signals. The shell will terminate the sub command with the hang up signal when running a command using & and exiting the shell. This can be prevented by using nohup, as it catches the signal. Nohup command accept hang up signal which can be sent to a process by the kernel and block them. Nohup command is helpful in when a user wants to start long running application log out or close the window in which the process was initiated. Either of these actions normally prompts the kernel to hang up on the application, but a nohup wrapper will allow the process to continue. Using the ampersand will run the command in a child process and this child of the current bash session. When you exit the session, all of the child processes of that process will be killed. The ampersand relates to job control for the active shell. This is useful for running a process in a session in the background.

How to unnest a nested list

itertools provides the chain function for that:

From http://docs.python.org/library/itertools.html#recipes:

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

Note that the result is an iterable, so you may need list(flatten(...)).

Docker: adding a file from a parent directory

With docker-compose, you could set context folder:

#docker-compose.yml
version: '3.3'    
services:
      yourservice:
        build:
          context: ./
          dockerfile: ./docker/yourservice/Dockerfile

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

Start up R in a fresh session and paste this in:

library(ggplot2)

df <- structure(list(year = c(1, 2, 3, 4), pollution = structure(c(346.82, 
134.308821199349, 130.430379885892, 88.275457392443), .Dim = 4L, .Dimnames = list(
    c("1999", "2002", "2005", "2008")))), .Names = c("year", 
"pollution"), row.names = c(NA, -4L), class = "data.frame")

df[] <- lapply(df, as.numeric) # make all columns numeric

ggplot(df, aes(year, pollution)) +
           geom_point() +
           geom_line() +
           labs(x = "Year", 
                y = "Particulate matter emissions (tons)", 
                title = "Motor vehicle emissions in Baltimore")

How to set the title text color of UIButton?

Swift UI solution

Button(action: {}) {
            Text("Button")
        }.foregroundColor(Color(red: 1.0, green: 0.0, blue: 0.0))

Swift 3, Swift 4, Swift 5

to improve comments. This should work:

button.setTitleColor(.red, for: .normal)

Powershell Execute remote exe with command line arguments on remote computer

I have been trying to achieve this by using 1 row single entry but I ended that Invoke command did not worked successfully because it is killing the process immediately after starting despite it can work if you are entering the session and waiting enough before exiting.

The only working way I could find, for example, to run a command with arguments and space on the remote machine HFVMACHINE1 (running Windows 7) is the following:

([WMICLASS]"\\HFVMACHINE1\ROOT\CIMV2:win32_process").Create('c:\Program Files (x86)\Thinware\vBackup\vBackup.exe -v HFSVR12-WWW')

How to remove the first and the last character of a string

You can do something like that :

"/installers/services/".replace(/^\/+/g,'').replace(/\/+$/g,'')

This regex is a common way to have the same behaviour of the trim function used in many languages.

A possible implementation of trim function is :

function trim(string, char){
    if(!char) char = ' '; //space by default
    char = char.replace(/([()[{*+.$^\\|?])/g, '\\$1'); //escape char parameter if needed for regex syntax.
    var regex_1 = new RegExp("^" + char + "+", "g");
    var regex_2 = new RegExp(char + "+$", "g");
    return string.replace(regex_1, '').replace(regex_2, '');
}

Which will delete all / at the beginning and the end of the string. It handles cases like ///installers/services///

You can also simply do :

"/installers/".substring(1, string.length-1);

/usr/bin/codesign failed with exit code 1

I was also getting this error ("/usr/bin/codesign failed with exit code 1"), and when I looked in Keychain Access my developer certificates were marked as "This certificate was signed by an unknown authority". I had recently upgraded to Mac OS 10.8 and have had a couple of other XCode (4.5.2) issues since then. It turns out I did not have the WWDR intermediate certificate installed. I downloaded that from the iOS Provisioning Portal, installed that in Keychain Access, and my project builds again!

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

Any constructor for any class as you know creates an object. So, the constructor should contain proper initialization code for its class. But if you have some class which extends another one (lets call it "parent") then constructor for the class cannot contain all the code needed for the initialization by definition (for example, you cannot define private fields of the parent). That's why constructor of the class has to call constructor of its parent. If you do not call it explicitly then the default parent constructor is called (which is without any parameter).

So, in your case, you can either implement default constructor in parent or directly call any constructor in the class.

How can I remove the "No file chosen" tooltip from a file input in Chrome?

It's better to avoid using unnecessary javascript. You can take advantage of the label tag to expand the click target of the input like so:

<label>
  <input type="file" style="display: none;">
  <a>Open</a>
</label>

Even though input is hidden, the link still works as a click target for it, and you can style it however you want.

How to get these two divs side-by-side?

#parent_div_1, #parent_div_2, #parent_div_3 {
  width: 100px;
  height: 100px;
  border: 1px solid red;
  margin-right: 10px;
  float: left;
}
.child_div_1 {
  float: left;
  margin-right: 5px;
}

Check working example at http://jsfiddle.net/c6242/1/

JQuery Datatables : Cannot read property 'aDataSort' of undefined

Also had this issue, This array was out of range:

order: [1, 'asc'],

How to convert Java String to JSON Object

You are passing into the JSONObject constructor an instance of a StringBuilder class.

This is using the JSONObject(Object) constructor, not the JSONObject(String) one.

Your code should be:

JSONObject jsonObj = new JSONObject(jsonString.toString());

How to go from Blob to ArrayBuffer

This is an async method which first checks for the availability of arrayBuffer method. This function is backward compatible and future proof.

async function blobToArrayBuffer(blob) {
    if ('arrayBuffer' in blob) return await blob.arrayBuffer();
    
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => reject;
        reader.readAsArrayBuffer(blob);
    });
}

How to get current screen width in CSS?

Based on your requirement i think you are wanted to put dynamic fields in CSS file, however that is not possible as CSS is a static language. However you can simulate the behaviour by using Angular.

Please refer to the below example. I'm here showing only one component.

login.component.html

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {

      cssProperty:any;
      constructor(private sanitizer: DomSanitizer) { 
        console.log(window.innerWidth);
        console.log(window.innerHeight);
        this.cssProperty = 'position:fixed;top:' + Math.floor(window.innerHeight/3.5) + 'px;left:' + Math.floor(window.innerWidth/3) + 'px;';
        this.cssProperty = this.sanitizer.bypassSecurityTrustStyle(this.cssProperty);
      }

    ngOnInit() {

      }

    }

login.component.ts

<div class="home">
    <div class="container" [style]="cssProperty">
        <div class="card">
            <div class="card-header">Login</div>
            <div class="card-body">Please login</div>
            <div class="card-footer">Login</div>
        </div>
    </div>
</div>

login.component.css

.card {
    max-width: 400px;
}
.card .card-body {
    min-height: 150px;
}
.home {
    background-color: rgba(171, 172, 173, 0.575);
}

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

It sounds like installing the VS2017 update for that specific version didn't also install the .NET Core 2.0 SDK. You can download that here.

To check which version of the SDK you've already got installed, run

dotnet --info

from the command line. Note that if there's a global.json file in either your current working directory or any ancestor directory, that will override which version of the SDK is run. (That's useful if you want to enforce a particular version for a project, for example.)

Judging by comments, some versions of VS2017 updates do install the .NET Core SDK. I suspect it may vary somewhat over time.

How to convert an object to a byte array in C#

Well a cast from myObject to byte[] is never going to work unless you've got an explicit conversion or if myObject is a byte[]. You need a serialization framework of some kind. There are plenty out there, including Protocol Buffers which is near and dear to me. It's pretty "lean and mean" in terms of both space and time.

You'll find that almost all serialization frameworks have significant restrictions on what you can serialize, however - Protocol Buffers more than some, due to being cross-platform.

If you can give more requirements, we can help you out more - but it's never going to be as simple as casting...

EDIT: Just to respond to this:

I need my binary file to contain the object's bytes. Only the bytes, no metadata whatsoever. Packed object-to-object. So I'll be implementing custom serialization.

Please bear in mind that the bytes in your objects are quite often references... so you'll need to work out what to do with them.

I suspect you'll find that designing and implementing your own custom serialization framework is harder than you imagine.

I would personally recommend that if you only need to do this for a few specific types, you don't bother trying to come up with a general serialization framework. Just implement an instance method and a static method in all the types you need:

public void WriteTo(Stream stream)
public static WhateverType ReadFrom(Stream stream)

One thing to bear in mind: everything becomes more tricky if you've got inheritance involved. Without inheritance, if you know what type you're starting with, you don't need to include any type information. Of course, there's also the matter of versioning - do you need to worry about backward and forward compatibility with different versions of your types?

WCF on IIS8; *.svc handler mapping doesn't work

This was a really silly one for me. Adding this here as it's one of the more popular threads on svc 404 issues.

I had in my Project Settings' \ Web \ Project URL, pasted:

http://blah.webservice.local.blahblah.com/Blah.svc

And for some unknown reason (having done this a thousand times) didn't spot straight away that the name of the .svc file was at the end.

DOH!

I had just pasted the address from my WCF test client and hadn't checked it sufficiently. What this did in the background was create an IIS application at the .svc address and I was getting nothing out of IIS. I couldn't work out how I couldn't even hit the .svc file.

Simple fix, obviously, just remove the application in IIS and change the project URL.

After almost 20 years at this, you can still make schoolboy errors / rookie mistakes. Hope this helps someone.

Interface extends another interface but implements its methods

ad 1. It does not implement its methods.

ad 4. The purpose of one interface extending, not implementing another, is to build a more specific interface. For example, SortedMap is an interface that extends Map. A client not interested in the sorting aspect can code against Map and handle all the instances of for example TreeMap, which implements SortedMap. At the same time, another client interested in the sorted aspect can use those same instances through the SortedMap interface.

In your example you are repeating the methods from the superinterface. While legal, it's unnecessary and doesn't change anything in the end result. The compiled code will be exactly the same whether these methods are there or not. Whatever Eclipse's hover says is irrelevant to the basic truth that an interface does not implement anything.

JavaScript hashmap equivalent

My 'Map' implementation, derived from Christoph's example:

Example usage:

var map = new Map();  // Creates an "in-memory" map
var map = new Map("storageId");  // Creates a map that is loaded/persisted using html5 storage

function Map(storageId) {
    this.current = undefined;
    this.size = 0;
    this.storageId = storageId;
    if (this.storageId) {
        this.keys = new Array();
        this.disableLinking();
    }
}

Map.noop = function() {
    return this;
};

Map.illegal = function() {
    throw new Error("illegal operation for maps without linking");
};

// Map initialisation from an existing object
// doesn't add inherited properties if not explicitly instructed to:
// omitting foreignKeys means foreignKeys === undefined, i.e. == false
// --> inherited properties won't be added
Map.from = function(obj, foreignKeys) {
    var map = new Map;
    for(var prop in obj) {
        if(foreignKeys || obj.hasOwnProperty(prop))
            map.put(prop, obj[prop]);
    }
    return map;
};

Map.prototype.disableLinking = function() {
    this.link = Map.noop;
    this.unlink = Map.noop;
    this.disableLinking = Map.noop;

    this.next = Map.illegal;
    this.key = Map.illegal;
    this.value = Map.illegal;
//    this.removeAll = Map.illegal;


    return this;
};

// Overwrite in Map instance if necessary
Map.prototype.hash = function(value) {
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :
        value.toString());
};

Map.prototype.hash.current = 0;

// --- Mapping functions

Map.prototype.get = function(key) {
    var item = this[this.hash(key)];
    if (item === undefined) {
        if (this.storageId) {
            try {
                var itemStr = localStorage.getItem(this.storageId + key);
                if (itemStr && itemStr !== 'undefined') {
                    item = JSON.parse(itemStr);
                    this[this.hash(key)] = item;
                    this.keys.push(key);
                    ++this.size;
                }
            } catch (e) {
                console.log(e);
            }
        }
    }
    return item === undefined ? undefined : item.value;
};

Map.prototype.put = function(key, value) {
    var hash = this.hash(key);

    if(this[hash] === undefined) {
        var item = { key : key, value : value };
        this[hash] = item;

        this.link(item);
        ++this.size;
    }
    else this[hash].value = value;
    if (this.storageId) {
        this.keys.push(key);
        try {
            localStorage.setItem(this.storageId + key, JSON.stringify(this[hash]));
        } catch (e) {
            console.log(e);
        }
    }
    return this;
};

Map.prototype.remove = function(key) {
    var hash = this.hash(key);
    var item = this[hash];
    if(item !== undefined) {
        --this.size;
        this.unlink(item);

        delete this[hash];
    }
    if (this.storageId) {
        try {
            localStorage.setItem(this.storageId + key, undefined);
        } catch (e) {
            console.log(e);
        }
    }
    return this;
};

// Only works if linked
Map.prototype.removeAll = function() {
    if (this.storageId) {
        for (var i=0; i<this.keys.length; i++) {
            this.remove(this.keys[i]);
        }
        this.keys.length = 0;
    } else {
        while(this.size)
            this.remove(this.key());
    }
    return this;
};

// --- Linked list helper functions

Map.prototype.link = function(item) {
    if (this.storageId) {
        return;
    }
    if(this.size == 0) {
        item.prev = item;
        item.next = item;
        this.current = item;
    }
    else {
        item.prev = this.current.prev;
        item.prev.next = item;
        item.next = this.current;
        this.current.prev = item;
    }
};

Map.prototype.unlink = function(item) {
    if (this.storageId) {
        return;
    }
    if(this.size == 0)
        this.current = undefined;
    else {
        item.prev.next = item.next;
        item.next.prev = item.prev;
        if(item === this.current)
            this.current = item.next;
    }
};

// --- Iterator functions - only work if map is linked

Map.prototype.next = function() {
    this.current = this.current.next;
};

Map.prototype.key = function() {
    if (this.storageId) {
        return undefined;
    } else {
        return this.current.key;
    }
};

Map.prototype.value = function() {
    if (this.storageId) {
        return undefined;
    }
    return this.current.value;
};

How to create a box when mouse over text in pure CSS?

You can easily make this CSS Tool Tip through simple code :-

    <!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
a.info{
    position:relative; /*this is the key*/
    color:#000;
    top:100px;
    left:50px;
    text-decoration:none;
    text-align:center;
  }



a.info span{display: none}

a.info:hover span{ /*the span will display just on :hover state*/
    display:block;
    position:absolute;
    top:-60px;
    width:15em;
    border:5px solid #0cf;
    background-color:#cff; color:#000;
    text-align: center;
    padding:10px;
  }

  a.info:hover span:after{ /*the span will display just on :hover state*/
    content:'';
    position:absolute;
    bottom:-11px;
    width:10px;
    height:10px;
    border-bottom:5px solid #0cf;
    border-right:5px solid #0cf;
    background:#cff;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    transform:rotate(45deg);
  }


</style>
</head>
<body>
<a href="#" class="info">Shailender Arora <span>TOOLTIP</span></a>
  </div>
</body>
</html>

http://jsbin.com/ebucoz/25/edit

NodeJs : TypeError: require(...) is not a function

For me, this was an issue with cyclic dependencies.

IOW, module A required module B, and module B required module A.

So in module B, require('./A') is an empty object rather than a function.

How to deal with cyclic dependencies in Node.js

Dead simple example of using Multiprocessing Queue, Pool and Locking

The best solution for your problem is to utilize a Pool. Using Queues and having a separate "queue feeding" functionality is probably overkill.

Here's a slightly rearranged version of your program, this time with only 2 processes coralled in a Pool. I believe it's the easiest way to go, with minimal changes to original code:

import multiprocessing
import time

data = (
    ['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'],
    ['e', '1'], ['f', '3'], ['g', '5'], ['h', '7']
)

def mp_worker((inputs, the_time)):
    print " Processs %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs

def mp_handler():
    p = multiprocessing.Pool(2)
    p.map(mp_worker, data)

if __name__ == '__main__':
    mp_handler()

Note that mp_worker() function now accepts a single argument (a tuple of the two previous arguments) because the map() function chunks up your input data into sublists, each sublist given as a single argument to your worker function.

Output:

Processs a  Waiting 2 seconds
Processs b  Waiting 4 seconds
Process a   DONE
Processs c  Waiting 6 seconds
Process b   DONE
Processs d  Waiting 8 seconds
Process c   DONE
Processs e  Waiting 1 seconds
Process e   DONE
Processs f  Waiting 3 seconds
Process d   DONE
Processs g  Waiting 5 seconds
Process f   DONE
Processs h  Waiting 7 seconds
Process g   DONE
Process h   DONE

Edit as per @Thales comment below:

If you want "a lock for each pool limit" so that your processes run in tandem pairs, ala:

A waiting B waiting | A done , B done | C waiting , D waiting | C done, D done | ...

then change the handler function to launch pools (of 2 processes) for each pair of data:

def mp_handler():
    subdata = zip(data[0::2], data[1::2])
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

Now your output is:

 Processs a Waiting 2 seconds
 Processs b Waiting 4 seconds
 Process a  DONE
 Process b  DONE
 Processs c Waiting 6 seconds
 Processs d Waiting 8 seconds
 Process c  DONE
 Process d  DONE
 Processs e Waiting 1 seconds
 Processs f Waiting 3 seconds
 Process e  DONE
 Process f  DONE
 Processs g Waiting 5 seconds
 Processs h Waiting 7 seconds
 Process g  DONE
 Process h  DONE

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

JavaFX open new window

The code below worked for me I used part of the code above inside the button class.

public Button signupB;

public void handleButtonClick (){

    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
        /*
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 630, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }

}

}

Looping through JSON with node.js

You can iterate through JavaScript objects this way:

for(var attributename in myobject){
    console.log(attributename+": "+myobject[attributename]);
}

myobject could be your json.data

Spring RestTemplate timeout

  1. RestTemplate timeout with SimpleClientHttpRequestFactory To programmatically override the timeout properties, we can customize the SimpleClientHttpRequestFactory class as below.

Override timeout with SimpleClientHttpRequestFactory

//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory() 
{
    SimpleClientHttpRequestFactory clientHttpRequestFactory
                      = new SimpleClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}
  1. RestTemplate timeout with HttpComponentsClientHttpRequestFactory SimpleClientHttpRequestFactory helps in setting timeout but it is very limited in functionality and may not prove sufficient in realtime applications. In production code, we may want to use HttpComponentsClientHttpRequestFactory which support HTTP Client library along with resttemplate.

HTTPClient provides other useful features such as connection pool, idle connection management etc.

Read More : Spring RestTemplate + HttpClient configuration example

Override timeout with HttpComponentsClientHttpRequestFactory

//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory() 
{
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
                      = new HttpComponentsClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}

reference: Spring RestTemplate timeout configuration example

React-Router External link

I don't think React-Router provides this support. The documentation mentions

A < Redirect > sets up a redirect to another route in your application to maintain old URLs.

You could try using something like React-Redirect instead

Difference between Visibility.Collapsed and Visibility.Hidden

The difference is that Visibility.Hidden hides the control, but reserves the space it occupies in the layout. So it renders whitespace instead of the control. Visibilty.Collapsed does not render the control and does not reserve the whitespace. The space the control would take is 'collapsed', hence the name.

The exact text from the MSDN:

Collapsed: Do not display the element, and do not reserve space for it in layout.

Hidden: Do not display the element, but reserve space for the element in layout.

Visible: Display the element.

See: http://msdn.microsoft.com/en-us/library/system.windows.visibility.aspx

Paused in debugger in chrome?

Threads > switch "Main" to "app"

In the "Threads" section I changed the context from "Main" > to "app". The "app" should have a blue arrow aside.

Paste text on Android Emulator

In a terminal, type adb shell input text 'my string here. With some characters escaped like \$ that'

Note that an alternative method for including spaces in the text is to substitute %s for each space character.

Android ListView Divider

set android:dividerHeight="1dp"

<ListView
            android:id="@+id/myphnview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@drawable/dividerheight"
            android:background="#E9EAEC"
            android:clickable="true"
    android:divider="@color/white"
                android:dividerHeight="1dp"
                android:headerDividersEnabled="true" >
    </ListView>

Google Maps API v2: How to make markers clickable?

Another Solution : you get the marker by its title

public class MarkerDemoActivity extends android.support.v4.app.FragmentActivity implements OnMarkerClickListener
{
      private Marker myMarker;    

      private void setUpMap()
      {
      .......
      googleMap.setOnMarkerClickListener(this);

      myMarker = googleMap.addMarker(new MarkerOptions()
                  .position(latLng)
                  .title("My Spot")
                  .snippet("This is my spot!")
                  .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
      ......
      }

  @Override
  public boolean onMarkerClick(final Marker marker) 
  {

     String name= marker.getTitle();

      if (name.equalsIgnoreCase("My Spot")) 
      {
          //write your code here
      }
  }
}

Where does the iPhone Simulator store its data?

If the Simulator is running you can get the path to any app's container:

xcrun simctl get_app_container booted <app bundle identifier>

Example output:

$ xcrun simctl get_app_container booted com.example.app
/Users/jappleseed/Library/Developer/CoreSimulator/Devices/7FB6CB8F-63CB-4F27-BDAB-884814DA6FE0/data/Containers/Bundle/Application/466AE987-76BC-47CF-A207-266E65E7DE0A/example.app

"booted" can be substituted to most simctl commands anywhere a device UDID is expected.

You can see the list of devices with xcrun simctl list and get help on specific commands with xcrun simctl help.

Update: By popular request in Xcode 8.3 you can now specify the kind of container you want by appending "app", "data", "groups", or an app group identifier.

To get the data container:

$ xcrun simctl get_app_container booted com.example.app data

Google Play on Android 4.0 emulator

You could download it from a Android 4.0 phone and then mount the system image rw and copy it over.

Didnt tried it before but it should work.

How do I compare two variables containing strings in JavaScript?

instead of using the == sign, more safer use the === sign when compare, the code that you post is work well

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

I had same issue reported here. I solved the issue moving the mainTest.cpp from a subfolder src/mainTest/ to the main folder src/ I guess this was your problem too.

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

you can also skip creating dictionary altogether. i used below approach to same problem .

 mappedItems: {};
 items.forEach(item => {     
        if (mappedItems[item.key]) {
           mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
        } else {
          mappedItems[item.key] = [];
          mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        }
    });

How to set the part of the text view is clickable

Boom Check this for java Lovers :D We can modify it according to our need:

List<Pair<String, View.OnClickListener>> pairsList = new ArrayList<>();

        pairsList.add(new Pair<>("38,50", v -> {
            Intent intent = new Intent(SignUpActivity.this, WebActivity.class);
            intent.putExtra("which", "tos");
            startActivity(intent);
        }));

        pairsList.add(new Pair<>("81,95", v -> {
            Intent intent = new Intent(SignUpActivity.this, WebActivity.class);
            intent.putExtra("which", "policy");
            startActivity(intent);
        }));

        makeLinks(pairsList); // Method calling


private void makeLinks(List<Pair<String, View.OnClickListener>> pairsList) {

        SpannableString ss = new SpannableString(By signing up, I’m agree to PAKRISM’s Terms of Use and confirms that I have read Privacy Policy);

        for (Pair<String, View.OnClickListener> pair : pairsList) {

            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(View textView) {
                    //Toast.makeText(MyApplication.getAppContext(), "Clicked!", Toast.LENGTH_SHORT).show();
                    pair.second.onClick(textView);
                }

                @Override
                public void updateDrawState(TextPaint ds) {

                    ds.linkColor = ContextCompat.getColor(SignUpActivity.this, R.color.primary_main);
                    ds.setUnderlineText(true);

                    super.updateDrawState(ds);
                }
            };

            String[] indexes = pair.first.split(",");
            ss.setSpan(clickableSpan, Integer.parseInt(indexes[0]), Integer.parseInt(indexes[1]), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        
        TextView tv = findViewById(R.id.txtView);
        tv.setText(ss);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
    }

Adding maven nexus repo to my pom.xml

It seems the answers here do not support an enterprise use case where a Nexus server has multiple users and has project-based isolation (protection) based on user id ALONG with using an automated build (CI) system like Jenkins. You would not be able to create a settings.xml file to satisfy the different user ids needed for different projects. I am not sure how to solve this, except by opening Nexus up to anonymous access for reading repositories, unless the projects could store a project-specific generic user id in their pom.xml.

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

What are the differences between json and simplejson Python modules?

The builtin json module got included in Python 2.6. Any projects that support versions of Python < 2.6 need to have a fallback. In many cases, that fallback is simplejson.

Exception 'open failed: EACCES (Permission denied)' on Android

I have observed this once when running the application inside the emulator. In the emulator settings, you need to specify the size of external storage ("SD Card") properly. By default, the "external storage" field is empty, and that probably means there is no such device and EACCES is thrown even if permissions are granted in the manifest.

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

Round to 2 decimal places

double formattedNumber = Double.parseDouble(new DecimalFormat("#.##").format(unformattedNumber));

worked for me :)

How to delete a whole folder and content?

Safest code I know:

private boolean recursiveRemove(File file) {
    if(file == null  || !file.exists()) {
        return false;
    }

    if(file.isDirectory()) {
        File[] list = file.listFiles();

        if(list != null) {

            for(File item : list) {
                recursiveRemove(item);
            }

        }
    }

    if(file.exists()) {
        file.delete();
    }

    return !file.exists();
}

Checks the file exists, handles nulls, checks the directory was actually deleted

Where can I set environment variables that crontab will use?

I got one more solution for this problem:

0 5 * * * . $HOME/.profile; /path/to/command/to/run

In this case it will pick all the environment variable defined in your $HOME/.profile file.

Of course $HOME is also not set, you have to replace it with the full path of your $HOME.

Why does PEP-8 specify a maximum line length of 79 characters?

Here's why I like the 80-character with: at work I use Vim and work on two files at a time on a monitor running at, I think, 1680x1040 (I can never remember). If the lines are any longer, I have trouble reading the files, even when using word wrap. Needless to say, I hate dealing with other people's code as they love long lines.

WooCommerce - get category for product page

A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
    $product_cat_id = $term->term_id;
    break;
}

Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.

<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>

Log4j, configuring a Web App to use a relative path

I've finally done it in this way.

Added a ServletContextListener that does the following:

public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    System.setProperty("rootPath", context.getRealPath("/"));
}

Then in the log4j.properties file:

log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log

By doing it in this way Log4j will write into the right folder as long as you don't use it before the "rootPath" system property has been set. This means that you cannot use it from the ServletContextListener itself but you should be able to use it from anywhere else in the app.

It should work on every web container and OS as it's not dependent on a container specific system property and it's not affected by OS specific path issues. Tested with Tomcat and Orion web containers and on Windows and Linux and it works fine so far.

What do you think?

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

React-router: How to manually invoke Link?

React Router v5 - React 16.8+ with Hooks (updated 09/23/2020)

If you're leveraging React Hooks, you can take advantage of the useHistory API that comes from React Router v5.

import React, {useCallback} from 'react';
import {useHistory} from 'react-router-dom';

export default function StackOverflowExample() {
  const history = useHistory();
  const handleOnClick = useCallback(() => history.push('/sample'), [history]);

  return (
    <button type="button" onClick={handleOnClick}>
      Go home
    </button>
  );
}

Another way to write the click handler if you don't want to use useCallback

const handleOnClick = () => history.push('/sample');

React Router v4 - Redirect Component

The v4 recommended way is to allow your render method to catch a redirect. Use state or props to determine if the redirect component needs to be shown (which then trigger's a redirect).

import { Redirect } from 'react-router';

// ... your class implementation

handleOnClick = () => {
  // some action...
  // then redirect
  this.setState({redirect: true});
}

render() {
  if (this.state.redirect) {
    return <Redirect push to="/sample" />;
  }

  return <button onClick={this.handleOnClick} type="button">Button</button>;
}

Reference: https://reacttraining.com/react-router/web/api/Redirect

React Router v4 - Reference Router Context

You can also take advantage of Router's context that's exposed to the React component.

static contextTypes = {
  router: PropTypes.shape({
    history: PropTypes.shape({
      push: PropTypes.func.isRequired,
      replace: PropTypes.func.isRequired
    }).isRequired,
    staticContext: PropTypes.object
  }).isRequired
};

handleOnClick = () => {
  this.context.router.push('/sample');
}

This is how <Redirect /> works under the hood.

Reference: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Redirect.js#L46,L60

React Router v4 - Externally Mutate History Object

If you still need to do something similar to v2's implementation, you can create a copy of BrowserRouter then expose the history as an exportable constant. Below is a basic example but you can compose it to inject it with customizable props if needed. There are noted caveats with lifecycles, but it should always rerender the Router, just like in v2. This can be useful for redirects after an API request from an action function.

// browser router file...
import createHistory from 'history/createBrowserHistory';
import { Router } from 'react-router';

export const history = createHistory();

export default class BrowserRouter extends Component {
  render() {
    return <Router history={history} children={this.props.children} />
  }
}

// your main file...
import BrowserRouter from './relative/path/to/BrowserRouter';
import { render } from 'react-dom';

render(
  <BrowserRouter>
    <App/>
  </BrowserRouter>
);

// some file... where you don't have React instance references
import { history } from './relative/path/to/BrowserRouter';

history.push('/sample');

Latest BrowserRouter to extend: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js

React Router v2

Push a new state to the browserHistory instance:

import {browserHistory} from 'react-router';
// ...
browserHistory.push('/sample');

Reference: https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md

Google Maps API OVER QUERY LIMIT per second limit

Often when you need to show so many points on the map, you'd be better off using the server-side approach, this article explains when to use each:

Geocoding Strategies: https://developers.google.com/maps/articles/geocodestrat

The client-side limit is not exactly "10 requests per second", and since it's not explained in the API docs I wouldn't rely on its behavior.

git: patch does not apply

git apply --reverse --reject example.patch

When you created a patch file with the branch names reversed:

ie. git diff feature_branch..master instead of git diff master..feature_branch

Char array declaration and initialization in C

myarray = "abc";

...is the assignation of a pointer on "abc" to the pointer myarray.

This is NOT filling the myarray buffer with "abc".

If you want to fill the myarray buffer manually, without strcpy(), you can use:

myarray[0] = 'a', myarray[1] = 'b', myarray[2] = 'c', myarray[3] = 0;

or

char *ptr = myarray;
*ptr++ = 'a', *ptr++ = 'b', *ptr++ = 'c', *ptr = 0;

Your question is about the difference between a pointer and a buffer (an array). I hope you now understand how C addresses each kind.

html - table row like a link

I know this question is already answered but I still don't like any solution on this page. For the people who use JQuery I made a final solution which enables you to give the table row almost the same behaviour as the <a> tag.

This is my solution:

jQuery You can add this for example to a standard included javascript file

$('body').on('mousedown', 'tr[url]', function(e){
    var click = e.which;
    var url = $(this).attr('url');
    if(url){
        if(click == 1){
            window.location.href = url;
        }
        else if(click == 2){
            window.open(url, '_blank');
            window.focus();
        }
        return true;
    }
});

HTML Now you can use this on any <tr> element inside your HTML

<tr url="example.com">
    <td>value</td>
    <td>value</td>
    <td>value</td>
<tr>

Check if cookie exists else set cookie to Expire in 10 days

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

What is the best way to create a string array in python?

Sometimes I need a empty char array. You cannot do "np.empty(size)" because error will be reported if you fill in char later. Then I usually do something quite clumsy but it is still one way to do it:

# Suppose you want a size N char array
charlist = [' ']*N # other preset character is fine as well, like 'x'
chararray = np.array(charlist)
# Then you change the content of the array
chararray[somecondition1] = 'a'
chararray[somecondition2] = 'b'

The bad part of this is that your array has default values (if you forget to change them).

find all the name using mysql query which start with the letter 'a'

Try this simple select:

select * 
from artists 
where name like "a%"

How to catch a unique constraint error in a PL/SQL block?

I suspect the condition you are looking for is DUP_VAL_ON_INDEX

EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
        DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')

What is a software framework?

In General, A frame Work is real or Conceptual structure of intended to serve as a support or Guide for the building some thing that expands the structure into something useful...

Xampp Access Forbidden php

The only solution that worked for me after spending hours researching online

sudo chmod -R 0777 /opt/lampp/htdocs/projectname

Get String in YYYYMMDD format from JS date object?

_x000D_
_x000D_
// UTC/GMT 0_x000D_
document.write('UTC/GMT 0: ' + (new Date()).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812013509_x000D_
_x000D_
// Client local time_x000D_
document.write('<br/>Local time: ' + (new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000)).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812113509
_x000D_
_x000D_
_x000D_

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

How to get text box value in JavaScript

+1 Gumbo: ‘id’ is the easiest way to access page elements. IE (pre version 8) will return things with a matching ‘name’ if it can't find anything with the given ID, but this is a bug.

i am getting only "software".

id-vs-name won't affect this; I suspect what's happened is that (contrary to the example code) you've forgotten to quote your ‘value’ attribute:

<input type="text" name="txtJob" value=software engineer>

expand/collapse table rows with JQuery

I liked the simplest answer provided. However, I didn't like the choppiness of the collapsing. So I combined a solution from this question: How to Use slideDown (or show) function on a table row? to make it a smoother animation when the rows slide up or down. It involves having to wrap the content of each td in a div. This allows it to smoothly animate the collapsing. When the rows are expanded, it will replace the div, with just the content.

So here's the html:

<table>
<tr class="header">
    <td>CARS</td>
</tr>
<tr class="thing">
    <td>car</td>
</tr>
<tr class="thing">
    <td>truck</td>
</tr>
<tr class="header">
    <td>HOUSES</td>
</tr>
<tr class="thing">
    <td>split level</td>
</tr>
<tr class="thing">
    <td>trailer</td>
</tr>

And here's the js

$('.header').click(function(){
if($(this).hasClass("collapsed")){
    $(this).nextUntil('tr.header')
    .find('td')
    .parent()
    .find('td > div')
    .slideDown("fast", function(){
        var $set = $(this);
        $set.replaceWith($set.contents());
    });
    $(this).removeClass("collapsed");
} else {
    $(this).nextUntil('tr.header')
    .find('td')
    .wrapInner('<div style="display: block;" />')
    .parent()
    .find('td > div')
    .slideUp("fast");
    $(this).addClass("collapsed");
}
});

Checkout this fiddle for an example https://jsfiddle.net/p9mtqhm7/52/

What's the point of the X-Requested-With header?

Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.

Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.

Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html

Merge two json/javascript arrays in to one array

var json1=["Chennai","Bangalore"];
var json2=["TamilNadu","Karanataka"];

finaljson=json1.concat(json2);

How to create a toggle button in Bootstrap

Initial answer from 2013

An excellent (unofficial) Bootstrap Switch is available.

Classic 2013 Switch

<input type="checkbox" name="my-checkbox" checked>
$("[name='my-checkbox']").bootstrapSwitch();

It uses radio types or checkboxes as switches. A type attribute has been added since V.1.8.

Source code is available on Github.

Note from 2018

I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.

Please consider having a look at modern Switches like this one from the React Component framework (not Bootstrap related, but can be integrated in Bootstrap grid and UI though).

Other implementations exist for Angular, View or jQuery.

Modern 2018 Switch

import '../assets/index.less'
import React from 'react'
import ReactDOM from 'react-dom'
import Switch from 'rc-switch'

class Switcher extends React.Component {
  state = {
    disabled: false,
  }

  toggle = () => {
    this.setState({
      disabled: !this.state.disabled,
    })
  }

  render() {
    return (
      <div style={{ margin: 20 }}>
        <Switch
          disabled={this.state.disabled}
          checkedChildren={'?'}
          unCheckedChildren={'?'}
        />
        </div>
      </div>
    )
  }
}

ReactDOM.render(<Switcher />, document.getElementById('__react-content'))

Native Bootstrap Switches

See ohkts11's answer below about the native Bootstrap switches.

Call of overloaded function is ambiguous

That is ambiguous because a pointer is just an address, so an int can also be treated as a pointer – 0 (an int) can be converted to unsigned int or char * equally easily.

The short answer is to call p.setval() with something that's unambiguously one of the types it's implemented for: unsigned int or char *. p.setval(0U), p.setval((unsigned int)0), and p.setval((char *)0) will all compile.

It's generally a good idea to stay out of this situation in the first place, though, by not defining overloaded functions with such similar types.

How to use LocalBroadcastManager?

By declaring one in your AndroidManifest.xml file with the tag (also called static)

<receiver android:name=".YourBrodcastReceiverClass"  android:exported="true">
<intent-filter>
    <!-- The actions you wish to listen to, below is an example -->
    <action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>

You will notice that the broadcast receiver declared above has a property of exported=”true”. This attribute tells the receiver that it can receive broadcasts from outside the scope of the application.
2. Or dynamically by registering an instance with registerReceiver (what is known as context registered)

public abstract Intent registerReceiver (BroadcastReceiver receiver, 
            IntentFilter filter);

public void onReceive(Context context, Intent intent) {
//Implement your logic here
}

There are three ways to send broadcasts:
The sendOrderedBroadcast method, makes sure to send broadcasts to only one receiver at a time. Each broadcast can in turn, pass along data to the one following it, or to stop the propagation of the broadcast to the receivers that follow.
The sendBroadcast is similar to the method mentioned above, with one difference. All broadcast receivers receive the message and do not depend on one another.
The LocalBroadcastManager.sendBroadcast method only sends broadcasts to receivers defined inside your application and does not exceed the scope of your application.

Windows command for file size only

If you don't want to do this in a batch script, you can do this from the command line like this:

for %I in (test.jpg) do @echo %~zI

Ugly, but it works. You can also pass in a file mask to get a listing for more than one file:

for %I in (*.doc) do @echo %~znI

Will display the size, file name of each .DOC file.

NULL or BLANK fields (ORACLE)

COUNT(expresion) returns the count of of rows where expresion is not null. So SELECT COUNT (COL_NAME) FROM TABLE WHERE COL_NAME IS NULL will return 0, because you are only counting col_name where col_name is null, and a count of nothing but nulls is zero. COUNT(*) will return the number of rows of the query:

SELECT COUNT (*) FROM TABLE WHERE COL_NAME IS NULL

The other two queries are probably not returning any rows, since they are trying to match against strings with one blank character, and your dump query indicates that the column is actually holding nulls.

If you have rows with variable strings of space characters that you want included in the count, use:

SELECT COUNT (*) FROM TABLE WHERE trim(COL_NAME) IS NULL

trim(COL_NAME) will remove beginning and ending spaces. If the string is nothing but spaces, then the string becomes '' (empty string), which is equivalent to null in Oracle.

Add up a column of numbers at the Unix shell

I would use "du" instead.

$ cat files.txt | xargs du -c | tail -1
4480    total

If you just want the number:

cat files.txt | xargs du -c | tail -1 | awk '{print $1}'

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

I tried the solution xcode-select --install but it don't help me, I update from Sierra to High and happened this, my solution:

sudo xcode-select --reset

How can I throw CHECKED exceptions from inside Java 8 streams?

I agree with the comments above, in using Stream.map you are limited to implementing Function which doesn't throw Exceptions.

You could however create your own FunctionalInterface that throws as below..

@FunctionalInterface
public interface UseInstance<T, X extends Throwable> {
  void accept(T instance) throws X;
}

then implement it using Lambdas or references as shown below.

import java.io.FileWriter;
import java.io.IOException;

//lambda expressions and the execute around method (EAM) pattern to
//manage resources

public class FileWriterEAM  {
  private final FileWriter writer;

  private FileWriterEAM(final String fileName) throws IOException {
    writer = new FileWriter(fileName);
  }
  private void close() throws IOException {
    System.out.println("close called automatically...");
    writer.close();
  }
  public void writeStuff(final String message) throws IOException {
    writer.write(message);
  }
  //...

  public static void use(final String fileName, final UseInstance<FileWriterEAM, IOException> block) throws IOException {

    final FileWriterEAM writerEAM = new FileWriterEAM(fileName);    
    try {
      block.accept(writerEAM);
    } finally {
      writerEAM.close();
    }
  }

  public static void main(final String[] args) throws IOException {

    FileWriterEAM.use("eam.txt", writerEAM -> writerEAM.writeStuff("sweet"));

    FileWriterEAM.use("eam2.txt", writerEAM -> {
        writerEAM.writeStuff("how");
        writerEAM.writeStuff("sweet");      
      });

    FileWriterEAM.use("eam3.txt", FileWriterEAM::writeIt);     

  }


 void writeIt() throws IOException{
     this.writeStuff("How ");
     this.writeStuff("sweet ");
     this.writeStuff("it is");

 }

}

Color Tint UIButton Image

For Xamarin.iOS (C#):

UIButton messagesButton = new UIButton(UIButtonType.Custom);
UIImage icon = UIImage.FromBundle("Images/icon.png");
messagesButton.SetImage(icon.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal);
messagesButton.TintColor = UIColor.White;
messagesButton.Frame = new RectangleF(0, 0, 25, 25);

Insert all values of a table into another table in SQL

I think this statement might do what you want.

INSERT INTO newTableName (SELECT column1, column2, column3 FROM oldTable);

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

How do I check if file exists in jQuery or pure JavaScript?

So long as you're testing files on the same domain this should work:

function fileExists(url) {
    if(url){
        var req = new XMLHttpRequest();
        req.open('GET', url, false);
        req.send();
        return req.status==200;
    } else {
        return false;
    }
}

Please note, this example is using a GET request, which besides getting the headers (all you need to check weather the file exists) gets the whole file. If the file is big enough this method can take a while to complete.

The better way to do this would be changing this line: req.open('GET', url, false); to req.open('HEAD', url, false);

iPhone X / 8 / 8 Plus CSS media queries

iPhone X

@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

iPhone 8

@media only screen 
    and (device-width : 375px) 
    and (device-height : 667px) 
    and (-webkit-device-pixel-ratio : 2) { }

iPhone 8 Plus

@media only screen 
    and (device-width : 414px) 
    and (device-height : 736px) 
    and (-webkit-device-pixel-ratio : 3) { }


iPhone 6+/6s+/7+/8+ share the same sizes, while the iPhone 7/8 also do.


Looking for a specific orientation ?

Portrait

Add the following rule:

    and (orientation : portrait) 

Landscape

Add the following rule:

    and (orientation : landscape) 



References:

What is "loose coupling?" Please provide examples

I propose a very simple Test of Code Coupling:

  1. Piece A of code is tightly coupled to Piece B of code if there exists any possible modification to the Piece B that would force changes in Piece A in order to keep correctness.

  2. Piece A of code is not tightly coupled to Piece B of code if there is no possible modification to the Piece B that would make a change to Piece A necessary.

This will help you to verify how much coupling there is between the pieces of your code. for reasoning on that see this blog post: http://marekdec.wordpress.com/2012/11/14/loose-coupling-tight-coupling-decoupling-what-is-that-all-about/

jQuery.click() vs onClick

Go for this as it will give you both standard and performance.

 $('#myDiv').click(function(){
      //Some code
 });

As the second method is simple JavaScript code and is faster than jQuery. But here performance will be approximately the same.

Split a large pandas dataframe

I guess now we can use plain iloc with range for this.

chunk_size = int(df.shape[0] / 4)
for start in range(0, df.shape[0], chunk_size):
    df_subset = df.iloc[start:start + chunk_size]
    process_data(df_subset)
    ....

MySQL: can't access root account

You can use the init files. Check the MySQL official documentation on How to Reset the Root Password (including comments for alternative solutions).

So basically using init files, you can add any SQL queries that you need for fixing your access (such as GRAND, CREATE, FLUSH PRIVILEGES, etc.) into init file (any file).

Here is my example of recovering root account:

echo "CREATE USER 'root'@'localhost' IDENTIFIED BY 'root';" > your_init_file.sql
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;" >> your_init_file.sql 
echo "FLUSH PRIVILEGES;" >> your_init_file.sql

and after you've created your file, you can run:

killall mysqld
mysqld_safe --init-file=$PWD/your_init_file.sql

then to check if this worked, press Ctrl+Z and type: bg to run the process from the foreground into the background, then verify your access by:

mysql -u root -proot
mysql> show grants;
+-------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                   |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' |

See also:

How to add key,value pair to dictionary?

For quick reference, all the following methods will add a new key 'a' if it does not exist already or it will update the existing key value pair with the new value offered:

data['a']=1  

data.update({'a':1})

data.update(dict(a=1))

data.update(a=1)

You can also mixing them up, for example, if key 'c' is in data but 'd' is not, the following method will updates 'c' and adds 'd'

data.update({'c':3,'d':4})  

Java math function to convert positive int to negative and negative to positive?

Yes, as was already noted by Jeffrey Bosboom (Sorry Jeffrey, I hadn't noticed your comment when I answered), there is such a function: Math.negateExact.

and

No, you probably shouldn't be using it. Not unless you need a method reference.

How to delete a specific file from folder using asp.net

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files. 
    foreach (string f in picList)
    {
        // Remove path from the file name. 
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path. 
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files. 
    foreach (string f in txtList)
    {

        // Remove path from the file name. 
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied. 
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied. 
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}

Refresh Page C# ASP.NET

Depending on what exactly you require, a Server.Transfer might be a resource-cheaper alternative to Response.Redirect. More information is in Server.Transfer Vs. Response.Redirect.

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

I had this same problem and had to refer to the php manual which told me the mysql and mysqli extensions require libmysql.dll to load. I searched for it under C:\windows\system32 (windows 7) and could not find, so I downloaded it here and placed it in my C:\windows\system32. I restarted Apache and everything worked fine. Took me 3 days to figure out, hope it helps.

Verify a certificate chain using openssl verify

If you only want to verify that issuer of UserCert.pem is actually Intermediate.pem do the following (example uses: OpenSSL 1.1.1):

openssl verify -no-CAfile -no-CApath -partial_chain -trusted Intermediate.pem UserCert.pem

and you will get:

UserCert.pem: OK

or

UserCert.pem: verification failed

Required attribute on multiple checkboxes with the same name?

Sorry, now I've read what you expected better, so I'm updating the answer.

Based on the HTML5 Specs from W3C, nothing is wrong. I created this JSFiddle test and it's behaving correctly based on the specs (for those browsers based on the specs, like Chrome 11 and Firefox 4):

_x000D_
_x000D_
<form>_x000D_
    <input type="checkbox" name="q" id="a-0" required autofocus>_x000D_
    <label for="a-0">a-1</label>_x000D_
    <br>_x000D_
_x000D_
    <input type="checkbox" name="q" id="a-1" required>_x000D_
    <label for="a-1">a-2</label>_x000D_
    <br>_x000D_
_x000D_
    <input type="checkbox" name="q" id="a-2" required>_x000D_
    <label for="a-2">a-3</label>_x000D_
    <br>_x000D_
_x000D_
    <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

I agree that it isn't very usable (in fact many people have complained about it in the W3C's mailing lists).

But browsers are just following the standard's recommendations, which is correct. The standard is a little misleading, but we can't do anything about it in practice. You can always use JavaScript for form validation, though, like some great jQuery validation plugin.

Another approach would be choosing a polyfill that can make (almost) all browsers interpret form validation rightly.

Check if one list contains element from the other

Loius answer is correct, I just want to add an example:

listOne.add("A");
listOne.add("B");
listOne.add("C");

listTwo.add("D");
listTwo.add("E");
listTwo.add("F");      

boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

TypeError: got multiple values for argument

I had the same problem that is really easy to make, but took me a while to see through.

I had copied the declaration to where I was using it and had left the 'self' argument there, but it took me ages to realise that.

I had

self.myFunction(self, a, b, c='123')

but it should have been

self.myFunction(a, b, c='123')

Best practice for storing and protecting private API keys in applications

Ages old post, but still good enough. I think hiding it in an .so library would be great, using NDK and C++ of course. .so files can be viewed in a hex editor, but good luck decompiling that :P

Formatting floats in a numpy array

[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]

How to download PDF automatically using js?

/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
    var save = document.createElement('a');
    save.href = fileURL;
    save.target = '_blank';
    var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
    save.download = fileName || filename;
       if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
            document.location = save.href; 
// window event not working here
        }else{
            var evt = new MouseEvent('click', {
                'view': window,
                'bubbles': true,
                'cancelable': false
            });
            save.dispatchEvent(evt);
            (window.URL || window.webkitURL).revokeObjectURL(save.href);
        }   
}

// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand)     {
    var _window = window.open(fileURL, '_blank');
    _window.document.close();
    _window.document.execCommand('SaveAs', true, fileName || fileURL)
    _window.close();
}
}

How to use?

download_file(fileURL, fileName); //call function

Source: convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/

Creating a new user and password with Ansible

I know that I'm late to the party, but there is another solution that I'm using. It might be handy for distros that don't have --stdin in passwd binary.

- hosts: localhost
  become: True
  tasks:
    - name: Change user password
      shell: "yes '{{ item.pass }}' | passwd {{ item.user }}"
      loop:
       - { pass: 123123, user: foo }
       - { pass: asdf, user: bar }
      loop_control:
        label: "{{ item.user }}"

Label in loop_control is responsible for printing only username. The whole playbook or just user variables (you can use vars_files:) should be encrypted with ansible-vault.

Display names of all constraints for a table in Oracle SQL

maybe this can help:

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

cheers

Cocoa: What's the difference between the frame and the bounds?

try to run the code below

- (void)viewDidLoad {
    [super viewDidLoad];
    UIWindow *w = [[UIApplication sharedApplication] keyWindow];
    UIView *v = [w.subviews objectAtIndex:0];

    NSLog(@"%@", NSStringFromCGRect(v.frame));
    NSLog(@"%@", NSStringFromCGRect(v.bounds));
}

the output of this code is:

case device orientation is Portrait

{{0, 0}, {768, 1024}}
{{0, 0}, {768, 1024}}

case device orientation is Landscape

{{0, 0}, {768, 1024}}
{{0, 0}, {1024, 768}}

obviously, you can see the difference between frame and bounds

How do I convert a C# List<string[]> to a Javascript array?

For those trying to do it without using JSON, the following is how I did it:

<script>
    var originalLabels = [ '@Html.Raw(string.Join("', '", Model.labels))'];
</script>

CSS two divs next to each other

I use a mixture of float and overflow-x:hidden. Minimal code, always works.

https://jsfiddle.net/9934sc4d/4/ - PLUS you don't need to clear your float!

.left-half{
    width:200px;
    float:left;
}
.right-half{
    overflow-x:hidden;
}

Removing pip's cache?

On Mac OS (Mavericks), I had to delete /tmp/pip-build/

CSS for grabbing cursors (drag & drop)

The closed hand cursor is not 16x16. If you would need them in the same dimensions, here you have both of them in 16x16 px

opened hand closed hand

Or if you need original cursors:

https://www.google.com/intl/en_ALL/mapfiles/openhand.cur https://www.google.com/intl/en_ALL/mapfiles/closedhand.cur

LDAP filter for blank (empty) attribute

This article http://technet.microsoft.com/en-us/library/ee198810.aspx led me to the solution. The only change is the placement of the exclamation mark.

(!manager=*)

It seems to be working just as wanted.

Upload files from Java client to a HTTP server

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    String uploadFolder = getServletContext().getRealPath("")
            + File.separator + DATA_DIRECTORY;//DATA_DIRECTORY is directory where you upload this file on the server

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(MAX_REQUEST_SIZE);//MAX_REQUEST_SIZE is the size which size you prefer

And use <form enctype="multipart/form-data"> and use <input type="file"> in the html

Adding an arbitrary line to a matplotlib plot in ipython notebook

Matplolib now allows for 'annotation lines' as the OP was seeking. The annotate() function allows several forms of connecting paths and a headless and tailess arrow, i.e., a simple line, is one of them.

ax.annotate("",
            xy=(0.2, 0.2), xycoords='data',
            xytext=(0.8, 0.8), textcoords='data',
            arrowprops=dict(arrowstyle="-",
                      connectionstyle="arc3, rad=0"),
            )

In the documentation it says you can draw only an arrow with an empty string as the first argument.

From the OP's example:

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
              xy=(70, 100), xycoords='data',
              xytext=(70, 250), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              connectionstyle="arc3,rad=0."), 
              )

# draw diagonal line from (70, 90) to (90, 200)
plt.annotate("",
              xy=(70, 90), xycoords='data',
              xytext=(90, 200), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              connectionstyle="arc3,rad=0."), 
              )

plt.show()

Example inline image

Just as in the approach in gcalmettes's answer, you can choose the color, line width, line style, etc..

Here is an alteration to a portion of the code that would make one of the two example lines red, wider, and not 100% opaque.

# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
              xy=(70, 100), xycoords='data',
              xytext=(70, 250), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              edgecolor = "red",
                              linewidth=5,
                              alpha=0.65,
                              connectionstyle="arc3,rad=0."), 
              )

You can also add curve to the connecting line by adjusting the connectionstyle.

XAMPP Start automatically on Windows 7 startup

Try following Steps for Apache

  • Go to your XAMPP installation folder. Right-click xampp-control.exe. Click "Run as administrator"
  • Stop Apache service action port
  • Tick this (in snapshot) check box. It will ask if you want to install as service. Click "Yes".
  • Go to Windows Services by typing Window + R, then typing services.msc

  • Enter a new service name as Apache2 (or similar)

  • Set it as automatic, if you want it to run as startup.

Repeat the steps for the MySQL service

enter image description here

Transform only one axis to log10 scale with ggplot2

Another solution using scale_y_log10 with trans_breaks, trans_format and annotation_logticks()

library(ggplot2)

m <- ggplot(diamonds, aes(y = price, x = color))

m + geom_boxplot() +
  scale_y_log10(
    breaks = scales::trans_breaks("log10", function(x) 10^x),
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  ) +
  theme_bw() +
  annotation_logticks(sides = 'lr') +
  theme(panel.grid.minor = element_blank())

Javascript to open popup window and disable parent window

This is how I finally did it! You can put a layer (full sized) over your body with high z-index and, of course hidden. You will make it visible when the window is open, make it focused on click over parent window (the layer), and finally will disappear it when the opened window is closed or submitted or whatever.

      .layer
  {
        position: fixed;
        opacity: 0.7;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        z-index: 999999;
        background-color: #BEBEBE;
        display: none;
        cursor: not-allowed;
  }

and layer in the body:

                <div class="layout" id="layout"></div>

function that opens the popup window:

    var new_window;
    function winOpen(){
        $(".layer").show();
        new_window=window.open(srcurl,'','height=750,width=700,left=300,top=200');
    }

keeping new window focused:

         $(document).ready(function(){
             $(".layout").click(function(e) {
                new_window.focus();
            }
        });

and in the opened window:

    function submit(){
        var doc = window.opener.document,
        doc.getElementById("layer").style.display="none";
         window.close();
    }   

   window.onbeforeunload = function(){
        var doc = window.opener.document;
        doc.getElementById("layout").style.display="none";
   }

I hope it would help :-)

Is it possible to change the radio button icon in an android radio button group

The easier way to only change the radio button is simply set selector for drawable right

<RadioButton
    ...
    android:button="@null"
    android:checked="false"
    android:drawableRight="@drawable/radio_button_selector" />

And the selector is:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_checkbox_checked" android:state_checked="true" />
    <item android:drawable="@drawable/ic_checkbox_unchecked" android:state_checked="false" /></selector>

That's all

Creating a script for a Telnet session?

I've used various methods for scripting telnet sessions under unix, but the simplest one is probably a sequence of echo and sleep commands, with their output piped into telnet. Piping the output into another command is also a possibility.

Silly example

(echo password; echo "show ip route"; sleep 1; echo "quit" ) | telnet myrouter

This (basicallly) retrieves the routing table of a Cisco router.

jQuery Toggle Text?

I've written my own little extension for toggleText. It may come in handy.

Fiddle: https://jsfiddle.net/b5u14L5o/

jQuery Extension:

jQuery.fn.extend({
    toggleText: function(stateOne, stateTwo) {
        return this.each(function() {
            stateTwo = stateTwo || '';
            $(this).text() !== stateTwo && stateOne ? $(this).text(stateTwo)
                                                    : $(this).text(stateOne);
        });  
    }
});

Usage:

...
<button>Unknown</button>
...
//------- BEGIN e.g. 1 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Show', 'Hide'); // Hide, Show, Hide ... and so on.
});
//------- END e.g. 1 -------

//------- BEGIN e.g. 2 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Unknown', 'Hide'); // Hide, Unknown, Hide ...
});
//------- END e.g. 2 -------

//------- BEGIN e.g. 3 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText(); // Unknown, Unknown, Unknown ...
});
//------- END e.g.3 -------

//------- BEGIN e.g.4 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Show'); // '', Show, '' ...
});
//------- END e.g.4 -------

angular.js ng-repeat li items with html content

use ng-bind-html-unsafe

it will apply html with text inside like below:

    <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
        {{ opt.text }}
    </li>

Which versions of SSL/TLS does System.Net.WebRequest support?

I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.

If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.

How can I escape double quotes in XML attributes values?

A double quote character (") can be escaped as &quot;, but here's the rest of the story...

Double quote character must be escaped in this context:

  • In XML attributes delimited by double quotes:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    

Double quote character need not be escaped in most contexts:

  • In XML textual content:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • In XML attributes delimited by single quotes ('):

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    Similarly, (') require no escaping if (") are used for the attribute value delimiters:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    

See also

I want to vertical-align text in select box

I found that only adding padding-top pushed down the grey dropdown arrow box on the right, which was undesirable.

The method that worked for me was to go into the inspector and incrementally add padding until the text was centered. This will also reduce the size of the dropdown icon, but it will be centered as well so it isn't as visually disturbing.

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

For OSX your path needs to include /Users/yourusername

their example: /Development/adt-bundle/sdk/platform-tools
needs to be: /Users/yourusername/Development/adt-bundle/sdk/platform-tools

Background color of text in SVG

No this is not possible, SVG elements do not have background-... presentation attributes.

To simulate this effect you could draw a rectangle behind the text attribute with fill="green" or something similar (filters). Using JavaScript you could do the following:

var ctx = document.getElementById("the-svg"),
textElm = ctx.getElementById("the-text"),
SVGRect = textElm.getBBox();

var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    rect.setAttribute("x", SVGRect.x);
    rect.setAttribute("y", SVGRect.y);
    rect.setAttribute("width", SVGRect.width);
    rect.setAttribute("height", SVGRect.height);
    rect.setAttribute("fill", "yellow");
    ctx.insertBefore(rect, textElm);

insert vertical divider line between two nested divs, not full height

Try this. I set the blue box to float right, gave left and right a fixed height, and added a white border on the right of the left div. Also added rounded corners to more match your example (These won't work in ie 8 or less). I also took out the position: relative. You don't need it. Block level elements are set to position relative by default.

See it here: http://jsfiddle.net/ZSgLJ/

#left {
  float: left;
  width: 44%;
  margin: 0;
  padding: 0;
  border-right: 1px solid white;
  height:400px;
}

#right {
  position: relative;
  float: right;
  width: 49%;
  margin: 0;
  padding: 0;
  height:400px;
}

#blue_box {
  background-color:blue;
  border-radius: 10px;
  -moz-border-radius:10px;
  -webkit-border-radius: 10px;
  width: 45%;
  min-width: 400px;
  max-width: 600px;
  padding: 2%;
  float: right;
}

Get everything after the dash in a string in JavaScript

myString.split('-').splice(1).join('-')

CSS3 transform not working

In webkit-based browsers(Safari and Chrome), -webkit-transform is ignored on inline elements.. Set display: inline-block; to make it work. For demonstration/testing purposes, you may also want to use a negative angle or a transformation-origin lest the text is rotated out of the visible area.

Why does git status show branch is up-to-date when changes exist upstream?

Trivial answer yet accurate in some cases, such as the one that brought me here. I was working in a repo which was new for me and I added a file which was not seen as new by the status.

It ends up that the file matched a pattern in the .gitignore file.

How to solve npm install throwing fsevents warning on non-MAC OS?

If anyone get this error for ionic cordova install . just use this code npm install --no-optional in your cmd. And then run this code npm install -g ionic@latest cordova

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

How do I select between the 1st day of the current month and current day in MySQL?

A less orthodox approach might be

SELECT * FROM table_name 
WHERE LEFT(table_name.date, 7) = LEFT(CURDATE(), 7)
  AND table_name.date <= CURDATE();

as a date being between the first of a month and now is equivalent to a date being in this month, and before now. I do feel that this is a bit easier on the eyes than some other approaches, though.

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

I know it's an old post but I came across the exact same issue and I managed to use this by turning off MALWAREBYTES program which was causing the issue.

'invalid value encountered in double_scalars' warning, possibly numpy

Whenever you are working with csv imports, try to use df.dropna() to avoid all such warnings or errors.

How to specify the JDK version in android studio?

On a Mac, you can use terminal to go to /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home (or wherever your Android SDK is installed) and enter the following in the command prompt:

./java -version

python: create list of tuples from lists

You're after the zip function.

Taken directly from the question: How to merge lists into a list of tuples in Python?

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]

C# Remove object from list of objects

First you have to find out the object in the list. Then you can remove from the list.

       var item = myList.Find(x=>x.ItemName == obj.ItemName);
       myList.Remove(item);

VBA - how to conditionally skip a for loop iteration

VBA does not have a Continue or any other equivalent keyword to immediately jump to the next loop iteration. I would suggest a judicious use of Goto as a workaround, especially if this is just a contrived example and your real code is more complicated:

For i = LBound(Schedule, 1) To UBound(Schedule, 1)
    If (Schedule(i, 1) < ReferenceDate) Then
        PrevCouponIndex = i
        Goto NextIteration
    End If
    DF = Application.Run("SomeFunction"....)
    PV = PV + (DF * Coupon / CouponFrequency)
    '....'
    'a whole bunch of other code you are not showing us'
    '....'
    NextIteration:
Next

If that is really all of your code, though, @Brian is absolutely correct. Just put an Else clause in your If statement and be done with it.

How to draw a path on a map using kml file?

Mathias Lin code working beautifully. However, you might want to consider changing this part inside drawPath method:

 if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                    && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

GeoPoint can be less than zero as well, I switch mine to:

     if (lngLat.length >= 2 && gp1.getLatitudeE6() != 0 && gp1.getLongitudeE6() != 0
                    && gp2.getLatitudeE6() != 0 && gp2.getLongitudeE6() != 0) {

Thank you :D

How to set a value of a variable inside a template code?

Create a template tag:

The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.

Create a file named define_action.py inside of the templatetags directory with the following code:

from django import template
register = template.Library()

@register.simple_tag
def define(val=None):
  return val

Note: Development server won’t automatically restart. After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.


Then in your template you can assign values to the context like this:

{% load define_action %}
{% if item %}

   {% define "Edit" as action %}

{% else %}

   {% define "Create" as action %}

{% endif %}


Would you like to {{action}} this item?

Applying styles to tables with Twitter Bootstrap

Twitter bootstrap tables can be styled and well designed. You can style your table just adding some classes on your table and it’ll look nice. You might use it on your data reports, showing information, etc.

enter image description here You can use :

basic table
Striped rows
Bordered table
Hover rows
Condensed table
Contextual classes
Responsive tables

Striped rows Table :

    <table class="table table-striped" width="647">
    <thead>
    <tr>
    <th>#</th>
    <th>Name</th>
    <th>Address</th>
    <th>mail</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>1</td>
    <td>Thomas bell</td>
    <td>Brick lane, London</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td height="29">2</td>
    <td>Yan Chapel</td>
    <td>Toronto Australia</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td>3</td>
    <td>Pit Sampras</td>
    <td>Berlin, Germany</td>
    <td>Pit @yahoo.com</td>
    </tr>
    </tbody>
    </table>

Condensed table :

Compacting a table you need to add class class=”table table-condensed” .

    <table class="table table-condensed" width="647">
    <thead>
    <tr>
    <th>#</th>
    <th>Sample Name</th>
    <th>Address</th>
    <th>Mail</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>1</td>
    <td>Thomas bell</td>
    <td>Brick lane, London</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td height="29">2</td>
    <td>Yan Chapel</td>
    <td>Toronto Australia</td>
    <td>[email protected]</td>
    </tr>
    <tr>
    <td>3</td>
    <td>Pit Sampras</td>
    <td>Berlin, Germany</td>
    <td>Pit @yahoo.com</td>
    </tr>
    <tr>
    <td></td>
    <td colspan="3" align="center"></td>
    </tr>
    </tbody>
    </table>

Ref : http://twitterbootstrap.org/twitter-bootstrap-table-example-tutorial

Role/Purpose of ContextLoaderListener in Spring?

enter image description hereThis Bootstrap listener is to start up and shut down Spring's root WebApplicationContext. As a web application can have multiple dispatcher servlet and each having its own application context containing controllers, view resolver, handler mappings etc But you might want to have service beans, DAO beans in root application context and want to use in all child application context(application context created by dispatcher servlets).

2nd use of this listener is when you want to use spring security.

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

You can use plt.subplots_adjust to change the spacing between the subplots Link

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

left  = 0.125  # the left side of the subplots of the figure
right = 0.9    # the right side of the subplots of the figure
bottom = 0.1   # the bottom of the subplots of the figure
top = 0.9      # the top of the subplots of the figure
wspace = 0.2   # the amount of width reserved for blank space between subplots
hspace = 0.2   # the amount of height reserved for white space between subplots

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

PowerShell - Start-Process and Cmdline Switches

Unless the OP is using PowerShell Community Extensions which does provide a Start-Process cmdlet along with a bunch of others. If this the case then Glennular's solution works a treat since it matches the positional parameters of pscx\start-process : -path (position 1) -arguments (positon 2).

when exactly are we supposed to use "public static final String"?

? public makes it accessible across the other classes. You can use it without instantiate of the class or using any object.

? static makes it uniform value across all the class instances. It ensures that you don't waste memory creating many of the same thing if it will be the same value for all the objects.

? final makes it non-modifiable value. It's a "constant" value which is same across all the class instances and cannot be modified.

How do I pause my shell script for a second before continuing?

And what about:

read -p "Press enter to continue"

load json into variable

  • this will get JSON file externally to your javascript variable.
  • now this sample_data will contain the values of JSON file.

var sample_data = '';
$.getJSON("sample.json", function (data) {
    sample_data = data;
    $.each(data, function (key, value) {
        console.log(sample_data);
    });
});

Using group by and having clause

Having: It applies filter conditions to each group of rows. Where: It applies a filter of individual rows.