Programs & Examples On #Scope

Scope is an enclosing context where values and expressions are associated. Use this tag for questions about different types of scope as well for questions where scope may be unclear.

Why Is `Export Default Const` invalid?

If the component name is explained in the file name MyComponent.js, just don't name the component, keeps code slim.

import React from 'react'

export default (props) =>
    <div id='static-page-template'>
        {props.children}
    </div>

Update: Since this labels it as unknown in stack tracing, it isn't recommended

How do I get current scope dom-element in AngularJS controller?

The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element to do DOM operations. The method defined in the directive controller is accessible in the main controller.

Example, finding a child element:

var app = angular.module('myapp', []);
app.directive("testDir", function () {
    function link(scope, element) { 

    }
    return {
        restrict: "AE", 
        link: link, 
        controller:function($scope,$element){
            $scope.name2 = 'this is second name';
            var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
    }
    };
})

app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});

Access a global variable in a PHP function

<?php

    $data = 'My data';

    $menugen = function() use ($data) {

        echo "[ $data ]";
    };

    $menugen();
?>

You can also simplify

echo "[" . $data . "]"

to

echo "[$data]"

Setting dynamic scope variables in AngularJs - scope.<some_string>

Please keep in mind: this is just a JavaScript thing and has nothing to do with Angular JS. So don't be confused about the magical '$' sign ;)

The main problem is that this is an hierarchical structure.

console.log($scope.life.meaning);  // <-- Nope! This is undefined.
=> a.b.c

This is undefined because "$scope.life" is not existing but the term above want to solve "meaning".

A solution should be

var the_string = 'lifeMeaning';
$scope[the_string] = 42;
console.log($scope.lifeMeaning);
console.log($scope['lifeMeaning']);

or with a little more efford.

var the_string_level_one = 'life';
var the_string_level_two = the_string_level_one + '.meaning';
$scope[the_string_level_two ] = 42;
console.log($scope.life.meaning);
console.log($scope['the_string_level_two ']);

Since you can access a structural objecte with

var a = {};
a.b = "ab";
console.log(a.b === a['b']);

There are several good tutorials about this which guide you well through the fun with JavaScript.

There is something about the

$scope.$apply();
do...somthing...bla...bla

Go and search the web for 'angular $apply' and you will find information about the $apply function. And you should use is wisely more this way (if you are not alreay with a $apply phase).

$scope.$apply(function (){
    do...somthing...bla...bla
})

What's the scope of a variable initialized in an if statement?

Scope in python follows this order:

  • Search the local scope

  • Search the scope of any enclosing functions

  • Search the global scope

  • Search the built-ins

(source)

Notice that if and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.

Don't understand why UnboundLocalError occurs (closure)

To answer the question in your subject line,* yes, there are closures in Python, except they only apply inside a function, and also (in Python 2.x) they are read-only; you can't re-bind the name to a different object (though if the object is mutable, you can modify its contents). In Python 3.x, you can use the nonlocal keyword to modify a closure variable.

def incrementer():
    counter = 0
    def increment():
        nonlocal counter
        counter += 1
        return counter
    return increment

increment = incrementer()

increment()   # 1
increment()   # 2

* The question origially asked about closures in Python.

Static variables in C++

Static variable in a header file:

say 'common.h' has

static int zzz;

This variable 'zzz' has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h' has it's own unique object of name 'zzz'.

Static variable in a class:

Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.

$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."

So let's say 'myclass.h' has

struct myclass{
   static int zzz;        // this is only a declaration
};

and myclass.cpp has

#include "myclass.h"

int myclass::zzz = 0           // this is a definition, 
                               // should be done once and only once

and "hisclass.cpp" has

#include "myclass.h"

void f(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

and "ourclass.cpp" has

#include "myclass.h"
void g(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.

Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate

Global variables in Javascript across multiple files

You can make a json object like:

globalVariable={example_attribute:"SomeValue"}; 

in fileA.js

And access it from fileB.js like: globalVariable.example_attribute

Is it possible to declare two variables of different types in a for loop?

See "Is there a way to define variables of two types in for loop?" for another way involving nesting multiple for loops. The advantage of the other way over Georg's "struct trick" is that it (1) allows you to have a mixture of static and non-static local variables and (2) it allows you to have non-copyable variables. The downside is that it is far less readable and may be less efficient.

What is the difference between 'my' and 'our' in Perl?

Let us think what an interpreter actually is: it's a piece of code that stores values in memory and lets the instructions in a program that it interprets access those values by their names, which are specified inside these instructions. So, the big job of an interpreter is to shape the rules of how we should use the names in those instructions to access the values that the interpreter stores.

On encountering "my", the interpreter creates a lexical variable: a named value that the interpreter can access only while it executes a block, and only from within that syntactic block. On encountering "our", the interpreter makes a lexical alias of a package variable: it binds a name, which the interpreter is supposed from then on to process as a lexical variable's name, until the block is finished, to the value of the package variable with the same name.

The effect is that you can then pretend that you're using a lexical variable and bypass the rules of 'use strict' on full qualification of package variables. Since the interpreter automatically creates package variables when they are first used, the side effect of using "our" may also be that the interpreter creates a package variable as well. In this case, two things are created: a package variable, which the interpreter can access from everywhere, provided it's properly designated as requested by 'use strict' (prepended with the name of its package and two colons), and its lexical alias.

Sources:

What's the correct way to communicate between controllers in AngularJS?

Actually using emit and broadcast is inefficient because the event bubbles up and down the scope hierarchy which can easily degrade into performance bottlement for a complex application.

I would suggest to use a service. Here is how I recently implemented it in one of my projects - https://gist.github.com/3384419.

Basic idea - register a pubsub/event bus as a service. Then inject that eventbus where ever you need to subscribe or publish events/topics.

What underlies this JavaScript idiom: var self = this?

See this article on alistapart.com. (Ed: The article has been updated since originally linked)

self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).

Edit: Note that using self is now discouraged as window.self exists and has the potential to cause errors if you are not careful.

What you call the variable doesn't particularly matter. var that = this; is fine, but there's nothing magic about the name.

Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.

For example, a simple event callback:

_x000D_
_x000D_
function MyConstructor(options) {_x000D_
  let that = this;_x000D_
_x000D_
  this.someprop = options.someprop || 'defaultprop';_x000D_
_x000D_
  document.addEventListener('click', (event) => {_x000D_
    alert(that.someprop);_x000D_
  });_x000D_
}_x000D_
_x000D_
new MyConstructor({_x000D_
  someprop: "Hello World"_x000D_
});
_x000D_
_x000D_
_x000D_

Declaring an enum within a class

In general, I always put my enums in a struct. I have seen several guidelines including "prefixing".

enum Color
{
  Clr_Red,
  Clr_Yellow,
  Clr_Blue,
};

Always thought this looked more like C guidelines than C++ ones (for one because of the abbreviation and also because of the namespaces in C++).

So to limit the scope we now have two alternatives:

  • namespaces
  • structs/classes

I personally tend to use a struct because it can be used as parameters for template programming while a namespace cannot be manipulated.

Examples of manipulation include:

template <class T>
size_t number() { /**/ }

which returns the number of elements of enum inside the struct T :)

A variable modified inside a while loop is not remembered

How about a very simple method

    +call your while loop in a function 
     - set your value inside (nonsense, but shows the example)
     - return your value inside 
    +capture your value outside
    +set outside
    +display outside


    #!/bin/bash
    # set -e
    # set -u
    # No idea why you need this, not using here

    foo=0
    bar="hello"

    if [[ "$bar" == "hello" ]]
    then
        foo=1
        echo "Setting  \$foo to $foo"
    fi

    echo "Variable \$foo after if statement: $foo"

    lines="first line\nsecond line\nthird line"

    function my_while_loop
    {

    echo -e $lines | while read line
    do
        if [[ "$line" == "second line" ]]
        then
        foo=2; return 2;
        echo "Variable \$foo updated to $foo inside if inside while loop"
        fi

        echo -e $lines | while read line
do
    if [[ "$line" == "second line" ]]
    then
    foo=2;          
    echo "Variable \$foo updated to $foo inside if inside while loop"
    return 2;
    fi

    # Code below won't be executed since we returned from function in 'if' statement
    # We aready reported the $foo var beint set to 2 anyway
    echo "Value of \$foo in while loop body: $foo"

done
}

    my_while_loop; foo="$?"

    echo "Variable \$foo after while loop: $foo"


    Output:
    Setting  $foo 1
    Variable $foo after if statement: 1
    Value of $foo in while loop body: 1
    Variable $foo after while loop: 2

    bash --version

    GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
    Copyright (C) 2007 Free Software Foundation, Inc.

shared global variables in C

In the header file

header file

#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef  MAIN_FILE
int global;
#else
extern int global;
#endif
#endif

In the file with the file you want the global to live:

#define MAIN_FILE
#include "share.h"

In the other files that need the extern version:

#include "share.h"

var self = this?

Yeah, this appears to be a common standard. Some coders use self, others use me. It's used as a reference back to the "real" object as opposed to the event.

It's something that took me a little while to really get, it does look odd at first.

I usually do this right at the top of my object (excuse my demo code - it's more conceptual than anything else and isn't a lesson on excellent coding technique):

function MyObject(){
  var me = this;

  //Events
  Click = onClick; //Allows user to override onClick event with their own

  //Event Handlers
  onClick = function(args){
    me.MyProperty = args; //Reference me, referencing this refers to onClick
    ...
    //Do other stuff
  }
}

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

  1. To avoid clash with other methods/libraries in the same window,
  2. Avoid Global scope, make it local scope,
  3. To make debugging faster (local scope),
  4. JavaScript has function scope only, so it will help in compilation of codes as well.

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

What is the scope of variables in JavaScript?

A very common issue not described yet that front-end coders often run into is the scope that is visible to an inline event handler in the HTML - for example, with

<button onclick="foo()"></button>

The scope of the variables that an on* attribute can reference must be either:

  • global (working inline handlers almost always reference global variables)
  • a property of the document (eg, querySelector as a standalone variable will point to document.querySelector; rare)
  • a property of the element the handler is attached to (like above; rare)

Otherwise, you'll get a ReferenceError when the handler is invoked. So, for example, if the inline handler references a function which is defined inside window.onload or $(function() {, the reference will fail, because the inline handler may only reference variables in the global scope, and the function is not global:

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', () => {_x000D_
  function foo() {_x000D_
    console.log('foo running');_x000D_
  }_x000D_
});
_x000D_
<button onclick="foo()">click</button>
_x000D_
_x000D_
_x000D_

Properties of the document and properties of the element the handler is attached to may also be referenced as standalone variables inside inline handlers because inline handlers are invoked inside of two with blocks, one for the document, one for the element. The scope chain of variables inside these handlers is extremely unintuitive, and a working event handler will probably require a function to be global (and unnecessary global pollution should probably be avoided).

Since the scope chain inside inline handlers is so weird, and since inline handlers require global pollution to work, and since inline handlers sometimes require ugly string escaping when passing arguments, it's probably easier to avoid them. Instead, attach event handlers using Javascript (like with addEventListener), rather than with HTML markup.

_x000D_
_x000D_
function foo() {_x000D_
  console.log('foo running');_x000D_
}_x000D_
document.querySelector('.my-button').addEventListener('click', foo);
_x000D_
<button class="my-button">click</button>
_x000D_
_x000D_
_x000D_


On a different note, unlike normal <script> tags, which run on the top level, code inside ES6 modules runs in its own private scope. A variable defined at the top of a normal <script> tag is global, so you can reference it in other <script> tags, like this:

_x000D_
_x000D_
<script>_x000D_
const foo = 'foo';_x000D_
</script>_x000D_
<script>_x000D_
console.log(foo);_x000D_
</script>
_x000D_
_x000D_
_x000D_

But the top level of an ES6 module is not global. A variable declared at the top of an ES6 module will only be visible inside that module, unless the variable is explicitly exported, or unless it's assigned to a property of the global object.

_x000D_
_x000D_
<script type="module">_x000D_
const foo = 'foo';_x000D_
</script>_x000D_
<script>_x000D_
// Can't access foo here, because the other script is a module_x000D_
console.log(typeof foo);_x000D_
</script>
_x000D_
_x000D_
_x000D_

The top level of an ES6 module is similar to that of the inside of an IIFE on the top level in a normal <script>. The module can reference any variables which are global, and nothing can reference anything inside the module unless the module is explicitly designed for it.

Calling a Function defined inside another function in Javascript

You can also try this.Here you are returning the function "inside" and invoking with the second set of parenthesis.

function outer() {
  return (function inside(){
    console.log("Inside inside function");
  });
}
outer()();

Or

function outer2() {
    let inside = function inside(){
      console.log("Inside inside");
    };
    return inside;
  }
outer2()();

Giving my function access to outside variable

Global $myArr;
$myArr = array();

function someFuntion(){
    global $myArr;

    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

Be forewarned, generally people stick away from globals as it has some downsides.

You could try this

function someFuntion($myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
    return $myArr;
}
$myArr = someFunction($myArr);

That would make it so you aren't relying on Globals.

C++ "was not declared in this scope" compile error

grid is not a global, it is local to the main function. Change this:

int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int row, int column)

to this:

int nonrecursivecountcells(color grid[ROW_SIZE][COL_SIZE], int row, int column)

Basically you forgot to give that first param a name, grid will do since it matches your code.

clearInterval() not working

i think you should do:

var myInterval
on.onclick = function() {
    myInterval=setInterval(fontChange, 500);
};

off.onclick = function() {
    clearInterval(myInterval);
}; 

What's the difference between using "let" and "var"?

As I am currently trying to get an in depth understanding of JavaScript I will share my brief research which contains some of the great pieces already discussed plus some other details in a different perspective.

Understanding the difference between var and let can be easier if we understand the difference between function and block scope.

Let's consider the following cases:

(function timer() {
    for(var i = 0; i <= 5; i++) {
        setTimeout(function notime() { console.log(i); }, i * 1000);
    }
})();


   Stack            VariableEnvironment //one VariablEnvironment for timer();
                                       // when the timer is out - the value will be the same value for each call
5. [setTimeout, i]  [i=5] 
4. [setTimeout, i]  
3. [setTimeout, i]
2. [setTimeout, i]
1. [setTimeout, i]
0. [setTimeout, i]

####################    

(function timer() {
    for (let i = 0; i <= 5; i++) {
        setTimeout(function notime() { console.log(i); }, i * 1000);
    }
})();

   Stack           LexicalEnvironment - each iteration has a new lexical environment
5. [setTimeout, i]  [i=5]       
                      LexicalEnvironment 
4. [setTimeout, i]    [i=4]     
                        LexicalEnvironment 
3. [setTimeout, i]      [i=3]       
                         LexicalEnvironment 
2. [setTimeout, i]       [i=2]
                           LexicalEnvironment 
1. [setTimeout, i]         [i=1]
                             LexicalEnvironment 
0. [setTimeout, i]           [i=0]

when timer() gets called an ExecutionContext is created which will contain both the VariableEnvironment and all the LexicalEnvironments corresponding to each iteration.

And a simpler example

Function Scope

function test() {
    for(var z = 0; z < 69; z++) {
        //todo
    }
    //z is visible outside the loop
}

Block Scope

function test() {
    for(let z = 0; z < 69; z++) {
        //todo
    }
    //z is not defined :(
}

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

Why is it OK to return a 'vector' from a function?

Can we guarantee it will not die?

As long there is no reference returned, it's perfectly fine to do so. words will be moved to the variable receiving the result.

The local variable will go out of scope. after it was moved (or copied).

Using json_encode on objects in PHP (regardless of scope)

for an array of objects, I used something like this, while following the custom method for php < 5.4:

$jsArray=array();

//transaction is an array of the class transaction
//which implements the method to_json

foreach($transactions as $tran)
{
    $jsArray[]=$tran->to_json();
}

echo json_encode($jsArray);

Problems with local variable scope. How to solve it?

not Error:

JSONObject json1 = getJsonX();

Error:

JSONObject json2 = null;
if(x == y)
   json2 = getJSONX();

Error: Local variable statement defined in an enclosing scope must be final or effectively final.

But you can write:

JSONObject json2 = (x == y) ? json2 = getJSONX() : null;

Limiting number of displayed results when using ngRepeat

Slightly more "Angular way" would be to use the straightforward limitTo filter, as natively provided by Angular:

<ul class="phones">
  <li ng-repeat="phone in phones | filter:query | orderBy:orderProp | limitTo:quantity">
    {{phone.name}}
    <p>{{phone.snippet}}</p>
  </li>
</ul>
app.controller('PhoneListCtrl', function($scope, $http) {
    $http.get('phones.json').then(
      function(phones){
        $scope.phones = phones.data;
      }
    );
    $scope.orderProp = 'age';
    $scope.quantity = 5;
  }
);

PLUNKER

What is the default scope of a method in Java?

Anything defined as package private can be accessed by the class itself, other classes within the same package, but not outside of the package, and not by sub-classes.

See this page for a handy table of access level modifiers...

Nested classes' scope?

class Outer(object):
    outer_var = 1

    class Inner(object):
        @property
        def inner_var(self):
            return Outer.outer_var

This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to outer_var. (If you change what object the name Outer is bound to, then this code will use that object the next time it is executed.)

If you instead want all Inner objects to have a reference to an Outer because outer_var is really an instance attribute:

class Outer(object):
    def __init__(self):
        self.outer_var = 1

    def get_inner(self):
        return self.Inner(self)
        # "self.Inner" is because Inner is a class attribute of this class
        # "Outer.Inner" would also work, or move Inner to global scope
        # and then just use "Inner"

    class Inner(object):
        def __init__(self, outer):
            self.outer = outer

        @property
        def inner_var(self):
            return self.outer.outer_var

Note that nesting classes is somewhat uncommon in Python, and doesn't automatically imply any sort of special relationship between the classes. You're better off not nesting. (You can still set a class attribute on Outer to Inner, if you want.)

Underscore prefix for property and method names in JavaScript

JSDoc 3 allows you to annotate your functions with the @access private (previously the @private tag) which is also useful for broadcasting your intent to other developers - http://usejsdoc.org/tags-access.html

Define a global variable in a JavaScript function

Classic example:

window.foo = 'bar';

A modern, safe example following best practice by using an IIFE:

;(function (root) {
    'use strict'

    root.foo = 'bar';
)(this));

Nowadays, there's also the option of using the WebStorage API:

localStorage.foo = 42;

or

sessionStorage.bar = 21;

Performance-wise, I'm not sure whether it is noticeably slower than storing values in variables.

Widespread browser support as stated on Can I use....

When to use self over $this?

Short Answer

Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.

Full Answer

Here is an example of correct usage of $this and self for non-static and static member variables:

<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo $this->non_static_member . ' '
           . self::$static_member;
    }
}

new X();
?>

Here is an example of incorrect usage of $this and self for non-static and static member variables:

<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo self::$non_static_member . ' '
           . $this->static_member;
    }
}

new X();
?>

Here is an example of polymorphism with $this for member functions:

<?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        $this->foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?>

Here is an example of suppressing polymorphic behaviour by using self for member functions:

<?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        self::foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?>

The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.

From http://www.phpbuilder.com/board/showthread.php?t=10354489:

By http://board.phpbuilder.com/member.php?145249-laserlight

Global javascript variable inside document.ready

like this: put intro outside your document ready, Good discussion here: http://forum.jquery.com/topic/how-do-i-declare-a-global-variable-in-jquery @thecodeparadox is awesomely fast :P anyways!

 var intro;

$(document).ready(function() {



    if ($('.intro_check').is(':checked')) {
        intro = true;
        $('.intro').wrap('<div class="disabled"></div>');
    };

    $('.intro_check').change(function(){
        if(this.checked) {
            intro = false;
            $('.enabled').removeClass('enabled').addClass('disabled');
        } else {
            intro = true;
            if($('.intro').exists()) {
                $('.disabled').removeClass('disabled').addClass('enabled'); 
            } else {
                $('.intro').wrap('<div class="disabled"></div>');
            }
        }
    });
});

Is there a reason for C#'s reuse of the variable in a foreach?

In C# 5.0, this problem is fixed and you can close over loop variables and get the results you expect.

The language specification says:

8.8.4 The foreach statement

(...)

A foreach statement of the form

foreach (V v in x) embedded-statement

is then expanded to:

{
  E e = ((C)(x)).GetEnumerator();
  try {
      while (e.MoveNext()) {
          V v = (V)(T)e.Current;
          embedded-statement
      }
  }
  finally {
      … // Dispose e
  }
}

(...)

The placement of v inside the while loop is important for how it is captured by any anonymous function occurring in the embedded-statement. For example:

int[] values = { 7, 9, 13 };
Action f = null;
foreach (var value in values)
{
    if (f == null) f = () => Console.WriteLine("First value: " + value);
}
f();

If v was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value, 13, which is what the invocation of f would print. Instead, because each iteration has its own variable v, the one captured by f in the first iteration will continue to hold the value 7, which is what will be printed. (Note: earlier versions of C# declared v outside of the while loop.)

Using global variables in a function

You're not actually storing the global in a local variable, just creating a local reference to the same object that your original global reference refers to. Remember that pretty much everything in Python is a name referring to an object, and nothing gets copied in usual operation.

If you didn't have to explicitly specify when an identifier was to refer to a predefined global, then you'd presumably have to explicitly specify when an identifier is a new local variable instead (for example, with something like the 'var' command seen in JavaScript). Since local variables are more common than global variables in any serious and non-trivial system, Python's system makes more sense in most cases.

You could have a language which attempted to guess, using a global variable if it existed or creating a local variable if it didn't. However, that would be very error-prone. For example, importing another module could inadvertently introduce a global variable by that name, changing the behaviour of your program.

How do I access previous promise results in a .then() chain?

Explicit pass-through

Similar to nesting the callbacks, this technique relies on closures. Yet, the chain stays flat - instead of passing only the latest result, some state object is passed for every step. These state objects accumulate the results of the previous actions, handing down all values that will be needed later again plus the result of the current task.

function getExample() {
    return promiseA(…).then(function(resultA) {
        // some processing
        return promiseB(…).then(b => [resultA, b]); // function(b) { return [resultA, b] }
    }).then(function([resultA, resultB]) {
        // more processing
        return // something using both resultA and resultB
    });
}

Here, that little arrow b => [resultA, b] is the function that closes over resultA, and passes an array of both results to the next step. Which uses parameter destructuring syntax to break it up in single variables again.

Before destructuring became available with ES6, a nifty helper method called .spread() was pro­vi­ded by many promise libraries (Q, Bluebird, when, …). It takes a function with multiple parameters - one for each array element - to be used as .spread(function(resultA, resultB) { ….

Of course, that closure needed here can be further simplified by some helper functions, e.g.

function addTo(x) {
    // imagine complex `arguments` fiddling or anything that helps usability
    // but you get the idea with this simple one:
    return res => [x, res];
}

…
return promiseB(…).then(addTo(resultA));

Alternatively, you can employ Promise.all to produce the promise for the array:

function getExample() {
    return promiseA(…).then(function(resultA) {
        // some processing
        return Promise.all([resultA, promiseB(…)]); // resultA will implicitly be wrapped
                                                    // as if passed to Promise.resolve()
    }).then(function([resultA, resultB]) {
        // more processing
        return // something using both resultA and resultB
    });
}

And you might not only use arrays, but arbitrarily complex objects. For example, with _.extend or Object.assign in a different helper function:

function augment(obj, name) {
    return function (res) { var r = Object.assign({}, obj); r[name] = res; return r; };
}

function getExample() {
    return promiseA(…).then(function(resultA) {
        // some processing
        return promiseB(…).then(augment({resultA}, "resultB"));
    }).then(function(obj) {
        // more processing
        return // something using both obj.resultA and obj.resultB
    });
}

While this pattern guarantees a flat chain and explicit state objects can improve clarity, it will become tedious for a long chain. Especially when you need the state only sporadically, you still have to pass it through every step. With this fixed interface, the single callbacks in the chain are rather tightly coupled and inflexible to change. It makes factoring out single steps harder, and callbacks cannot be supplied directly from other modules - they always need to be wrapped in boilerplate code that cares about the state. Abstract helper functions like the above can ease the pain a bit, but it will always be present.

Short description of the scoping rules?

The scoping rules for Python 2.x have been outlined already in other answers. The only thing I would add is that in Python 3.0, there is also the concept of a non-local scope (indicated by the 'nonlocal' keyword). This allows you to access outer scopes directly, and opens up the ability to do some neat tricks, including lexical closures (without ugly hacks involving mutable objects).

EDIT: Here's the PEP with more information on this.

How to remove elements/nodes from angular.js array

My solution was quite straight forward

app.controller('TaskController', function($scope) {
 $scope.items = tasks;

    $scope.addTask = function(task) {
        task.created = Date.now();
        $scope.items.push(task);
        console.log($scope.items);
    };

    $scope.removeItem = function(item) {
        // item is the index value which is obtained using $index in ng-repeat
        $scope.items.splice(item, 1);
    }
});

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

How do JavaScript closures work?

Also... Perhaps we should cut your 27-year-old friend a little slack, because the entire concept of "closures" really is(!) ... voodoo!

By that I mean: (a) you do not, intuitively, expect it ...AND... (b) when someone takes the time to explain it to you, you certainly do not expect it to work!

Intuition tells you that "this must be nonsense... surely it must result in some kind of syntax-error or something!" How on earth(!) could you, in effect, "pull a function from 'the middle of' wherever-it's-at," such that you could [still!] actually have read/write access to the context of "wherever-it-was-at?!"

When you finally realize that such a thing is possible, then ... sure ... anyone's after-the-fact reaction would be: "whoa-a-a-a(!)... kew-el-l-l-l...(!!!)"

But there will be a "big counter-intuitive hurdle" to overcome, first. Intuition gives you plenty of utterly-plausible expectations that such a thing would be "of course, absolutely nonsensical and therefore quite impossible."

Like I said: "it's voodoo."

Passing a variable from one php include file to another: global vs. not

This is all you have to do:

In front.inc

global $name;
$name = 'james';

Can I access variables from another file?

This is quite an old question, but I'm going to provide a modern solution that's been available since ES6 - export and import:

In first.js:

let colorcodes = <whatever>;
export default colorcodes //or a different export statement

In second.js:

import colorcodes from <path-to-first.js> //or a matching import statement

How to use Global Variables in C#?

First examine if you really need a global variable instead using it blatantly without consideration to your software architecture.

Let's assuming it passes the test. Depending on usage, Globals can be hard to debug with race conditions and many other "bad things", it's best to approach them from an angle where you're prepared to handle such bad things. So,

  1. Wrap all such Global variables into a single static class (for manageability).
  2. Have Properties instead of fields(='variables'). This way you have some mechanisms to address any issues with concurrent writes to Globals in the future.

The basic outline for such a class would be:

public class Globals
{
    private static bool _expired;
    public static bool Expired 
    {
        get
        {
            // Reads are usually simple
            return _expired;
        }
        set
        {
            // You can add logic here for race conditions,
            // or other measurements
            _expired = value;
        }
    }
    // Perhaps extend this to have Read-Modify-Write static methods
    // for data integrity during concurrency? Situational.
}

Usage from other classes (within same namespace)

// Read
bool areWeAlive = Globals.Expired;

// Write
// past deadline
Globals.Expired = true;

JavaScript closures vs. anonymous functions

Editor's Note: All functions in JavaScript are closures as explained in this post. However we are only interested in identifying a subset of these functions which are interesting from a theoretical point of view. Henceforth any reference to the word closure will refer to this subset of functions unless otherwise stated.

A simple explanation for closures:

  1. Take a function. Let's call it F.
  2. List all the variables of F.
  3. The variables may be of two types:
    1. Local variables (bound variables)
    2. Non-local variables (free variables)
  4. If F has no free variables then it cannot be a closure.
  5. If F has any free variables (which are defined in a parent scope of F) then:
    1. There must be only one parent scope of F to which a free variable is bound.
    2. If F is referenced from outside that parent scope, then it becomes a closure for that free variable.
    3. That free variable is called an upvalue of the closure F.

Now let's use this to figure out who uses closures and who doesn't (for the sake of explanation I have named the functions):

Case 1: Your Friend's Program

for (var i = 0; i < 10; i++) {
    (function f() {
        var i2 = i;
        setTimeout(function g() {
            console.log(i2);
        }, 1000);
    })();
}

In the above program there are two functions: f and g. Let's see if they are closures:

For f:

  1. List the variables:
    1. i2 is a local variable.
    2. i is a free variable.
    3. setTimeout is a free variable.
    4. g is a local variable.
    5. console is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. i is bound to the global scope.
    2. setTimeout is bound to the global scope.
    3. console is bound to the global scope.
  3. In which scope is the function referenced? The global scope.
    1. Hence i is not closed over by f.
    2. Hence setTimeout is not closed over by f.
    3. Hence console is not closed over by f.

Thus the function f is not a closure.

For g:

  1. List the variables:
    1. console is a free variable.
    2. i2 is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
    2. i2 is bound to the scope of f.
  3. In which scope is the function referenced? The scope of setTimeout.
    1. Hence console is not closed over by g.
    2. Hence i2 is closed over by g.

Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.

Bad for you: Your friend is using a closure. The inner function is a closure.

Case 2: Your Program

for (var i = 0; i < 10; i++) {
    setTimeout((function f(i2) {
        return function g() {
            console.log(i2);
        };
    })(i), 1000);
}

In the above program there are two functions: f and g. Let's see if they are closures:

For f:

  1. List the variables:
    1. i2 is a local variable.
    2. g is a local variable.
    3. console is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
  3. In which scope is the function referenced? The global scope.
    1. Hence console is not closed over by f.

Thus the function f is not a closure.

For g:

  1. List the variables:
    1. console is a free variable.
    2. i2 is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
    2. i2 is bound to the scope of f.
  3. In which scope is the function referenced? The scope of setTimeout.
    1. Hence console is not closed over by g.
    2. Hence i2 is closed over by g.

Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.

Good for you: You are using a closure. The inner function is a closure.

So both you and your friend are using closures. Stop arguing. I hope I cleared the concept of closures and how to identify them for the both of you.

Edit: A simple explanation as to why are all functions closures (credits @Peter):

First let's consider the following program (it's the control):

_x000D_
_x000D_
lexicalScope();_x000D_
_x000D_
function lexicalScope() {_x000D_
    var message = "This is the control. You should be able to see this message being alerted.";_x000D_
_x000D_
    regularFunction();_x000D_
_x000D_
    function regularFunction() {_x000D_
        alert(eval("message"));_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

  1. We know that both lexicalScope and regularFunction aren't closures from the above definition.
  2. When we execute the program we expect message to be alerted because regularFunction is not a closure (i.e. it has access to all the variables in its parent scope - including message).
  3. When we execute the program we observe that message is indeed alerted.

Next let's consider the following program (it's the alternative):

_x000D_
_x000D_
var closureFunction = lexicalScope();_x000D_
_x000D_
closureFunction();_x000D_
_x000D_
function lexicalScope() {_x000D_
    var message = "This is the alternative. If you see this message being alerted then in means that every function in JavaScript is a closure.";_x000D_
_x000D_
    return function closureFunction() {_x000D_
        alert(eval("message"));_x000D_
    };_x000D_
}
_x000D_
_x000D_
_x000D_

  1. We know that only closureFunction is a closure from the above definition.
  2. When we execute the program we expect message not to be alerted because closureFunction is a closure (i.e. it only has access to all its non-local variables at the time the function is created (see this answer) - this does not include message).
  3. When we execute the program we observe that message is actually being alerted.

What do we infer from this?

  1. JavaScript interpreters do not treat closures differently from the way they treat other functions.
  2. Every function carries its scope chain along with it. Closures don't have a separate referencing environment.
  3. A closure is just like every other function. We just call them closures when they are referenced in a scope outside the scope to which they belong because this is an interesting case.

Java, "Variable name" cannot be resolved to a variable

I've noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:

String cannot be resolved to a variable

With this Java code:

if (true)
    String my_variable = "somevalue";
    System.out.println("foobar");

You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?

Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.

If you put braces around the conditional block like this:

if (true){
    String my_variable = "somevalue"; }
    System.out.println("foobar");

Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.

How do I pass the this context to a function?

Javascripts .call() and .apply() methods allow you to set the context for a function.

var myfunc = function(){
    alert(this.name);
};

var obj_a = {
    name:  "FOO"
};

var obj_b = {
    name:  "BAR!!"
};

Now you can call:

myfunc.call(obj_a);

Which would alert FOO. The other way around, passing obj_b would alert BAR!!. The difference between .call() and .apply() is that .call() takes a comma separated list if you're passing arguments to your function and .apply() needs an array.

myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);

Therefore, you can easily write a function hook by using the apply() method. For instance, we want to add a feature to jQuerys .css() method. We can store the original function reference, overwrite the function with custom code and call the stored function.

var _css = $.fn.css;
$.fn.css = function(){
   alert('hooked!');
   _css.apply(this, arguments);
};

Since the magic arguments object is an array like object, we can just pass it to apply(). That way we guarantee, that all parameters are passed through to the original function.

How do I declare a global variable in VBA?

Create a public integer in the General Declaration.

Then in your function you can increase its value each time. See example (function to save attachements of an email as CSV).

Public Numerator As Integer

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim FileName As String

saveFolder = "c:\temp\"

     For Each objAtt In itm.Attachments
            FileName = objAtt.DisplayName & "_" & Numerator & "_" & Format(Now, "yyyy-mm-dd H-mm-ss") & ".CSV"
                      objAtt.SaveAsFile saveFolder & "\" & FileName
                      Numerator = Numerator + 1

          Set objAtt = Nothing
     Next
End Sub

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

The first function in an m-file (i.e. the main function), is invoked when that m-file is called. It is not required that the main function have the same name as the m-file, but for clarity it should. When the function and file name differ, the file name must be used to call the main function.

All subsequent functions in the m-file, called local functions (or "subfunctions" in the older terminology), can only be called by the main function and other local functions in that m-file. Functions in other m-files can not call them. Starting in R2016b, you can add local functions to scripts as well, although the scoping behavior is still the same (i.e. they can only be called from within the script).

In addition, you can also declare functions within other functions. These are called nested functions, and these can only be called from within the function they are nested. They can also have access to variables in functions in which they are nested, which makes them quite useful albeit slightly tricky to work with.

More food for thought...

There are some ways around the normal function scoping behavior outlined above, such as passing function handles as output arguments as mentioned in the answers from SCFrench and Jonas (which, starting in R2013b, is facilitated by the localfunctions function). However, I wouldn't suggest making it a habit of resorting to such tricks, as there are likely much better options for organizing your functions and files.

For example, let's say you have a main function A in an m-file A.m, along with local functions D, E, and F. Now let's say you have two other related functions B and C in m-files B.m and C.m, respectively, that you also want to be able to call D, E, and F. Here are some options you have:

  • Put D, E, and F each in their own separate m-files, allowing any other function to call them. The downside is that the scope of these functions is large and isn't restricted to just A, B, and C, but the upside is that this is quite simple.

  • Create a defineMyFunctions m-file (like in Jonas' example) with D, E, and F as local functions and a main function that simply returns function handles to them. This allows you to keep D, E, and F in the same file, but it doesn't do anything regarding the scope of these functions since any function that can call defineMyFunctions can invoke them. You also then have to worry about passing the function handles around as arguments to make sure you have them where you need them.

  • Copy D, E and F into B.m and C.m as local functions. This limits the scope of their usage to just A, B, and C, but makes updating and maintenance of your code a nightmare because you have three copies of the same code in different places.

  • Use private functions! If you have A, B, and C in the same directory, you can create a subdirectory called private and place D, E, and F in there, each as a separate m-file. This limits their scope so they can only be called by functions in the directory immediately above (i.e. A, B, and C) and keeps them together in the same place (but still different m-files):

    myDirectory/
        A.m
        B.m
        C.m
        private/
            D.m
            E.m
            F.m
    

All this goes somewhat outside the scope of your question, and is probably more detail than you need, but I thought it might be good to touch upon the more general concern of organizing all of your m-files. ;)

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the + operator fails for strings in EL (which is correct), then just do:

<c:out value="abc${test}" />

Or if abc is to obtained from another scoped variable named ${resp}, then do:

<c:out value="${resp}${test}" />

How to create module-wide variables in Python?

Here is what is going on.

First, the only global variables Python really has are module-scoped variables. You cannot make a variable that is truly global; all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.)

All you have to do to make a module-global variable is just assign to a name.

Imagine a file called foo.py, containing this single line:

X = 1

Now imagine you import it.

import foo
print(foo.X)  # prints 1

However, let's suppose you want to use one of your module-scope variables as a global inside a function, as in your example. Python's default is to assume that function variables are local. You simply add a global declaration in your function, before you try to use the global.

def initDB(name):
    global __DBNAME__  # add this line!
    if __DBNAME__ is None: # see notes below; explicit test for None
        __DBNAME__ = name
    else:
        raise RuntimeError("Database name has already been set.")

By the way, for this example, the simple if not __DBNAME__ test is adequate, because any string value other than an empty string will evaluate true, so any actual database name will evaluate true. But for variables that might contain a number value that might be 0, you can't just say if not variablename; in that case, you should explicitly test for None using the is operator. I modified the example to add an explicit None test. The explicit test for None is never wrong, so I default to using it.

Finally, as others have noted on this page, two leading underscores signals to Python that you want the variable to be "private" to the module. If you ever do an import * from mymodule, Python will not import names with two leading underscores into your name space. But if you just do a simple import mymodule and then say dir(mymodule) you will see the "private" variables in the list, and if you explicitly refer to mymodule.__DBNAME__ Python won't care, it will just let you refer to it. The double leading underscores are a major clue to users of your module that you don't want them rebinding that name to some value of their own.

It is considered best practice in Python not to do import *, but to minimize the coupling and maximize explicitness by either using mymodule.something or by explicitly doing an import like from mymodule import something.

EDIT: If, for some reason, you need to do something like this in a very old version of Python that doesn't have the global keyword, there is an easy workaround. Instead of setting a module global variable directly, use a mutable type at the module global level, and store your values inside it.

In your functions, the global variable name will be read-only; you won't be able to rebind the actual global variable name. (If you assign to that variable name inside your function it will only affect the local variable name inside the function.) But you can use that local variable name to access the actual global object, and store data inside it.

You can use a list but your code will be ugly:

__DBNAME__ = [None] # use length-1 list as a mutable

# later, in code:  
if __DBNAME__[0] is None:
    __DBNAME__[0] = name

A dict is better. But the most convenient is a class instance, and you can just use a trivial class:

class Box:
    pass

__m = Box()  # m will contain all module-level values
__m.dbname = None  # database name global in module

# later, in code:
if __m.dbname is None:
    __m.dbname = name

(You don't really need to capitalize the database name variable.)

I like the syntactic sugar of just using __m.dbname rather than __m["DBNAME"]; it seems the most convenient solution in my opinion. But the dict solution works fine also.

With a dict you can use any hashable value as a key, but when you are happy with names that are valid identifiers, you can use a trivial class like Box in the above.

VB.Net Properties - Public Get, Private Set

If you are using VS2010 or later it is even easier than that

Public Property Name as String

You get the private properties and Get/Set completely for free!

see this blog post: Scott Gu's Blog

How to force addition instead of concatenation in javascript

Your code concatenates three strings, then converts the result to a number.

You need to convert each variable to a number by calling parseFloat() around each one.

total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

For some reason, the connection to the server was lost. It could be that the server explicitly closed the connection, or a bug on the server caused it to be closed unexpectedly. Or something between the client and the server (a switch or router) dropped the connection.

It might be server code that caused the problem, and it might not be. If you have access to the server code, you can put some debugging in there to tell you when client connections are closed. That might give you some indication of when and why connections are being dropped.

On the client, you have to write your code to take into account the possibility of the server failing at any time. That's just the way it is: network connections are inherently unreliable.

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

I figured it out. I had an error in my cloud formation template that was creating the EC2 instances. As a result, the EC2 instances that were trying to access the above code deploy buckets, were in different regions (not us-west-2). It seems like the access policies on the buckets (owned by Amazon) only allow access from the region they belong in. When I fixed the error in my template (it was wrong parameter map), the error disappeared

Can I use jQuery to check whether at least one checkbox is checked?

$('#frmTest').submit(function(){
    if(!$('#frmTest input[type="checkbox"]').is(':checked')){
      alert("Please check at least one.");
      return false;
    }
});

is(':checked') will return true if at least one or more of the checkboxes are checked.

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

Add row to query result using select

You use it like this:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

Use UNION ALL to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION.

Passing HTML input value as a JavaScript Function Parameter

   <form action="" onsubmit="additon()" name="form1" id="form1">
      a: <input type="number" name="a" id="a"><br>
      b: <input type="number" name="b" id="b"><br>
      <input type="submit" value="Submit" name="submit">
   </form>
  <script>
      function additon() 
      {
           var a = document.getElementById('a').value;
           var b = document.getElementById('b').value;
           var sum = parseInt(a) + parseInt(b);
           return sum;
      }
  </script>

Apk location in New Android Studio

I am using Android Studio 3.0 canary 6.

To build apk,

Click to Build->Build APK(s).

After your apk is build, Go to:

C:\Users\your-pc-name\AndroidStudioProjects\your-app-name\app\build\outputs\apk\debug

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

If the issue is a missing intermediate certificate, you can enable Oracle JRE to automatically download the missing intermediate certificate as explained in this answer.

Just set the Java system property -Dcom.sun.security.enableAIAcaIssuers=true

For this to work the server's certificate must provide the URI to the intermediate certificate (the certificate's issuer). As far as I can tell, this is what browsers do as well and should be just as secure - I'm not a security expert though.

Edit: If I recall correctly, this seems to work at least with Java 8 and is documented here for Java 9.

On localhost, how do I pick a free port number?

Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with getsockname() right after bind().

How to make an AlertDialog in Flutter?

showAlertDialog(BuildContext context, String message, String heading,
      String buttonAcceptTitle, String buttonCancelTitle) {
    // set up the buttons
    Widget cancelButton = FlatButton(
      child: Text(buttonCancelTitle),
      onPressed: () {},
    );
    Widget continueButton = FlatButton(
      child: Text(buttonAcceptTitle),
      onPressed: () {

      },
    );

    // set up the AlertDialog
    AlertDialog alert = AlertDialog(
      title: Text(heading),
      content: Text(message),
      actions: [
        cancelButton,
        continueButton,
      ],
    );

    // show the dialog
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

called like:

showAlertDialog(context, 'Are you sure you want to delete?', "AppName" , "Ok", "Cancel");

There are No resources that can be added or removed from the server

I encountered this error even though the Project Facets were set appropriately. The problem was that the "Runtime Environment" property was not set on the server:

Empty Runtime Environment for Eclipse Tomcat

It simply needed to be set to the appropriate Runtime:

Runtime Environment for Eclipse Tomcat

Is there any use for unique_ptr with array?

Some people do not have the luxury of using std::vector, even with allocators. Some people need a dynamically sized array, so std::array is out. And some people get their arrays from other code that is known to return an array; and that code isn't going to be rewritten to return a vector or something.

By allowing unique_ptr<T[]>, you service those needs.

In short, you use unique_ptr<T[]> when you need to. When the alternatives simply aren't going to work for you. It's a tool of last resort.

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

Replace None with NaN in pandas dataframe

You can use DataFrame.fillna or Series.fillna which will replace the Python object None, not the string 'None'.

import pandas as pd
import numpy as np

For dataframe:

df = df.fillna(value=np.nan)

For column or series:

df.mycol.fillna(value=np.nan, inplace=True)

How to make Excel VBA variables available to multiple macros?

You may consider declaring the variables with moudule level scope. Module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules

For details on Scope of variables refer this link

Please copy the below code into any module, save the workbook and then run the code.

Here is what code does

  • The sample subroutine sets the folder path & later the file path. Kindly set them accordingly before you run the code.

  • I have added a function IsWorkBookOpen to check if workbook is already then set the workbook variable the workbook name else open the workbook which will be assigned to workbook variable accordingly.

Dim wbA As Workbook
Dim wbB As Workbook

Sub MySubRoutine()
    Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String

    folderPath = ThisWorkbook.Path & "\"
    fileNm1 = "file1.xlsx"
    fileNm2 = "file2.xlsx"

    filePath1 = folderPath & fileNm1
    filePath2 = folderPath & fileNm2

    If IsWorkBookOpen(filePath1) Then
        Set wbA = Workbooks(fileNm1)
    Else
        Set wbA = Workbooks.Open(filePath1)
    End If


    If IsWorkBookOpen(filePath2) Then
        Set wbB = Workbooks.Open(fileNm2)
    Else
        Set wbB = Workbooks.Open(filePath2)
    End If


    ' your code here
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0: IsWorkBookOpen = False
    Case 70: IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Using Prompt to select the file use below code.

Dim wbA As Workbook
Dim wbB As Workbook

Sub MySubRoutine()
    Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String

    Dim filePath As String
    cmdBrowse_Click filePath, 1

    filePath1 = filePath

    'reset the variable
    filePath = vbNullString

    cmdBrowse_Click filePath, 2
    filePath2 = filePath

   fileNm1 = GetFileName(filePath1, "\")
   fileNm2 = GetFileName(filePath2, "\")

    If IsWorkBookOpen(filePath1) Then
        Set wbA = Workbooks(fileNm1)
    Else
        Set wbA = Workbooks.Open(filePath1)
    End If


    If IsWorkBookOpen(filePath2) Then
        Set wbB = Workbooks.Open(fileNm2)
    Else
        Set wbB = Workbooks.Open(filePath2)
    End If


    ' your code here
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0: IsWorkBookOpen = False
    Case 70: IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Private Sub cmdBrowse_Click(ByRef filePath As String, num As Integer)

    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Select workbook " & num
    fd.InitialView = msoFileDialogViewSmallIcons

    Dim FileChosen As Integer

    FileChosen = fd.Show

    fd.Filters.Clear
    fd.Filters.Add "Excel macros", "*.xlsx"


    fd.FilterIndex = 1



    If FileChosen <> -1 Then
        MsgBox "You chose cancel"
        filePath = ""
    Else
        filePath = fd.SelectedItems(1)
    End If

End Sub

Function GetFileName(fullName As String, pathSeparator As String) As String

    Dim i As Integer
    Dim iFNLenght As Integer
    iFNLenght = Len(fullName)

    For i = iFNLenght To 1 Step -1
        If Mid(fullName, i, 1) = pathSeparator Then Exit For
    Next

    GetFileName = Right(fullName, iFNLenght - i)

End Function

remove item from stored array in angular 2

This can be achieved as follows:

this.itemArr = this.itemArr.filter( h => h.id !== ID);

C++ string to double conversion

You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.

With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)

#include <stdlib.h>

int main()
{
    string word;  
    openfile >> word;
    double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
                                     previously (the function requires it)*/
    return 0;
}

find all unchecked checkbox in jquery

You can use like this :

$(":checkbox:not(:checked)")

Google Maps v3 - limit viewable area and zoom level

This can be used to re-center the map to a specific location. Which is what I needed.

    var MapBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(35.676263, 13.949096),
    new google.maps.LatLng(36.204391, 14.89038));

    google.maps.event.addListener(GoogleMap, 'dragend', function ()
    {
        if (MapBounds.contains(GoogleMap.getCenter()))
        {
            return;
        }
        else
        {
            GoogleMap.setCenter(new google.maps.LatLng(35.920242, 14.428825));
        }
    });

How to change the remote a branch is tracking?

Based on what I understand from the latest git documentation, the synopsis is:

git branch -u upstream-branch local-branch
git branch --set-upstream-to=upstream-branch local-branch

This usage seems to be a bit different than urschrei's answer, as in his the synopsis is:

git branch local-branch -u upstream-branch 
git branch local-branch --set-upstream-to=upstream-branch 

I'm guessing they changed the documentation again?

Java 8: merge lists with stream API

I think flatMap() is what you're looking for.

For example:

 List<AClass> allTheObjects = map.values()
         .stream()
         .flatMap(listContainer -> listContainer.lst.stream())
         .collect(Collectors.toList());

How do I get a human-readable file size in bytes abbreviation using .NET?

Here's a concise answer that determines the unit automatically.

public static string ToBytesCount(this long bytes)
{
    int unit = 1024;
    string unitStr = "b";
    if (bytes < unit) return string.Format("{0} {1}", bytes, unitStr);
    else unitStr = unitStr.ToUpper();
    int exp = (int)(Math.Log(bytes) / Math.Log(unit));
    return string.Format("{0:##.##} {1}{2}", bytes / Math.Pow(unit, exp), "KMGTPEZY"[exp - 1], unitStr);
}

"b" is for bit, "B" is for Byte and "KMGTPEZY" are respectively for kilo, mega, giga, tera, peta, exa, zetta and yotta

One can expand it to take ISO/IEC80000 into account:

public static string ToBytesCount(this long bytes, bool isISO = true)
{
    int unit = 1024;
    string unitStr = "b";
    if (!isISO) unit = 1000;
    if (bytes < unit) return string.Format("{0} {1}", bytes, unitStr);
    else unitStr = unitStr.ToUpper();
    if (isISO) unitStr = "i" + unitStr;
    int exp = (int)(Math.Log(bytes) / Math.Log(unit));
    return string.Format("{0:##.##} {1}{2}", bytes / Math.Pow(unit, exp), "KMGTPEZY"[exp - 1], unitStr);
}

org.hibernate.MappingException: Unknown entity

use below line of code in the case of spring boot applications.

@EntityScan(basePackageClasses=YourClassName.class)

JUnit 5: How to assert an exception is thrown?

Now Junit5 provides a way to assert the exceptions

You can test both general exceptions and customized exceptions

A general exception scenario:

ExpectGeneralException.java

public void validateParameters(Integer param ) {
    if (param == null) {
        throw new NullPointerException("Null parameters are not allowed");
    }
}

ExpectGeneralExceptionTest.java

@Test
@DisplayName("Test assert NullPointerException")
void testGeneralException(TestInfo testInfo) {
    final ExpectGeneralException generalEx = new ExpectGeneralException();

     NullPointerException exception = assertThrows(NullPointerException.class, () -> {
            generalEx.validateParameters(null);
        });
    assertEquals("Null parameters are not allowed", exception.getMessage());
}

You can find a sample to test CustomException here : assert exception code sample

ExpectCustomException.java

public String constructErrorMessage(String... args) throws InvalidParameterCountException {
    if(args.length!=3) {
        throw new InvalidParameterCountException("Invalid parametercount: expected=3, passed="+args.length);
    }else {
        String message = "";
        for(String arg: args) {
            message += arg;
        }
        return message;
    }
}

ExpectCustomExceptionTest.java

@Test
@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
    final ExpectCustomException expectEx = new ExpectCustomException();

     InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
            expectEx.constructErrorMessage("sample ","error");
        });
    assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
}

Count the number of occurrences of a character in a string in Javascript

This below is the simplest logic, which is very easy to understand

  //Demo string with repeat char 
  let str = "Coffee"
  //Splitted the str into an char array for looping
  let strArr = str.split("")
  //This below is the final object which holds the result
  let obj = {};
  //This loop will count char (You can also use traditional one for loop)
  strArr.forEach((value,index)=>{
      //If the char exists in the object it will simple increase its value
      if(obj[value] != undefined)
      {
          obj[value] = parseInt(obj[value]) + 1;
      }//else it will add the new one with initializing 1
      else{
          obj[value] =1;
      }      
  });

  console.log("Char with Count:",JSON.stringify(obj)); //Char with Count:{"C":1,"o":1,"f":2,"e":2}

What is 'PermSize' in Java?

The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.

You seem to not be depending on "@angular/core". This is an error

I had the same issue and along with removing the node_modules and reinstalling I needed to remove package-lock.json first.

Regular expression which matches a pattern, or is an empty string

To match pattern or an empty string, use

^$|pattern

Explanation

  • ^ and $ are the beginning and end of the string anchors respectively.
  • | is used to denote alternates, e.g. this|that.

References


On \b

\b in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.

That is, \b is located:

  • Between consecutive \w and \W (either order):
    • i.e. between a word character and a non-word character
  • Between ^ and \w
    • i.e. at the beginning of the string if it starts with \w
  • Between \w and $
    • i.e. at the end of the string if it ends with \w

References


On using regex to match e-mail addresses

This is not trivial depending on specification.

Related questions

How to start Apache and MySQL automatically when Windows 8 comes up

Apache

  1. Run cmd as administrator
  2. Go to the Apache bin directory, for example, C:\xampp\apache\bin
  3. Run: httpd.exe -k install more information
  4. Restart the computer, or run the service manually (from services.msc)

MySQL

  1. Run cmd as administrator
  2. Go to the MySQL bin directory, for example, C:\xampp\mysql\bin
  3. Run: mysqld.exe --install more information
  4. Restart the computer, or run the service manually (from services.msc)

Change arrow colors in Bootstraps carousel

for bootstrap-3 one can use:

.carousel-control span.glyphicon {
    color: red;
}

How to check for empty value in Javascript?

In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:

const isEmptyValue = (value) => {
    if (value === '' || value === null || value === undefined) {
        return true
    } else {
        return false
    }
}

SQL ROWNUM how to return rows between a specific range

I was looking for a solution for this and found this great article explaining the solution Relevant excerpt

My all-time-favorite use of ROWNUM is pagination. In this case, I use ROWNUM to get rows N through M of a result set. The general form is as follows:

select * enter code here
  from ( select /*+ FIRST_ROWS(n) */ 
  a.*, ROWNUM rnum 
      from ( your_query_goes_here, 
      with order by ) a 
      where ROWNUM <= 
      :MAX_ROW_TO_FETCH ) 
where rnum  >= :MIN_ROW_TO_FETCH;

Now with a real example (gets rows 148, 149 and 150):

select *
    from
  (select a.*, rownum rnum
     from
  (select id, data
     from t
   order by id, rowid) a
   where rownum <= 150
  )
   where rnum >= 148;

Is it possible to display my iPhone on my computer monitor?

Many screencasts displaying an iPhone application simply use the iPhone Simulator, which is one option.

You can also take screenshots on the phone by quickly pressing the menu and the power/sleep button at the same time. The image is then saved to your "Camera Roll" and easily transferable to the computer

The other way is only possible with a Jailbroken phone - Veency is a VNC server for the iPhone, which you can connect to with a regular VNC client.

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

How can I install MacVim on OS X?

  • Step 1. Install homebrew from here: http://brew.sh
  • Step 1.1. Run export PATH=/usr/local/bin:$PATH
  • Step 2. Run brew update
  • Step 3. Run brew install vim && brew install macvim
  • Step 4. Run brew link macvim

You now have the latest versions of vim and macvim managed by brew. Run brew update && brew upgrade every once in a while to upgrade them.

This includes the installation of the CLI mvim and the mac application (which both point to the same thing).

I use this setup and it works like a charm. Brew even takes care of installing vim with the preferable options.

CSS - Overflow: Scroll; - Always show vertical scroll bar?

This will make the scroll bars always display when there is content within windows that must be scrolled to access, it applies to all windows and all apps on the Mac:

Launch System Preferences from the ? Apple menu Click on the “General” settings panel Look for ‘Show scroll bars’ and select the radiobox next to “Always” Close out of System Preferences when finished

Meaning of "n:m" and "1:n" in database design

What does the letter 'N' on a relationship line in an Entity Relationship diagram mean? Any number

M:N

M - ordinality - describes the minimum (ordinal vs mandatory)

N - cardinality - describes the miximum

1:N (n=0,1,2,3...) one to zero or more

M:N (m and n=0,1,2,3...) zero or more to zero or more (many to many)

1:1 one to one

Find more here: https://www.smartdraw.com/entity-relationship-diagram/

execute function after complete page load

this may work for you :

document.addEventListener('DOMContentLoaded', function() {
   // your code here
}, false);

or if your comfort with jquery,

$(document).ready(function(){
// your code
});

$(document).ready() fires on DOMContentLoaded, but this event is not being fired consistently among browsers. This is why jQuery will most probably implement some heavy workarounds to support all the browsers. And this will make it very difficult to "exactly" simulate the behavior using plain Javascript (but not impossible of course).

as Jeffrey Sweeney and J Torres suggested, i think its better to have a setTimeout function, before firing the function like below :

setTimeout(function(){
 //your code here
}, 3000);

Count number of objects in list

Advice for R newcomers like me : beware, the following is a list of a single object :

> mylist <- list (1:10)
> length (mylist)
[1] 1

In such a case you are not looking for the length of the list, but of its first element :

> length (mylist[[1]])
[1] 10

This is a "true" list :

> mylist <- list(1:10, rnorm(25), letters[1:3])
> length (mylist)
[1] 3

Also, it seems that R considers a data.frame as a list :

> df <- data.frame (matrix(0, ncol = 30, nrow = 2))
> typeof (df)
[1] "list"

In such a case you may be interested in ncol() and nrow() rather than length() :

> ncol (df)
[1] 30
> nrow (df)
[1] 2

Though length() will also work (but it's a trick when your data.frame has only one column) :

> length (df)
[1] 30
> length (df[[1]])
[1] 2

hidden field in php

Yes, you can access it through GET and POST (trying this simple task would have made you aware of that).

Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.

How to use LocalBroadcastManager?

In Eclipse, eventually I had to add Compatibility/Support Library by right-clicking on my project and selecting:

Android Tools -> Add Support Library

Once it was added, then I was able to use LocalBroadcastManager class in my code.


Android Compatibility Library

How to read a HttpOnly cookie using JavaScript

Httponly cookies' purpose is being inaccessible by script, so you CAN NOT.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

This issue is caused by the pipeline mode in your Application Pool setting that your web site is set to.

Short

  • Simple way Change the Application Pool mode to one that has Classic pipeline enabled.
  • Correct way Your web.config / web app will need to be altered to support Integrated pipelines. Normally this is as simple as removing parts of your web.config.
  • Simple way (bad practice) Add the following to your web.config. See http://www.iis.net/ConfigReference/system.webServer/validation

     <system.webServer>
         <validation validateIntegratedModeConfiguration="false" />
     </system.webServer>
    

Long If possible, your best bet is to change your application to support the integrated pipelines. There are a number of changes between IIS6 and IIS7.x that will cause this error. You can find details about these changes here http://learn.iis.net/page.aspx/381/aspnet-20-breaking-changes-on-iis-70/.

If you're unable to do that, you'll need to change the App pool which may be more difficult to do depending on your availability to the web server.

  • Go to the web server
  • Open the IIS Manager
  • Navigate to your site
  • Click Advanced Settings on the right Action pane
  • Under Application Pool, change it to an app pool that has classic enabled.

Check http://technet.microsoft.com/en-us/library/cc731755(WS.10).aspx for details on changing the App Pool

If you need to create an App Pool with Classic pipelines, take a look at http://technet.microsoft.com/en-us/library/cc731784(WS.10).aspx

If you don't have access to the server to make this change, you'll need to do this through your hosting server and contact them for help.

Feel free to ask questions.

Should I use the datetime or timestamp data type in MySQL?

+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+
|                                       TIMESTAMP                                       |                                 DATETIME                                 |
+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+
| TIMESTAMP requires 4 bytes.                                                           | DATETIME requires 8 bytes.                                               |
| Timestamp is the number of seconds that have elapsed since January 1, 1970 00:00 UTC. | DATETIME is a text displays 'YYYY-MM-DD HH:MM:SS' format.                |
| TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC.    | DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59' |
| TIMESTAMP during retrieval converted back to the current time zone.                   | DATETIME can not do this.                                                |
| TIMESTAMP is used mostly for metadata i.e. row created/modified and audit purpose.    | DATETIME is used mostly for user-data.                                   |
+---------------------------------------------------------------------------------------+--------------------------------------------------------------------------+

In Java, how to find if first character in a string is upper case without regex

Actually, this is subtler than it looks.

The code above would give the incorrect answer for a lower case character whose code point was above U+FFFF (such as U+1D4C3, MATHEMATICAL SCRIPT SMALL N). String.charAt would return a UTF-16 surrogate pair, which is not a character, but rather half the character, so to speak. So you have to use String.codePointAt, which returns an int above 0xFFFF (not a char). You would do:

Character.isUpperCase(s.codePointAt(0));

Don't feel bad overlooked this; almost all Java coders handle UTF-16 badly, because the terminology misleadingly makes you think that each "char" value represents a character. UTF-16 sucks, because it is almost fixed width but not quite. So non-fixed-width edge cases tend not to get tested. Until one day, some document comes in which contains a character like U+1D4C3, and your entire system blows up.

Is there a JavaScript function that can pad a string to get to a determined length?

I think its better to avoid recursion because its costly.

_x000D_
_x000D_
function padLeft(str,size,padwith) {_x000D_
 if(size <= str.length) {_x000D_
        // not padding is required._x000D_
  return str;_x000D_
 } else {_x000D_
        // 1- take array of size equal to number of padding char + 1. suppose if string is 55 and we want 00055 it means we have 3 padding char so array size should be 3 + 1 (+1 will explain below)_x000D_
        // 2- now join this array with provided padding char (padwith) or default one ('0'). so it will produce '000'_x000D_
        // 3- now append '000' with orginal string (str = 55), will produce 00055_x000D_
_x000D_
        // why +1 in size of array? _x000D_
        // it is a trick, that we are joining an array of empty element with '0' (in our case)_x000D_
        // if we want to join items with '0' then we should have at least 2 items in the array to get joined (array with single item doesn't need to get joined)._x000D_
        // <item>0<item>0<item>0<item> to get 3 zero we need 4 (3+1) items in array   _x000D_
  return Array(size-str.length+1).join(padwith||'0')+str_x000D_
 }_x000D_
}_x000D_
_x000D_
alert(padLeft("59",5) + "\n" +_x000D_
     padLeft("659",5) + "\n" +_x000D_
     padLeft("5919",5) + "\n" +_x000D_
     padLeft("59879",5) + "\n" +_x000D_
     padLeft("5437899",5));
_x000D_
_x000D_
_x000D_

In SQL Server, what does "SET ANSI_NULLS ON" mean?

I guess the main thing here is:

Never user:

  • @anything = NULL
  • @anything <> NULL
  • @anything != null

Always use:

  • @anything IS NULL
  • @anything IS NOT NULL

Return first N key:value pairs from dict

I have tried a few of the answers above and note that some of them are version dependent and do not work in version 3.7.

I also note that since 3.6 all dictionaries are ordered by the sequence in which items are inserted.

Despite dictionaries being ordered since 3.6 some of the statements you expect to work with ordered structures don't seem to work.

The answer to the OP question that worked best for me.

itr = iter(dic.items())
lst = [next(itr) for i in range(3)]

How to display a Windows Form in full screen on top of the taskbar?

FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
WindowState = FormWindowState.Maximized;

Facebook Like-Button - hide count?

The Like button coded to show "Recommend" is 84px wide and the "Like" button is 44px, will save some time for you CSS guys like me who need to hide how unpopular my page currently is! I put this code on top of my homepage, so initially I don't want it to advertise how few Likes I have.

Email Address Validation in Android on EditText

Use this method for validating your email format. Pass email as string , it returns true if format is correct otherwise false.

/**
 * validate your email address format. [email protected]
 */
public boolean emailValidator(String email) 
{
    Pattern pattern;
    Matcher matcher;
    final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    pattern = Pattern.compile(EMAIL_PATTERN);
    matcher = pattern.matcher(email);
    return matcher.matches();
}

Matplotlib transparent line plots

After I plotted all the lines, I was able to set the transparency of all of them as follows:

for l in fig_field.gca().lines:
    l.set_alpha(.7)

EDIT: please see Joe's answer in the comments.

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

START_STICKY and START_NOT_STICKY

KISS answer

Difference:

START_STICKY

the system will try to re-create your service after it is killed

START_NOT_STICKY

the system will not try to re-create your service after it is killed


Standard example:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

You should create a background thread to to create and populate the form. This will allow your foreground thread to show the loading message.

git: How to ignore all present untracked files?

I came here trying to solve a slightly different problem. Maybe this will be useful to someone else:

I create a new branch feature-a. as part of this branch I create new directories and need to modify .gitignore to suppress some of them. This happens a lot when adding new tools to a project that create various cache folders. .serverless, .terraform, etc.

Before I'm ready to merge that back to master I have something else come up, so I checkout master again, but now git status picks up those suppressed folders again, since the .gitignore hasn't been merged yet.

The answer here is actually simple, though I had to find this blog to figure it out:

Just checkout the .gitignore file from feature-a branch

git checkout feature-a -- feature-a/.gitignore
git add .
git commit -m "update .gitignore from feature-a branch"

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

For me, only catching the mouseenter event was a bit buggy, and the tooltip was not showing/hiding properly. I had to write this, and it is now working perfectly:

$(document).on('mouseenter','[rel=tooltip]', function(){
    $(this).tooltip('show');
});

$(document).on('mouseleave','[rel=tooltip]', function(){
    $(this).tooltip('hide');
});

Google Map API v3 — set bounds and center

The setCenter() method is still applicable for latest version of Maps API for Flash where fitBounds() does not exist.

jQuery scrollTop not working in Chrome but working in Firefox

 $("html, body").animate({ scrollTop: 0 }, "slow");

This CSS conflict with scroll to top so take care of this

 html, body {
         overflow-x: hidden;        
    }

Why doesn't JavaScript have a last method?

i = [].concat(loves).pop(); //corn

icon cat loves popcorn

How to execute Table valued function

A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:

select * from FN('myFunc')

How to select and change value of table cell with jQuery?

You can use CSS selectors.

Depending on how you get that td, you can either give it an id:

<td id='cell'>c</td>

and then use:

$("#cell").text("text");

Or traverse to the third cell of the first row of table_header, etc.

How do I prevent the padding property from changing width or height in CSS?

If you would like to indent text within a div without changing the size of the div use the CSS text-indent instead of padding-left.

_x000D_
_x000D_
.indent {_x000D_
  text-indent: 1em;_x000D_
}_x000D_
.border {_x000D_
  border-style: solid;_x000D_
}
_x000D_
<div class="border">_x000D_
  Non indented_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<div class="border indent">_x000D_
  Indented_x000D_
</div>
_x000D_
_x000D_
_x000D_

A beginner's guide to SQL database design

I started out with this article

http://en.tekstenuitleg.net/articles/software/database-design-tutorial/intro.html

It's pretty concise compared to reading an entire book and it explains the basics of database design (normalization, types of relationships) very well.

Understanding string reversal via slicing

It's basic step notation, consider the functionality of:

a[2:4:2]

What happens is the index is sliced between position 2 and 4, what the third variable does is it sets the step size starting from the first value. In this case it would return a[2], since a[4] is an upper bounds only two values are return and no second step takes place. The (-) minus operator simply reverses the step output.

Build a simple HTTP server in C

I suggest you take a look at tiny httpd. If you want to write it from scratch, then you'll want to thoroughly read RFC 2616. Use BSD sockets to access the network at a really low level.

Using SimpleXML to create an XML object from scratch

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>

Have fun.

NSString with \n or line break

\n\r seems working for me.

I am using Xcode 4.6 with IOS 6.0 as target. Tested on iPhone 4S. Try it by yourself.

Feng Chiu

Stuck at ".android/repositories.cfg could not be loaded."

Creating a dummy blank repositories.cfg works on Windows 7 as well. After waiting for a couple of minutes the installation finishes and you get the message on your cmd window -- done

Do we need type="text/css" for <link> in HTML5

Don’t need to specify a type value of “text/css”

Every time you link to a CSS file:

<link rel="stylesheet" type="text/css" href="file.css">

You can simply write:

<link rel="stylesheet" href="file.css">

Selecting data from two different servers in SQL Server

I had same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. Other answers didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.

An extended answer for remote IP db connections:

Step 1: link servers

EXEC sp_addlinkedserver @server='SRV_NAME',
   @srvproduct=N'',
   @provider=N'SQLNCLI',   
   @datasrc=N'aaa.bbb.ccc.ddd';

EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'

...where SRV_NAME is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd is the ip address of the remote server hosting your SQLserver DB.

Step 2: Run your queries For instance:

SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table

...and that's it!

Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin

Writing file to web server - ASP.NET

There are methods like WriteAllText in the File class for common operations on files.

Use the MapPath method to get the physical path for a file in your web application.

File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);

How to make UIButton's text alignment center? Using IB

Try Like this :

yourButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
yourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

How to append data to div using JavaScript?

The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData MDN Reference AppendData

let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;

if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
   lastChild.appendData("YOUR TEXT CONTENT");

Concatenating Matrices in R

Sounds like you're looking for rbind:

> a<-matrix(nrow=10,ncol=5)
> b<-matrix(nrow=20,ncol=5)
> dim(rbind(a,b))
[1] 30  5

Similarly, cbind stacks the matrices horizontally.

I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")

symfony2 : failed to write cache directory

Maybe you forgot to change the permissions of app/cache app/log

I'm using Ubuntu so

sudo chmod -R 777 app/cache
sudo chmod -R 777 app/logs
sudo setfacl -dR -m u::rwX app/cache app/logs

Hope it helps..

What is more efficient? Using pow to square or just multiply it with itself?

I tested the performance difference between x*x*... vs pow(x,i) for small i using this code:

#include <cstdlib>
#include <cmath>
#include <boost/date_time/posix_time/posix_time.hpp>

inline boost::posix_time::ptime now()
{
    return boost::posix_time::microsec_clock::local_time();
}

#define TEST(num, expression) \
double test##num(double b, long loops) \
{ \
    double x = 0.0; \
\
    boost::posix_time::ptime startTime = now(); \
    for (long i=0; i<loops; ++i) \
    { \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
        x += expression; \
    } \
    boost::posix_time::time_duration elapsed = now() - startTime; \
\
    std::cout << elapsed << " "; \
\
    return x; \
}

TEST(1, b)
TEST(2, b*b)
TEST(3, b*b*b)
TEST(4, b*b*b*b)
TEST(5, b*b*b*b*b)

template <int exponent>
double testpow(double base, long loops)
{
    double x = 0.0;

    boost::posix_time::ptime startTime = now();
    for (long i=0; i<loops; ++i)
    {
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
        x += std::pow(base, exponent);
    }
    boost::posix_time::time_duration elapsed = now() - startTime;

    std::cout << elapsed << " ";

    return x;
}

int main()
{
    using std::cout;
    long loops = 100000000l;
    double x = 0.0;
    cout << "1 ";
    x += testpow<1>(rand(), loops);
    x += test1(rand(), loops);

    cout << "\n2 ";
    x += testpow<2>(rand(), loops);
    x += test2(rand(), loops);

    cout << "\n3 ";
    x += testpow<3>(rand(), loops);
    x += test3(rand(), loops);

    cout << "\n4 ";
    x += testpow<4>(rand(), loops);
    x += test4(rand(), loops);

    cout << "\n5 ";
    x += testpow<5>(rand(), loops);
    x += test5(rand(), loops);
    cout << "\n" << x << "\n";
}

Results are:

1 00:00:01.126008 00:00:01.128338 
2 00:00:01.125832 00:00:01.127227 
3 00:00:01.125563 00:00:01.126590 
4 00:00:01.126289 00:00:01.126086 
5 00:00:01.126570 00:00:01.125930 
2.45829e+54

Note that I accumulate the result of every pow calculation to make sure the compiler doesn't optimize it away.

If I use the std::pow(double, double) version, and loops = 1000000l, I get:

1 00:00:00.011339 00:00:00.011262 
2 00:00:00.011259 00:00:00.011254 
3 00:00:00.975658 00:00:00.011254 
4 00:00:00.976427 00:00:00.011254 
5 00:00:00.973029 00:00:00.011254 
2.45829e+52

This is on an Intel Core Duo running Ubuntu 9.10 64bit. Compiled using gcc 4.4.1 with -o2 optimization.

So in C, yes x*x*x will be faster than pow(x, 3), because there is no pow(double, int) overload. In C++, it will be the roughly same. (Assuming the methodology in my testing is correct.)


This is in response to the comment made by An Markm:

Even if a using namespace std directive was issued, if the second parameter to pow is an int, then the std::pow(double, int) overload from <cmath> will be called instead of ::pow(double, double) from <math.h>.

This test code confirms that behavior:

#include <iostream>

namespace foo
{

    double bar(double x, int i)
    {
        std::cout << "foo::bar\n";
        return x*i;
    }


}

double bar(double x, double y)
{
    std::cout << "::bar\n";
    return x*y;
}

using namespace foo;

int main()
{
    double a = bar(1.2, 3); // Prints "foo::bar"
    std::cout << a << "\n";
    return 0;
}

byte[] to hex string

I like using extension methods for conversions like this, even if they just wrap standard library methods. In the case of hexadecimal conversions, I use the following hand-tuned (i.e., fast) algorithms:

public static string ToHex(this byte[] bytes)
{
    char[] c = new char[bytes.Length * 2];

    byte b;

    for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx) 
    {
        b = ((byte)(bytes[bx] >> 4));
        c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);

        b = ((byte)(bytes[bx] & 0x0F));
        c[++cx]=(char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
    }

    return new string(c);
}

public static byte[] HexToBytes(this string str)
{
    if (str.Length == 0 || str.Length % 2 != 0)
        return new byte[0];

    byte[] buffer = new byte[str.Length / 2];
    char c;
    for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
    {
        // Convert first half of byte
        c = str[sx];
        buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);

        // Convert second half of byte
        c = str[++sx];
        buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
    }

    return buffer;
}

Creating and Naming Worksheet in Excel VBA

Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here

http://www.dailydoseofexcel.com/archives/2005/01/04/naming-a-sheet-based-on-a-cell/

for a list of invalid characters that you may want to check for.

Update

Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).

Dim WS As Worksheet
Dim i As Long

With ThisWorkbook
    Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With

For i = 1 To 1000
    DoEvents
Next i

WS.Name = txtSheetName.Value

Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.

Input type=password, don't let browser remember the password

Try using autocomplete="off". Not sure if every browser supports it, though. MSDN docs here.

EDIT: Note: most browsers have dropped support for this attribute. See Is autocomplete="off" compatible with all modern browsers?

This is arguably something that should be left up to the user rather than the web site designer.

ORA-01008: not all variables bound. They are bound

You have two references to the :lot_priprc binding variable -- while it should require you to only set the variable's value once and bind it in both places, I've had problems where this didn't work and had to treat each copy as a different variable. A pain, but it worked.

Find in Files: Search all code in Team Foundation Server

This is now possible as of TFS 2015 by using the Code Search plugin. https://marketplace.visualstudio.com/items?itemName=ms.vss-code-search

The search is done via the web interface, and does not require you to download the code to your local machine which is nice.

Get the name of an object's type

Jason Bunting's answer gave me enough of a clue to find what I needed:

<<Object instance>>.constructor.name

So, for example, in the following piece of code:

function MyObject() {}
var myInstance = new MyObject();

myInstance.constructor.name would return "MyObject".

What is the best (and safest) way to merge a Git branch into master?

I would use the rebase method. Mostly because it perfectly reflects your case semantically, ie. what you want to do is to refresh the state of your current branch and "pretend" as if it was based on the latest.

So, without even checking out master, I would:

git fetch origin
git rebase -i origin/master
# ...solve possible conflicts here

Of course, just fetching from origin does not refresh the local state of your master (as it does not perform a merge), but it is perfectly ok for our purpose - we want to avoid switching around, for the sake of saving time.

Dynamically adding elements to ArrayList in Groovy

The Groovy way to do this is

def list = []
list << new MyType(...)

which creates a list and uses the overloaded leftShift operator to append an item

See the Groovy docs on Lists for lots of examples.

How to get span tag inside a div in jQuery and assign a text?

Vanilla JS, without jQuery:

document.querySelector('#message span').innerHTML = 'hello world!'

Available in all browsers: https://caniuse.com/#search=querySelector

Defining TypeScript callback type

I'm a little late, but, since some time ago in TypeScript you can define the type of callback with

type MyCallback = (KeyboardEvent) => void;

Example of use:

this.addEvent(document, "keydown", (e) => {
    if (e.keyCode === 1) {
      e.preventDefault();
    }
});

addEvent(element, eventName, callback: MyCallback) {
    element.addEventListener(eventName, callback, false);
}

What is HTML5 ARIA?

I ran some other question regarding ARIA. But it's content looks more promising for this question. would like to share them

What is ARIA?

If you put effort into making your website accessible to users with a variety of different browsing habits and physical disabilities, you'll likely recognize the role and aria-* attributes. WAI-ARIA (Accessible Rich Internet Applications) is a method of providing ways to define your dynamic web content and applications so that people with disabilities can identify and successfully interact with it. This is done through roles that define the structure of the document or application, or through aria-* attributes defining a widget-role, relationship, state, or property.

ARIA use is recommended in the specifications to make HTML5 applications more accessible. When using semantic HTML5 elements, you should set their corresponding role.

And see this you tube video for ARIA live.

js window.open then print()

Turgut gave the right solution. Just for clarity, you need to add close after writing.

function openWin()
  {
    myWindow=window.open('','','width=200,height=100');
    myWindow.document.write("<p>This is 'myWindow'</p>");


    myWindow.document.close(); //missing code


    myWindow.focus();
    myWindow.print(); 
  }

How to do URL decoding in Java?

 try {
        String result = URLDecoder.decode(urlString, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Styling mat-select in Angular Material

Put your class name on the mat-form-field element. This works for all inputs.

When should one use a spinlock instead of mutex?

Continuing with Mecki's suggestion, this article pthread mutex vs pthread spinlock on Alexander Sandler's blog, Alex on Linux shows how the spinlock & mutexes can be implemented to test the behavior using #ifdef.

However, be sure to take the final call based on your observation, understanding as the example given is an isolated case, your project requirement, environment may be entirely different.

how to open an URL in Swift3

I'm using macOS Sierra (v10.12.1) Xcode v8.1 Swift 3.0.1 and here's what worked for me in ViewController.swift:

//
//  ViewController.swift
//  UIWebViewExample
//
//  Created by Scott Maretick on 1/2/17.
//  Copyright © 2017 Scott Maretick. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController {

    //added this code
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Your webView code goes here
        let url = URL(string: "https://www.google.com")
        if UIApplication.shared.canOpenURL(url!) {
            UIApplication.shared.open(url!, options: [:], completionHandler: nil)
            //If you want handle the completion block than
            UIApplication.shared.open(url!, options: [:], completionHandler: { (success) in
                print("Open url : \(success)")
            })
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


};

sed edit file in place

On a system where sed does not have the ability to edit files in place, I think the better solution would be to use perl:

perl -pi -e 's/foo/bar/g' file.txt

Although this does create a temporary file, it replaces the original because an empty in place suffix/extension has been supplied.

Download old version of package with NuGet

In NuGet 3.x (Visual Studio 2015) you can just select the version from the UI

NuGet 3 package manager UI

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

In my case the problem is fixed by setting the right permissions for the tomcat home path:

cd /opt/apache-tomee-webprofile-7.1.0/
chown -R tomcat:tomcat *

Encrypt & Decrypt using PyCrypto AES 256

Here is my implementation and works for me with some fixes and enhances the alignment of the key and secret phrase with 32 bytes and iv to 16 bytes:

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher(object):

    def __init__(self, key): 
        self.bs = AES.block_size
        self.key = hashlib.sha256(key.encode()).digest()

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw.encode()))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]

How do you convert a time.struct_time object into a datetime object?

Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.

from datetime import datetime
from time import mktime

dt = datetime.fromtimestamp(mktime(struct))

Can't find AVD or SDK manager in Eclipse

I had similar problem after updating SDK from r20 to r21, but all I missed was the SDK/AVD Manager and running into this post while searching for the answer.

I managed to solve it by going to Window -> Customize Perspective, and under Command Groups Availability tab check the Android SDK and AVD Manager (not sure why it became unchecked because it was there before). I'm using Mac by the way, in case the menu option looks different.

Stop form from submitting , Using Jquery

This is a JQuery code for Preventing Submit

$('form').submit(function (e) {
            if (radioButtonValue !== "0") {
                e.preventDefault();
            }
        });

Hex transparency in colors

I always keep coming here to check for int/hex alpha value. So, end up creating a simple method in my java utils class. This method will convert the percentage to hex value and append to the color code string value.

 public static String setColorAlpha(int percentage, String colorCode){
    double decValue = ((double)percentage / 100) * 255;
    String rawHexColor = colorCode.replace("#","");
    StringBuilder str = new StringBuilder(rawHexColor);

    if(Integer.toHexString((int)decValue).length() == 1)
        str.insert(0, "#0" + Integer.toHexString((int)decValue));
    else
        str.insert(0, "#" + Integer.toHexString((int)decValue));
    return str.toString();
}

So, Utils.setColorAlpha(30, "#000000") will give you #4c000000

Creating a system overlay window (always on top)

WORKING ALWAYS ON TOP IMAGE BUTTON

first of all sorry for my english

i edit your codes and make working image button that listens his touch event do not give touch control to his background elements.

also it gives touch listeners to out of other elements

button alingments are bottom and left

you can chage alingments but you need to chages cordinats in touch event in the if element

import android.annotation.SuppressLint;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;

public class HepUstte extends Service {
    HUDView mView;

    @Override
    public void onCreate() {
        super.onCreate();   

        Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();

        final Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
                R.drawable.logo_l);


        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                kangoo.getWidth(), 
                kangoo.getHeight(),
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                |WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                |WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                 PixelFormat.TRANSLUCENT);






        params.gravity = Gravity.LEFT | Gravity.BOTTOM;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);



        mView = new HUDView(this,kangoo);

        mView.setOnTouchListener(new OnTouchListener() {


            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                // TODO Auto-generated method stub
                //Log.e("kordinatlar", arg1.getX()+":"+arg1.getY()+":"+display.getHeight()+":"+kangoo.getHeight());
                if(arg1.getX()<kangoo.getWidth() & arg1.getY()>0)
                {
                 Log.d("tiklandi", "touch me");
                }
                return false;
            }
             });


        wm.addView(mView, params);



        }



    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

}



@SuppressLint("DrawAllocation")
class HUDView extends ViewGroup {


    Bitmap kangoo;

    public HUDView(Context context,Bitmap kangoo) {
        super(context);

        this.kangoo=kangoo;



    }


    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);


        // delete below line if you want transparent back color, but to understand the sizes use back color
        canvas.drawColor(Color.BLACK);

        canvas.drawBitmap(kangoo,0 , 0, null); 


        //canvas.drawText("Hello World", 5, 15, mLoadPaint);

    }


    protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
    }

    public boolean onTouchEvent(MotionEvent event) {
        //return super.onTouchEvent(event);
       // Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();

        return true;
    }
}

Convert date to YYYYMM format

A more efficient method, that uses integer math rather than strings/varchars, that will result in an int type rather than a string type is:

SELECT YYYYMM = (YEAR(GETDATE()) * 100) + MONTH(GETDATE())

Adds two zeros to the right side of the year and then adds the month to the added two zeros.

How do I install a NuGet package .nupkg file locally?

On Linux, with NuGet CLI, the commands are similar. To install my.nupkg, run

nuget add -Source some/directory my.nupkg

Then run dotnet restore from that directory

dotnet restore --source some/directory Project.sln

or add that directory as a NuGet source

nuget sources Add -Name MySource -Source some/directory

and then tell msbuild to use that directory with /p:RestoreAdditionalSources=MySource or /p:RestoreSources=MySource. The second switch will disable all other sources, which is good for offline scenarios, for example.

What is the default initialization of an array in Java?

According to java,

Data Type - Default values

byte - 0

short - 0

int - 0

long - 0L

float - 0.0f

double - 0.0d

char - '\u0000'

String (or any object) - null

boolean - false

How can I convert a date to GMT?

Based on the accepted answer and the second highest scoring answer both are not perfect according to the comment so I mixed both to get something perfect:

_x000D_
_x000D_
var date = new Date(); //Current timestamp_x000D_
date = date.toGMTString(); _x000D_
//Based on the time zone where the date was created_x000D_
console.log(date);_x000D_
_x000D_
/*based on the comment getTimezoneOffset returns an offset based _x000D_
on the date it is called on, and the time zone of the computer the code is_x000D_
 running on. It does not supply the offset passed in when constructing a _x000D_
date from a string. */_x000D_
_x000D_
date = new Date(date); //will convert to present timestamp offset_x000D_
date = new Date(date.getTime() + (date.getTimezoneOffset() * 60 * 1000)); _x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

TypeError: Image data can not convert to float

This question comes up first in the Google search for this type error, but does not have a general answer about the cause of the error. The poster's unique problem was the use of an inappropriate object type as the main argument for plt.imshow(). A more general answer is that plt.imshow() wants an array of floats and if you don't specify a float, numpy, pandas, or whatever else, might infer a different data type somewhere along the line. You can avoid this by specifying a float for the dtype argument is the constructor of the object.

See the Numpy documentation here.

See the Pandas documentation here

HTML form readonly SELECT tag/input

One simple server-side approach is to remove all the options except the one that you want to be selected. Thus, in Zend Framework 1.12, if $element is a Zend_Form_Element_Select:

 $value =  $element->getValue();
 $options = $element->getAttrib('options');
 $sole_option = array($value => $options[$value]);
 $element->setAttrib('options', $sole_option);

What is the use of verbose in Keras while validating the model?

For verbose > 0, fit method logs:

  • loss: value of loss function for your training data
  • acc: accuracy value for your training data.

Note: If regularization mechanisms are used, they are turned on to avoid overfitting.

if validation_data or validation_split arguments are not empty, fit method logs:

  • val_loss: value of loss function for your validation data
  • val_acc: accuracy value for your validation data

Note: Regularization mechanisms are turned off at testing time because we are using all the capabilities of the network.

For example, using verbose while training the model helps to detect overfitting which occurs if your acc keeps improving while your val_acc gets worse.

2 "style" inline css img tags?

You should use :

<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="25"/>

That should work!!

If you want to create class then :

.size {
width:100px;
height:100px;
}

and then apply it like :

<img src="http://img705.imageshack.us/img705/119/original120x75.png" class="size" alt="25"/>

by creating a class you can use it at multiple places.

If you want to use only at one place then use inline CSS. Also Inline CSS overrides other CSS.

How to set the component size with GridLayout? Is there a better way?

In my project I managed to use GridLayout and results are very stable, with no flickering and with a perfectly working vertical scrollbar.

First I created a JPanel for the settings; in my case it is a grid with a row for each parameter and two columns: left column is for labels and right column is for components. I believe your case is similar.

JPanel yourSettingsPanel = new JPanel();
yourSettingsPanel.setLayout(new GridLayout(numberOfParams, 2));

I then populate this panel by iterating on my parameters and alternating between adding a JLabel and adding a component.

for (int i = 0; i < numberOfParams; ++i) {
    yourSettingsPanel.add(labels[i]);
    yourSettingsPanel.add(components[i]);
}

To prevent yourSettingsPanel from extending to the entire container I first wrap it in the north region of a dummy panel, that I called northOnlyPanel.

JPanel northOnlyPanel = new JPanel();
northOnlyPanel.setLayout(new BorderLayout());
northOnlyPanel.add(yourSettingsPanel, BorderLayout.NORTH);

Finally I wrap the northOnlyPanel in a JScrollPane, which should behave nicely pretty much anywhere.

JScrollPane scroll = new JScrollPane(northOnlyPanel,
                                     JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

Most likely you want to display this JScrollPane extended inside a JFrame; you can add it to a BorderLayout JFrame, in the CENTER region:

window.add(scroll, BorderLayout.CENTER);

In my case I put it on the left column of a GridLayout(1, 2) panel, and I use the right column to display contextual help for each parameter.

JTextArea help = new JTextArea();
help.setLineWrap(true);
help.setWrapStyleWord(true);
help.setEditable(false);

JPanel split = new JPanel();
split.setLayout(new GridLayout(1, 2));
split.add(scroll);
split.add(help);

How to convert an NSString into an NSNumber

Worked in Swift 3

NSDecimalNumber(string: "Your string") 

Changing background color of selected item in recyclerview

in the Kotlin you can do this simply: all you need is to create a static variable like this:

companion object {
     var last_position = 0
}

then in your onBindViewHolder add this code:

holder.item.setOnClickListener{
        holder.item.setBackgroundResource(R.drawable.selected_item)
        notifyItemChanged(last_position)
        last_position=position
    }

which item is the child of recyclerView which you want to change its background after clicking on it.

Passing parameters in rails redirect_to

If you are using RESTful resources you can do the following:

redirect_to action_name_resource_path(resource_object, param_1: 'value_1', param_2: 'value_2')

or
#You can also use the object_id instead of the object
redirect_to action_name_resource_path(resource_object_id, param_1: 'value_1', param_2: 'value_2')

or
#if its a collection action like index, you can omit the id as follows
redirect_to action_name_resource_path(param_1: 'value_1', param_2: 'value_2')

#An example with nested resource is as follows:
redirect_to edit_user_project_path(@user, @project, param_1: 'value_1', param_2: 'value_2')

Using grep to search for hex strings in a file

I just used this:

grep -c $'\x0c' filename

To search for and count a page control character in the file..

So to include an offset in the output:

grep -b -o $'\x0c' filename | less

I am just piping the result to less because the character I am greping for does not print well and the less displays the results cleanly. Output example:

21:^L
23:^L
2005:^L

Get time difference between two dates in seconds

The Code

var startDate = new Date();
// Do your operations
var endDate   = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;

Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.


The explanation

You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00


Rant

Depending on what your date related operations are, you might want to invest in integrating a library such as date.js or moment.js which make things so much easier for the developer, but that's just a matter of personal preference.

For example in moment.js we would do moment1.diff(moment2, "seconds") which is beautiful.


Useful docs for this answer

Dynamically create and submit form

Yes, it is possible. One of the solutions is below (jsfiddle as a proof).

HTML:

<a id="fire" href="#" title="submit form">Submit form</a>

(see, above there is no form)

JavaScript:

jQuery('#fire').click(function(event){
    event.preventDefault();
    var newForm = jQuery('<form>', {
        'action': 'http://www.google.com/search',
        'target': '_top'
    }).append(jQuery('<input>', {
        'name': 'q',
        'value': 'stack overflow',
        'type': 'hidden'
    }));
    newForm.submit();
});

The above example shows you how to create form, how to add inputs and how to submit. Sometimes display of the result is forbidden by X-Frame-Options, so I have set target to _top, which replaces the main window's content. Alternatively if you set _blank, it can show within new window / tab.

How do I copy a folder from remote to local using scp?

Better to first compress catalog on remote server:

tar czfP backup.tar.gz /path/to/catalog

Secondly, download from remote:

scp [email protected]:/path/to/backup.tar.gz .

At the end, extract the files:

tar -xzvf backup.tar.gz

How to list all the available keyspaces in Cassandra?

  1. login to cqlsh

  2. use below command to get names/list of keyspaces present

         SELECT keyspace_name FROM system_schema.keyspaces;
    

How to blur background images in Android

You can use

    Glide.with(getContext()).load(R.mipmap.bg)
            .apply(bitmapTransform(new BlurTransformation(22)))
            .into((ImageView) view.findViewById(R.id.imBg));

Show Image View from file path?

You can also use:



    File imgFile = new  File(“filepath”);
    if(imgFile.exists())
    {
        ImageView myImage = new ImageView(this);
        myImage.setImageURI(Uri.fromFile(imgFile));

    }

This does the bitmap decoding implicit for you.

if statements matching multiple values

In vb.net or C# I would expect that the fastest general approach to compare a variable against any reasonable number of separately-named objects (as opposed to e.g. all the things in a collection) will be to simply compare each object against the comparand much as you have done. It is certainly possible to create an instance of a collection and see if it contains the object, and doing so may be more expressive than comparing the object against all items individually, but unless one uses a construct which the compiler can explicitly recognize, such code will almost certainly be much slower than simply doing the individual comparisons. I wouldn't worry about speed if the code will by its nature run at most a few hundred times per second, but I'd be wary of the code being repurposed to something that's run much more often than originally intended.

An alternative approach, if a variable is something like an enumeration type, is to choose power-of-two enumeration values to permit the use of bitmasks. If the enumeration type has 32 or fewer valid values (e.g. starting Harry=1, Ron=2, Hermione=4, Ginny=8, Neville=16) one could store them in an integer and check for multiple bits at once in a single operation ((if ((thisOne & (Harry | Ron | Neville | Beatrix)) != 0) /* Do something */. This will allow for fast code, but is limited to enumerations with a small number of values.

A somewhat more powerful approach, but one which must be used with care, is to use some bits of the value to indicate attributes of something, while other bits identify the item. For example, bit 30 could indicate that a character is male, bit 29 could indicate friend-of-Harry, etc. while the lower bits distinguish between characters. This approach would allow for adding characters who may or may not be friend-of-Harry, without requiring the code that checks for friend-of-Harry to change. One caveat with doing this is that one must distinguish between enumeration constants that are used to SET an enumeration value, and those used to TEST it. For example, to set a variable to indicate Harry, one might want to set it to 0x60000001, but to see if a variable IS Harry, one should bit-test it with 0x00000001.

One more approach, which may be useful if the total number of possible values is moderate (e.g. 16-16,000 or so) is to have an array of flags associated with each value. One could then code something like "if (((characterAttributes[theCharacter] & chracterAttribute.Male) != 0)". This approach will work best when the number of characters is fairly small. If array is too large, cache misses may slow down the code to the point that testing against a small number of characters individually would be faster.

GROUP BY and COUNT in PostgreSQL

Using OVER() and LIMIT 1:

SELECT COUNT(1) OVER()
FROM posts 
   INNER JOIN votes ON votes.post_id = posts.id 
GROUP BY posts.id
LIMIT 1;

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

Laravel - Model Class not found

I was having the same "Class [class name] not found" error message, but it wasn't a namespace issue. All my namespaces were set up correctly. I even tried composer dump-autoload and it didn't help me.

Surprisingly (to me) I then did composer dump-autoload -o which according to Composer's help, "optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production." Somehow doing it that way got composer to behave and include the class correctly in the autoload_classmap.php file.

Oracle JDBC intermittent Connection Issue

The root cause of this problem has to do with user authentication versions. For each database user, multiple password verifiers are kept in the database. Typically when you upgrade your database, a new password verifier will be added to the list, a stronger one. The following query shows the password verifier versions that are available for each user. For example:

SQL> SELECT PASSWORD_VERSIONS FROM DBA_USERS WHERE USERNAME='SCOTT';

PASSWORD_VERSIONS
-----------------
11G 12C

When upgrading to a newer driver you can use a newer version of the verifier because the driver and server negotiate the strongest possible verifier to to be used. This newer version of the verifier will be more secure and will involve generating larger random numbers or using more complex hashing functions which can explain why you see issues while establishing JDBC connections. As mentioned by other responses using /dev/urandom normally resolves these issues. You can also decide to downgrade your password verifier and make the newer driver use the same older password verifier that your previous driver was using. For example if you want to use the 10G password verifier (for testing purposes only), first you need to make sure it's available for your user. Set SQLNET.ALLOWED_LOGON_VERSION_SERVER=8 in sqlnet.ora on the server. Then:

SQL> alter user scott identified by "tiger";

User altered.

SQL> SELECT PASSWORD_VERSIONS FROM DBA_USERS WHERE USERNAME='SCOTT';
PASSWORD_VERSIONS
-----------------
10G 11G 12C

Then you can force the JDBC thin driver to use the 10G verifier by setting this JDBC property oracle.jdbc.thinLogonCapability="o3". If you run into the error "ORA-28040: No matching authentication protocol" then that means your server is not allowing the 10G verifier to be used. If that's the case then you need to check your configuration again.

Mockito test a void method throws an exception

If you ever wondered how to do it using the new BDD style of Mockito:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));

What does auto do in margin:0 auto?

When you have specified a width on the object that you have applied margin: 0 auto to, the object will sit centrally within it's parent container.

Specifying auto as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first parameter 0 indicates that the top and bottom margins will both be set to 0.

margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;

Therefore, to give you an example, if the parent is 100px and the child is 50px, then the auto property will determine that there's 50px of free space to share between margin-left and margin-right:

var freeSpace = 100 - 50;
var equalShare = freeSpace / 2;

Which would give:

margin-left:25;
margin-right:25;

Have a look at this jsFiddle. You do not have to specify the parent width, only the width of the child object.

Detect touch press vs long press vs movement?

From the Android Docs -

onLongClick()

From View.OnLongClickListener. This is called when the user either touches and holds the item (when in touch mode), or focuses upon the item with the navigation-keys or trackball and presses and holds the suitable "enter" key or presses and holds down on the trackball (for one second).

onTouch()

From View.OnTouchListener. This is called when the user performs an action qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item).

As for the "moving happens even when I touch" I would set a delta and make sure the View has been moved by at least the delta before kicking in the movement code. If it hasn't been, kick off the touch code.

Getting path relative to the current working directory?

Thanks to the other answers here and after some experimentation I've created some very useful extension methods:

public static string GetRelativePathFrom(this FileSystemInfo to, FileSystemInfo from)
{
    return from.GetRelativePathTo(to);
}

public static string GetRelativePathTo(this FileSystemInfo from, FileSystemInfo to)
{
    Func<FileSystemInfo, string> getPath = fsi =>
    {
        var d = fsi as DirectoryInfo;
        return d == null ? fsi.FullName : d.FullName.TrimEnd('\\') + "\\";
    };

    var fromPath = getPath(from);
    var toPath = getPath(to);

    var fromUri = new Uri(fromPath);
    var toUri = new Uri(toPath);

    var relativeUri = fromUri.MakeRelativeUri(toUri);
    var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

    return relativePath.Replace('/', Path.DirectorySeparatorChar);
}

Important points:

  • Use FileInfo and DirectoryInfo as method parameters so there is no ambiguity as to what is being worked with. Uri.MakeRelativeUri expects directories to end with a trailing slash.
  • DirectoryInfo.FullName doesn't normalize the trailing slash. It outputs whatever path was used in the constructor. This extension method takes care of that for you.

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

The module was expected to contain an assembly manifest

First try to open the file with a decompiler such as ILSpy, your dll might be corrupt. I had this error on an online web site, when I downloaded the dll and tried to open it, it was corrupt, probably some error occurred while uploading it via ftp.

docker run <IMAGE> <MULTIPLE COMMANDS>

Just to make a proper answer from the @Eddy Hernandez's comment and which is very correct since Alpine comes with ash not bash.

The question now referes to Starting a shell in the Docker Alpine container which implies using sh or ash or /bin/sh or /bin/ash/.

Based on the OP's question:

docker run image sh -c "cd /path/to/somewhere && python a.py"

Convert Linq Query Result to Dictionary

Try the following

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

Or the fully fledged type inferenced version

var existingItems = TableObj.ToDictionary(x => x.Key);

Is quitting an application frowned upon?

There is a (relatively) simple design which will allow you to get around the "exit" conundrum. Make your app have a "base" state (activity) which is just a blank screen. On the first onCreate of the activity, you can launch another activity that your app's main functionality is in. The "exit" can then be accomplished by finish()ing this second activity and going back to the base of just a blank screen. The OS can keep this blank screen in memory for as long as it wants...

In essence, because you cannot exit out to OS, you simply transform into a self-created nothingness.

How do I count unique values inside a list

In addition, use collections.Counter to refactor your code:

from collections import Counter

words = ['a', 'b', 'c', 'a']

Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency

Output:

['a', 'c', 'b']
[2, 1, 1]

What are the differences between B trees and B+ trees?

Example from Database system concepts 5th

B+-tree B+tree

corresponding B-tree Btree

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

Consider defining a bean of type 'service' in your configuration [Spring boot]

In case you were wondering where to add @Service annotation, then make sure you have added @Service annotation to the class that implements the interface. That would solve this problem.

How to change the locale in chrome browser

Based from this thread, you need to bookmark chrome://settings/languages and then Drag and Drop the language to make it default. You have to click on the Display Google Chrome in this Language button and completely restart Chrome.

size of struct in C

As mentioned, the C compiler will add padding for alignment requirements. These requirements often have to do with the memory subsystem. Some types of computers can only access memory lined up to some 'nice' value, like 4 bytes. This is often the same as the word length. Thus, the C compiler may align fields in your structure to this value to make them easier to access (e.g., 4 byte values should be 4 byte aligned) Further, it may pad the bottom of the structure to line up data which follows the structure. I believe there are other reasons as well. More info can be found at this wikipedia page.

Equivalent of String.format in jQuery

Though not exactly what the Q was asking for, I've built one that is similar but uses named placeholders instead of numbered. I personally prefer having named arguments and just send in an object as an argument to it (more verbose, but easier to maintain).

String.prototype.format = function (args) {
    var newStr = this;
    for (var key in args) {
        newStr = newStr.replace('{' + key + '}', args[key]);
    }
    return newStr;
}

Here's an example usage...

alert("Hello {name}".format({ name: 'World' }));

How to paginate with Mongoose in Node.js?

you can use the following line of code as well

per_page = parseInt(req.query.per_page) || 10
page_no = parseInt(req.query.page_no) || 1
var pagination = {
  limit: per_page ,
  skip:per_page * (page_no - 1)
}
users = await User.find({<CONDITION>}).limit(pagination.limit).skip(pagination.skip).exec()

this code will work in latest version of mongo

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

AngularJS directive does not update on scope variable changes

You should keep a watch on your scope.

Here is how you can do it:

<layout layoutId="myScope"></layout>

Your directive should look like

app.directive('layout', function($http, $compile){
    return {
        restrict: 'E',
        scope: {
            layoutId: "=layoutId"
        },
        link: function(scope, element, attributes) {
            var layoutName = (angular.isDefined(attributes.name)) ? attributes.name : 'Default';
            $http.get(scope.constants.pathLayouts + layoutName + '.html')
                .success(function(layout){
                    var regexp = /^([\s\S]*?){{content}}([\s\S]*)$/g;
                    var result = regexp.exec(layout);

                    var templateWithLayout = result[1] + element.html() + result[2];
                    element.html($compile(templateWithLayout)(scope));
        });
    }
}

$scope.$watch('myScope',function(){
        //Do Whatever you want
    },true)

Similarly you can models in your directive, so if model updates automatically your watch method will update your directive.

Get only part of an Array in Java?

The length of an array in Java is immutable. So, you need to copy the desired part as a new array.
Use copyOfRange method from java.util.Arrays class:

int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);

startIndex is the initial index of the range to be copied, inclusive.
endIndex is the final index of the range to be copied, exclusive. (This index may lie outside the array)

E.g.:

   //index   0   1   2   3   4
int[] arr = {10, 20, 30, 40, 50};
Arrays.copyOfRange(arr, 0, 2);          // returns {10, 20}
Arrays.copyOfRange(arr, 1, 4);          // returns {20, 30, 40}
Arrays.copyOfRange(arr, 2, arr.length); // returns {30, 40, 50} (length = 5)

How to display the string html contents into webbrowser control?

Old question, but here's my go-to for this operation.

If browser.Document IsNot Nothing Then
    browser.Document.OpenNew(True)
    browser.Document.Write(My.Resources.htmlTemplate)
Else
    browser.DocumentText = My.Resources.htmlTemplate
End If

And be sure that any browser.Navigating event DOES NOT cancel "about:blank" URLs. Example event below for full control of WebBrowser navigating.

Private Sub browser_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles browser.Navigating

    Try
        Me.Cursor = Cursors.WaitCursor

        Select Case e.Url.Scheme

            Case Constants.App_Url_Scheme

                Dim query As Specialized.NameValueCollection = System.Web.HttpUtility.ParseQueryString(e.Url.Query)

                Select Case e.Url.Host

                    Case Constants.Navigation.URLs.ToggleExpander.Host

                        Dim nodeID As String = query.Item(Constants.Navigation.URLs.ToggleExpander.Parameters.NodeID)

                        :
                        :
                        <other operations here>
                        :
                        :

                End Select

            Case Else
                e.Cancel = (e.Url.ToString() <> "about:blank")

        End Select

    Catch ex As Exception
        ExceptionBox.Show(ex, "Operation failed.")
    Finally
        Me.Cursor = Cursors.Default
    End Try

End Sub

Scheduling Python Script to run every hour accurately

The Python standard library does provide sched and threading for this task. But this means your scheduler script will have be running all the time instead of leaving its execution to the OS, which may or may not be what you want.

Is there a way to catch the back button event in javascript?

I did a fun hack to solve this issue to my satisfaction. I've got an AJAX site that loads content dynamically, then modifies the window.location.hash, and I had code to run upon $(document).ready() to parse the hash and load the appropriate section. The thing is that I was perfectly happy with my section loading code for navigation, but wanted to add a way to intercept the browser back and forward buttons, which change the window location, but not interfere with my current page loading routines where I manipulate the window.location, and polling the window.location at constant intervals was out of the question.

What I ended up doing was creating an object as such:

var pageload = {
    ignorehashchange: false,
    loadUrl: function(){
        if (pageload.ignorehashchange == false){
            //code to parse window.location.hash and load content
        };
    }
};

Then, I added a line to my site script to run the pageload.loadUrl function upon the hashchange event, as such:

window.addEventListener("hashchange", pageload.loadUrl, false);

Then, any time I want to modify the window.location.hash without triggering this page loading routine, I simply add the following line before each window.location.hash = line:

pageload.ignorehashchange = true;

and then the following line after each hash modification line:

setTimeout(function(){pageload.ignorehashchange = false;}, 100);

So now my section loading routines are usually running, but if the user hits the 'back' or 'forward' buttons, the new location is parsed and the appropriate section loaded.

How do you configure HttpOnly cookies in tomcat / java webapps?

For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report Need to add support for HTTPOnly session cookie parameter. A somewhat involved work-around for now can be found here, which basically boils down to manually patching Tomcat. Can't really find an easy way to do it at this moment at this point I'm affraid.

To summarize the work-around, it involves downloading the 5.5 source, and then change the source in the following places:

org.apache.catalina.connector.Request.java

//this is what needs to be changed
//response.addCookieInternal(cookie);

//this is whats new
response.addCookieInternal(cookie, true);
}

org.apache.catalina.connectorResponse.addCookieInternal

public void addCookieInternal(final Cookie cookie) {
addCookieInternal(cookie, false);
}

public void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {

if (isCommitted())
return;

final StringBuffer sb = new StringBuffer();
//web application code can receive a IllegalArgumentException
//from the appendCookieValue invokation
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run(){
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(),
cookie.getValue(), cookie.getPath(),
cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
return null;
}
});
} else {
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
}
//of course, we really need to modify ServerCookie
//but this is the general idea
if (HTTPOnly) {
sb.append("; HttpOnly");
}

//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", sb.toString());

cookies.add(cookie);
}

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

C library function to perform sort

I think you are looking for qsort.
qsort function is the implementation of quicksort algorithm found in stdlib.h in C/C++.

Here is the syntax to call qsort function:

void qsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *));

List of arguments:

base: pointer to the first element or base address of the array
nmemb: number of elements in the array
size: size in bytes of each element
compar: a function that compares two elements

Here is a code example which uses qsort to sort an array:

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

int arr[] = { 33, 12, 6, 2, 76 };

// compare function, compares two elements
int compare (const void * num1, const void * num2) {
   if(*(int*)num1 > *(int*)num2)
    return 1;
   else
    return -1;
}

int main () {
   int i;

   printf("Before sorting the array: \n");
   for( i = 0 ; i < 5; i++ ) {
      printf("%d ", arr[i]);
   }
   // calling qsort
   qsort(arr, 5, sizeof(int), compare);

   printf("\nAfter sorting the array: \n");
   for( i = 0 ; i < 5; i++ ) {   
      printf("%d ", arr[i]);
   }
  
   return 0;
}

You can type man 3 qsort in Linux/Mac terminal to get a detailed info about qsort.
Link to qsort man page

How to disable phone number linking in Mobile Safari?

I too have this problem: Safari and other mobile browsers transform the VAT IDs into phone numbers. So I want a clean method to avoid it on a single element, not the whole page (or site).
I'm sharing a possible solution I found, it is suboptimal but still it is pretty viable: I put, inside the number I don't want to become a tel: link, the &#8288; HTML entity which is the Word-Joiner invisible character. I tried to stay more semantic (well, at least a sort of) by putting this char in some meaning spot, e.g. for the VAT ID I chose to put it between the different groups of digit according to its format so for an Italian VAT I wrote: 0613605&#8288;048&#8288;8 which renders in 0613605⁠048⁠8 and it is not transformed in a telephone number.

Parsing JSON in Spring MVC using Jackson JSON

The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).

Define a Java class that resembles the JSON you will be expecting.

e.g. this JSON:

{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}

could be mapped to this class:

public class Fizzle{
    private List<String> foo;
    private boolean bar;
    private int baz;
    // getters and setters omitted
}

Now if you have a Controller method like this:

@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
    return new Fozzle(input);
}

and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json.

For a full working example see this previous answer of mine.

Is there 'byte' data type in C++?

No, but since C++11 there is [u]int8_t.

What is the best way to calculate a checksum for a file that is on my machine?

QuickHash an open source tool supporting MD5, SHA1, SHA256, SHA512 and available for the Linux, Windows, and Apple Mac.

https://sourceforge.net/projects/quickhash/

Jquery check if element is visible in viewport

You can see this example.

// Is this element visible onscreen?
var visible = $(#element).visible( detectPartial );

detectPartial :

  • True : the entire element is visible
  • false : part of the element is visible

visible is boolean variable which indicates if the element is visible or not.

GET and POST methods with the same Action name in the same Controller

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}

Also see "How a Method Becomes An Action"

Converting from hex to string

string str = "47-61-74-65-77-61-79-53-65-72-76-65-72";
string[] parts = str.Split('-');

foreach (string val in parts)
{ 
    int x;
    if (int.TryParse(val, out x))
    {
         Console.Write(string.Format("{0:x2} ", x);
    }
}
Console.WriteLine();

You can split the string at the -
Convert the text to ints (int.TryParse)
Output the int as a hex string {0:x2}

What is Scala's yield?

It is used in sequence comprehensions (like Python's list-comprehensions and generators, where you may use yield too).

It is applied in combination with for and writes a new element into the resulting sequence.

Simple example (from scala-lang)

/** Turn command line arguments to uppercase */
object Main {
  def main(args: Array[String]) {
    val res = for (a <- args) yield a.toUpperCase
    println("Arguments: " + res.toString)
  }
}

The corresponding expression in F# would be

[ for a in args -> a.toUpperCase ]

or

from a in args select a.toUpperCase 

in Linq.

Ruby's yield has a different effect.

Vertical dividers on horizontal UL menu

.last { border-right: none

.last { border-right: none !important; }

Creating a file only if it doesn't exist in Node.js

You can do something like this:

function writeFile(i){
    var i = i || 0;
    var fileName = 'a_' + i + '.jpg';
    fs.exists(fileName, function (exists) {
        if(exists){
            writeFile(++i);
        } else {
            fs.writeFile(fileName);
        }
    });
}

How can I rebuild indexes and update stats in MySQL innoDB?

This is done with

ANALYZE TABLE table_name;

Read more about it here.

ANALYZE TABLE analyzes and stores the key distribution for a table. During the analysis, the table is locked with a read lock for MyISAM, BDB, and InnoDB. This statement works with MyISAM, BDB, InnoDB, and NDB tables.

How to align an indented line in a span that wraps into multiple lines?

span is a inline element which means if you use <br/> it'll b considered as one line anyway.

Change span to a block element or add display:block to your class.

http://www.jsfiddle.net/tZtpr/1/

Extract filename and extension in Bash

Ok so if I understand correctly, the problem here is how to get the name and the full extension of a file that has multiple extensions, e.g., stuff.tar.gz.

This works for me:

fullfile="stuff.tar.gz"
fileExt=${fullfile#*.}
fileName=${fullfile%*.$fileExt}

This will give you stuff as filename and .tar.gz as extension. It works for any number of extensions, including 0. Hope this helps for anyone having the same problem =)

Return single column from a multi-dimensional array

join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))

What is __pycache__?

The python interpreter compiles the *.py script file and saves the results of the compilation to the __pycache__ directory.

When the project is executed again, if the interpreter identifies that the *.py script has not been modified, it skips the compile step and runs the previously generated *.pyc file stored in the __pycache__ folder.

When the project is complex, you can make the preparation time before the project is run shorter. If the program is too small, you can ignore that by using python -B abc.py with the B option.

Write to file, but overwrite it if it exists

To overwrite one file's content to another file. use cat eg.

echo  "this is foo" > foobar.txt
cat foobar.txt

echo "this is bar" > bar.txt
cat bar.txt

Now to overwrite foobar we can use a cat command as below

cat bar.txt >> foobar.txt
cat foobar.txt

enter image description here

XDocument or XmlDocument

As mentioned elsewhere, undoubtedly, Linq to Xml makes creation and alteration of xml documents a breeze in comparison to XmlDocument, and the XNamespace ns + "elementName" syntax makes for pleasurable reading when dealing with namespaces.

One thing worth mentioning for xsl and xpath die hards to note is that it IS possible to still execute arbitrary xpath 1.0 expressions on Linq 2 Xml XNodes by including:

using System.Xml.XPath;

and then we can navigate and project data using xpath via these extension methods:

For instance, given the Xml document:

<xml>
    <foo>
        <baz id="1">10</baz>
        <bar id="2" special="1">baa baa</bar>
        <baz id="3">20</baz>
        <bar id="4" />
        <bar id="5" />
    </foo>
    <foo id="123">Text 1<moo />Text 2
    </foo>
</xml>

We can evaluate:

var node = xele.XPathSelectElement("/xml/foo[@id='123']");
var nodes = xele.XPathSelectElements(
"//moo/ancestor::xml/descendant::baz[@id='1']/following-sibling::bar[not(@special='1')]");
var sum = xele.XPathEvaluate("sum(//foo[not(moo)]/baz)");

Fill background color left to right CSS

If you are like me and need to change color of text itself also while in the same time filling the background color check my solution.

Steps to create:

  1. Have two text, one is static colored in color on hover, and the other one in default state color which you will be moving on hover
  2. On hover move wrapper of the not static one text while in the same time move inner text of that wrapper to the opposite direction.
  3. Make sure to add overflow hidden where needed

Good thing about this solution:

  • Support IE9, uses only transform
  • Button (or element you are applying animation) is fluid in width, so no fixed values are being used here

Not so good thing about this solution:

  • A really messy markup, could be solved by using pseudo elements and att(data)?
  • There is some small glitch in animation when having more then one button next to each other, maybe it could be easily solved but I didn't take much time to investigate yet.

Check the pen ---> https://codepen.io/nikolamitic/pen/vpNoNq

<button class="btn btn--animation-from-right">
  <span class="btn__text-static">Cover left</span>
  <div class="btn__text-dynamic">
    <span class="btn__text-dynamic-inner">Cover left</span>
  </div>
</button>

.btn {
  padding: 10px 20px;
  position: relative;

  border: 2px solid #222;
  color: #fff;
  background-color: #222;
  position: relative;

  overflow: hidden;
  cursor: pointer;

  text-transform: uppercase;
  font-family: monospace;
  letter-spacing: -1px;

  [class^="btn__text"] {
    font-size: 24px;
  }

  .btn__text-dynamic,
  .btn__text-dynamic-inner {    
    display: flex;
    justify-content: center;
    align-items: center;

    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    z-index: 2;

    transition: all ease 0.5s;
  }

  .btn__text-dynamic {
    background-color: #fff;
    color: #222;

    overflow: hidden;
  }

  &:hover {
    .btn__text-dynamic {
      transform: translateX(-100%);
    }
    .btn__text-dynamic-inner {
      transform: translateX(100%);
    }
  }
}

.btn--animation-from-right {
    &:hover {
    .btn__text-dynamic {
      transform: translateX(100%);
    }
    .btn__text-dynamic-inner {
      transform: translateX(-100%);
    }
  }
}

You can remove .btn--animation-from-right modifier if you want to animate to the left.

How to use "svn export" command to get a single file from the repository?

Guessing from your directory name, you are trying to access the repository on the local filesystem. You still need to use URL syntax to access it:

svn export file:///e:/repositories/process/test.txt c:\test.txt

PHP PDO: charset, set names?

I test this code and

$db=new PDO('mysql:host=localhost;dbname=cwDB','root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$sql="select * from products  ";
$stmt=$db->prepare($sql);
$stmt->execute();
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){                  
    $id=$result['id'];
}

How to reload current page?

Not really refreshing the page but thought it would help someone else out there looking for something simple

ngOnInit(){
    startUp()
}

startUp(){
    // Codes
}

refresh(){
    // Code to destroy child component
    startUp()
}

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

Here is the solution and the best practice:

You need to create a resources folder where you can keep all your files you want to copy.

+-- Dockerfile
+-- resources
¦     +-- file1.txt
¦     +-- file2.js

The command for copying files should be specified this way:

COPY resources /root/folder/

where

*resources - your local folder which you created in the same folder where Dockerfile is

*/root/folder/ - folder at your container

How to return data from promise

One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).

What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then() on the promise, and the result will be there when the promise has been resolved.

Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
http://www.html5rocks.com/en/tutorials/es6/promises/

How can I handle the warning of file_get_contents() function in PHP?

One alternative is to suppress the error and also throw an exception which you can catch later. This is especially useful if there are multiple calls to file_get_contents() in your code, since you don't need to suppress and handle all of them manually. Instead, several calls can be made to this function in a single try/catch block.

// Returns the contents of a file
function file_contents($path) {
    $str = @file_get_contents($path);
    if ($str === FALSE) {
        throw new Exception("Cannot access '$path' to read contents.");
    } else {
        return $str;
    }
}

// Example
try {
    file_contents("a");
    file_contents("b");
    file_contents("c");
} catch (Exception $e) {
    // Deal with it.
    echo "Error: " , $e->getMessage();
}

Vertical (rotated) text in HTML table

_x000D_
_x000D_
.box_rotate {_x000D_
     -moz-transform: rotate(7.5deg);  /* FF3.5+ */_x000D_
       -o-transform: rotate(7.5deg);  /* Opera 10.5 */_x000D_
  -webkit-transform: rotate(7.5deg);  /* Saf3.1+, Chrome */_x000D_
             filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083);  /* IE6,IE7 */_x000D_
         -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */_x000D_
    }
_x000D_
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>_x000D_
<div class="box_rotate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>_x000D_
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>
_x000D_
_x000D_
_x000D_

Taken from http://css3please.com/

As of 2017, the aforementioned site has simplified the rule set to drop legacy Internet Explorer filter and rely more in the now standard transform property:

_x000D_
_x000D_
.box_rotate {_x000D_
  -webkit-transform: rotate(7.5deg);  /* Chrome, Opera 15+, Safari 3.1+ */_x000D_
      -ms-transform: rotate(7.5deg);  /* IE 9 */_x000D_
          transform: rotate(7.5deg);  /* Firefox 16+, IE 10+, Opera */_x000D_
}
_x000D_
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>_x000D_
<div class="box_rotate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>_x000D_
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div>
_x000D_
_x000D_
_x000D_

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

You need to ensure that auto-commit on the Connection is turned off, or setFetchSize will have no effect.

dbConnection.setAutoCommit(false);

Edit: Remembered that when I used this fix it was Postgres-specific, but hopefully it will still work for SQL Server.

Iterate a list with indexes in Python

Here it is a solution using map function:

>>> a = [3, 7, 19]
>>> map(lambda x: (x, a[x]), range(len(a)))
[(0, 3), (1, 7), (2, 19)]

And a solution using list comprehensions:

>>> a = [3,7,19]
>>> [(x, a[x]) for x in range(len(a))]
[(0, 3), (1, 7), (2, 19)]

How can I use UserDefaults in Swift?

ref: NSUserdefault objectTypes

Swift 3 and above

Store

UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key")  //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject

Retrieve

 UserDefaults.standard.bool(forKey: "Key")
 UserDefaults.standard.integer(forKey: "Key")
 UserDefaults.standard.string(forKey: "Key")

Remove

 UserDefaults.standard.removeObject(forKey: "Key")

Remove all Keys

 if let appDomain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: appDomain)
 }

Swift 2 and below

Store

NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "yourkey")
NSUserDefaults.standardUserDefaults().synchronize()

Retrieve

  var returnValue: [NSString]? = NSUserDefaults.standardUserDefaults().objectForKey("yourkey") as? [NSString]

Remove

 NSUserDefaults.standardUserDefaults().removeObjectForKey("yourkey")


Register

registerDefaults: adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a "fallback" value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them.

Default values from Defaults Configuration Files will automatically be registered.

for example detect the app from launch , create the struct for save launch

struct DetectLaunch {
static let keyforLaunch = "validateFirstlunch"
static var isFirst: Bool {
    get {
        return UserDefaults.standard.bool(forKey: keyforLaunch)
    }
    set {
        UserDefaults.standard.set(newValue, forKey: keyforLaunch)
    }
}
}

Register default values on app launch:

UserDefaults.standard.register(defaults: [
        DetectLaunch.isFirst: true
    ])

remove the value on app termination:

func applicationWillTerminate(_ application: UIApplication) {
    DetectLaunch.isFirst = false

}

and check the condition as

if DetectLaunch.isFirst {
  // app launched from first
}

UserDefaults suite name

another one property suite name, mostly its used for App Groups concept, the example scenario I taken from here :

The use case is that I want to separate my UserDefaults (different business logic may require Userdefaults to be grouped separately) by an identifier just like Android's SharedPreferences. For example, when a user in my app clicks on logout button, I would want to clear his account related defaults but not location of the the device.

let user = UserDefaults(suiteName:"User")

use of userDefaults synchronize, the detail info has added in the duplicate answer.

Auto insert date and time in form input field?

It sounds like you are going to be storing the value that input field contains after the form is submitted, which means you are using a scripting language. I would use it instead of JavaScript as most scripting languages have better time/date formatting options. In PHP you could do something like this:

<input id="date" name="date" value="<?php echo date("M j, Y - g:i"); ?>"/>

Which would fill the field with "Jun 16, 2009 - 8:58"

What do parentheses surrounding an object/function/class declaration mean?

Juts to follow up on what Andy Hume and others have said:

The '()' surrounding the anonymous function is the 'grouping operator' as defined in section 11.1.6 of the ECMA spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.

Taken verbatim from the docs:

11.1.6 The Grouping Operator

The production PrimaryExpression : ( Expression ) is evaluated as follows:

  1. Return the result of evaluating Expression. This may be of type Reference.

In this context the function is treated as an expression.

com.sun.jdi.InvocationException occurred invoking method

Disabling 'Show Logical Structure' button/icon of the upper right corner of the variables window in the eclipse debugger resolved it, in my case.

How to call Makefile from another Makefile?

I'm not really too clear what you are asking, but using the -f command line option just specifies a file - it doesn't tell make to change directories. If you want to do the work in another directory, you need to cd to the directory:

clean:
    cd gtest-1.4.0 && $(MAKE) clean

Note that each line in Makefile runs in a separate shell, so there is no need to change the directory back.

Non-Static method cannot be referenced from a static context with methods and variables

You should place Scanner input = new Scanner (System.in); into the main method rather than creating the input object outside.

Set margins in a LinearLayout programmatically

Try this

 LayoutParams params = new LayoutParams(
            LayoutParams.WRAP_CONTENT,      
            LayoutParams.WRAP_CONTENT
    );
    params.setMargins(left, top, right, bottom);
    yourbutton.setLayoutParams(params);

Capture close event on Bootstrap Modal

This is worked for me, anyone can try it

$("#myModal").on("hidden.bs.modal", function () {
    for (instance in CKEDITOR.instances)
        CKEDITOR.instances[instance].destroy();
    $('#myModal .modal-body').html('');    
});

you can open ckEditor in Modal window

How to check if an Object is a Collection Type in Java?

if (x instanceof Collection<?>){
}

if (x instanceof Map<?,?>){
}

Tokenizing strings in C

You can simplify the code by introducing an extra variable.

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

int main()
{
    char str[100], *s = str, *t = NULL;

    strcpy(str, "a space delimited string");
    while ((t = strtok(s, " ")) != NULL) {
        s = NULL;
        printf(":%s:\n", t);
    }
    return 0;
}

Using sed to mass rename files

 ls F00001-0708-*|sed 's|^F0000\(.*\)|mv & F000\1|' | bash

How to convert a Title to a URL slug in jQuery?

Yet another one. Short and keeps special characters:

imaginação é mato => imaginacao-e-mato

function slugify (text) {
  const a = 'àáäâãèéëêìíïîòóöôùúüûñçßÿœærsn?????u?z?·/_,:;'
  const b = 'aaaaaeeeeiiiioooouuuuncsyoarsnpwgnmuxzh------'
  const p = new RegExp(a.split('').join('|'), 'g')

  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(p, c =>
        b.charAt(a.indexOf(c)))     // Replace special chars
    .replace(/&/g, '-and-')         // Replace & with 'and'
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '')             // Trim - from end of text
}

How do I convert a long to a string in C++?

   #include <sstream>


   ....

    std::stringstream ss;
    ss << a_long_int;  // or any other type
    std::string result=ss.str();   // use .str() to get a string back

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

For anyone using MySQL:

If you head into your PHPMYADMIN webpage and navigate to the table that has the foreign key you want to update, all you have to do is click the Relational view located in the Structure tab and change the On delete select menu option to Cascade.

Image shown below:

enter image description here

Entity Framework code first unique column

In Entity Framework 6.1+ you can use this attribute on your model:

[Index(IsUnique=true)]

You can find it in this namespace:

using System.ComponentModel.DataAnnotations.Schema;

If your model field is a string, make sure it is not set to nvarchar(MAX) in SQL Server or you will see this error with Entity Framework Code First:

Column 'x' in table 'dbo.y' is of a type that is invalid for use as a key column in an index.

The reason is because of this:

SQL Server retains the 900-byte limit for the maximum total size of all index key columns."

(from: http://msdn.microsoft.com/en-us/library/ms191241.aspx )

You can solve this by setting a maximum string length on your model:

[StringLength(450)]

Your model will look like this now in EF CF 6.1+:

public class User
{
   public int UserId{get;set;}
   [StringLength(450)]
   [Index(IsUnique=true)]
   public string UserName{get;set;}
}

Update:

if you use Fluent:

  public class UserMap : EntityTypeConfiguration<User>
  {
    public UserMap()
    {
      // ....
      Property(x => x.Name).IsRequired().HasMaxLength(450).HasColumnAnnotation("Index", new IndexAnnotation(new[] { new IndexAttribute("Index") { IsUnique = true } }));
    }
  }

and use in your modelBuilder:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  // ...
  modelBuilder.Configurations.Add(new UserMap());
  // ...
}

Update 2

for EntityFrameworkCore see also this topic: https://github.com/aspnet/EntityFrameworkCore/issues/1698

Update 3

for EF6.2 see: https://github.com/aspnet/EntityFramework6/issues/274

Update 4

ASP.NET Core Mvc 2.2 with EF Core:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Unique { get; set; }

rename the columns name after cbind the data

Try:

colnames(merger)[1] <- "Date"

Example

Here is a simple example:

a <- 1:10
b <- cbind(a, a, a)
colnames(b)

# change the first one
colnames(b)[1] <- "abc"

# change all colnames
colnames(b) <- c("aa", "bb", "cc")