Programs & Examples On #Remember me

What is the best way to implement "remember me" for a website?

Investigating persistent sessions myself I have found that it's simply not worth the security risk. Use it if you absolutely have to, but you should consider such a session only weakly authenticated and force a new login for anything that could be of value to an attacker.

The reason being of course is that your cookies containing your persistent session are so easily stolen.

4 ways to steal your cookies (from a comment by Jens Roland on the page @splattne based his answer on):

  1. By intercepting it over an unsecure line (packet sniffing / session hijacking)
  2. By directly accessing the user's browser (via either malware or physical access to the box)
  3. By reading it from the server database (probably SQL Injection, but could be anything)
  4. By an XSS hack (or similar client-side exploit)

"Keep Me Logged In" - the best approach

Introduction

Your title “Keep Me Logged In” - the best approach make it difficult for me to know where to start because if you are looking at best approach then you would have to consideration the following :

  • Identification
  • Security

Cookies

Cookies are vulnerable, Between common browser cookie-theft vulnerabilities and cross-site scripting attacks we must accept that cookies are not safe. To help improve security you must note that php setcookies has additional functionality such as

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

  • secure (Using HTTPS connection)
  • httponly (Reduce identity theft through XSS attack)

Definitions

  • Token ( Unpredictable random string of n length eg. /dev/urandom)
  • Reference ( Unpredictable random string of n length eg. /dev/urandom)
  • Signature (Generate a keyed hash value using the HMAC method)

Simple Approach

A simple solution would be :

  • User is logged on with Remember Me
  • Login Cookie issued with token & Signature
  • When is returning, Signature is checked
  • If Signature is ok .. then username & token is looked up in the database
  • if not valid .. return to login page
  • If valid automatically login

The above case study summarizes all example given on this page but they disadvantages is that

  • There is no way to know if the cookies was stolen
  • Attacker may be access sensitive operations such as change of password or data such as personal and baking information etc.
  • The compromised cookie would still be valid for the cookie life span

Better Solution

A better solution would be

  • User is logged in and remember me is selected
  • Generate Token & signature and store in cookie
  • The tokens are random and are only valid for single autentication
  • The token are replace on each visit to the site
  • When a non-logged user visit the site the signature, token and username are verified
  • Remember me login should have limited access and not allow modification of password, personal information etc.

Example Code

// Set privateKey
// This should be saved securely 
$key = 'fc4d57ed55a78de1a7b31e711866ef5a2848442349f52cd470008f6d30d47282';
$key = pack("H*", $key); // They key is used in binary form

// Am Using Memecahe as Sample Database
$db = new Memcache();
$db->addserver("127.0.0.1");

try {
    // Start Remember Me
    $rememberMe = new RememberMe($key);
    $rememberMe->setDB($db); // set example database

    // Check if remember me is present
    if ($data = $rememberMe->auth()) {
        printf("Returning User %s\n", $data['user']);

        // Limit Acces Level
        // Disable Change of password and private information etc

    } else {
        // Sample user
        $user = "baba";

        // Do normal login
        $rememberMe->remember($user);
        printf("New Account %s\n", $user);
    }
} catch (Exception $e) {
    printf("#Error  %s\n", $e->getMessage());
}

Class Used

class RememberMe {
    private $key = null;
    private $db;

    function __construct($privatekey) {
        $this->key = $privatekey;
    }

    public function setDB($db) {
        $this->db = $db;
    }

    public function auth() {

        // Check if remeber me cookie is present
        if (! isset($_COOKIE["auto"]) || empty($_COOKIE["auto"])) {
            return false;
        }

        // Decode cookie value
        if (! $cookie = @json_decode($_COOKIE["auto"], true)) {
            return false;
        }

        // Check all parameters
        if (! (isset($cookie['user']) || isset($cookie['token']) || isset($cookie['signature']))) {
            return false;
        }

        $var = $cookie['user'] . $cookie['token'];

        // Check Signature
        if (! $this->verify($var, $cookie['signature'])) {
            throw new Exception("Cokies has been tampared with");
        }

        // Check Database
        $info = $this->db->get($cookie['user']);
        if (! $info) {
            return false; // User must have deleted accout
        }

        // Check User Data
        if (! $info = json_decode($info, true)) {
            throw new Exception("User Data corrupted");
        }

        // Verify Token
        if ($info['token'] !== $cookie['token']) {
            throw new Exception("System Hijacked or User use another browser");
        }

        /**
         * Important
         * To make sure the cookie is always change
         * reset the Token information
         */

        $this->remember($info['user']);
        return $info;
    }

    public function remember($user) {
        $cookie = [
                "user" => $user,
                "token" => $this->getRand(64),
                "signature" => null
        ];
        $cookie['signature'] = $this->hash($cookie['user'] . $cookie['token']);
        $encoded = json_encode($cookie);

        // Add User to database
        $this->db->set($user, $encoded);

        /**
         * Set Cookies
         * In production enviroment Use
         * setcookie("auto", $encoded, time() + $expiration, "/~root/",
         * "example.com", 1, 1);
         */
        setcookie("auto", $encoded); // Sample
    }

    public function verify($data, $hash) {
        $rand = substr($hash, 0, 4);
        return $this->hash($data, $rand) === $hash;
    }

    private function hash($value, $rand = null) {
        $rand = $rand === null ? $this->getRand(4) : $rand;
        return $rand . bin2hex(hash_hmac('sha256', $value . $rand, $this->key, true));
    }

    private function getRand($length) {
        switch (true) {
            case function_exists("mcrypt_create_iv") :
                $r = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
                break;
            case function_exists("openssl_random_pseudo_bytes") :
                $r = openssl_random_pseudo_bytes($length);
                break;
            case is_readable('/dev/urandom') : // deceze
                $r = file_get_contents('/dev/urandom', false, null, 0, $length);
                break;
            default :
                $i = 0;
                $r = "";
                while($i ++ < $length) {
                    $r .= chr(mt_rand(0, 255));
                }
                break;
        }
        return substr(bin2hex($r), 0, $length);
    }
}

Testing in Firefox & Chrome

enter image description here

Advantage

  • Better Security
  • Limited access for attacker
  • When cookie is stolen its only valid for single access
  • When next the original user access the site you can automatically detect and notify the user of theft

Disadvantage

  • Does not support persistent connection via multiple browser (Mobile & Web)
  • The cookie can still be stolen because the user only gets the notification after the next login.

Quick Fix

  • Introduction of approval system for each system that must have persistent connection
  • Use multiple cookies for the authentication

Multiple Cookie Approach

When an attacker is about to steal cookies the only focus it on a particular website or domain eg. example.com

But really you can authenticate a user from 2 different domains (example.com & fakeaddsite.com) and make it look like "Advert Cookie"

  • User Logged on to example.com with remember me
  • Store username, token, reference in cookie
  • Store username, token, reference in Database eg. Memcache
  • Send refrence id via get and iframe to fakeaddsite.com
  • fakeaddsite.com uses the reference to fetch user & token from Database
  • fakeaddsite.com stores the signature
  • When a user is returning fetch signature information with iframe from fakeaddsite.com
  • Combine it data and do the validation
  • ..... you know the remaining

Some people might wonder how can you use 2 different cookies ? Well its possible, imagine example.com = localhost and fakeaddsite.com = 192.168.1.120. If you inspect the cookies it would look like this

enter image description here

From the image above

  • The current site visited is localhost
  • It also contains cookies set from 192.168.1.120

192.168.1.120

  • Only accepts defined HTTP_REFERER
  • Only accepts connection from specified REMOTE_ADDR
  • No JavaScript, No content but consist nothing rather than sign information and add or retrieve it from cookie

Advantage

  • 99% percent of the time you have tricked the attacker
  • You can easily lock the account in the attacker first attempt
  • Attack can be prevented even before the next login like the other methods

Disadvantage

  • Multiple Request to server just for a single login

Improvement

  • Done use iframe use ajax

how to replace characters in hive?

There is no OOTB feature at this moment which allows this. One way to achieve that could be to write a custom InputFormat and/or SerDe that will do this for you. You might this JIRA useful : https://issues.apache.org/jira/browse/HIVE-3751. (not related directly to your problem though).

How to get year and month from a date - PHP

I'm using these function to get year, month, day from the date

you should put them in a class

    public function getYear($pdate) {
        $date = DateTime::createFromFormat("Y-m-d", $pdate);
        return $date->format("Y");
    }

    public function getMonth($pdate) {
        $date = DateTime::createFromFormat("Y-m-d", $pdate);
        return $date->format("m");
    }

    public function getDay($pdate) {
        $date = DateTime::createFromFormat("Y-m-d", $pdate);
        return $date->format("d");
    }

Setting the classpath in java using Eclipse IDE

Try this:

Project -> Properties -> Java Build Path -> Add Class Folder.

If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.

What is the best way to get all the divisors of a number?

For me this works fine and is also clean (Python 3)

def divisors(number):
    n = 1
    while(n<number):
        if(number%n==0):
            print(n)
        else:
            pass
        n += 1
    print(number)

Not very fast but returns divisors line by line as you wanted, also you can do list.append(n) and list.append(number) if you really want to

Abort a Git Merge

as long as you did not commit you can type

git merge --abort

just as the command line suggested.

nginx upload client_max_body_size issue

From the documentation:

It is necessary to keep in mind that the browsers do not know how to correctly show this error.

I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.

How to get last 7 days data from current datetime to last 7 days in sql server

DATEADD and GETDATE functions might not work in MySQL database. so if you are working with MySQL database, then the following command may help you.

select id, NewsHeadline as news_headline,    
NewsText as news_text,    
state, CreatedDate as created_on    
from News    
WHERE CreatedDate>= DATE_ADD(CURDATE(), INTERVAL -3 DAY);

I hope it will help you

Delaying AngularJS route change until model loaded to prevent flicker

I have had a complex multi-level sliding panel interface, with disabled screen layer. Creating directive on disable screen layer that would create click event to execute the state like

$state.go('account.stream.social.view');

were producing a flicking effect. history.back() instead of it worked ok, however its not always back in history in my case. SO what I find out is that if I simply create attribute href on my disable screen instead of state.go , worked like a charm.

<a class="disable-screen" back></a>

Directive 'back'

app.directive('back', [ '$rootScope', function($rootScope) {

    return {
        restrict : 'A',
        link : function(scope, element, attrs) {
            element.attr('href', $rootScope.previousState.replace(/\./gi, '/'));
        }
    };

} ]);

app.js I just save previous state

app.run(function($rootScope, $state) {      

    $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {         

        $rootScope.previousState = fromState.name;
        $rootScope.currentState = toState.name;


    });
});

SQL grammar for SELECT MIN(DATE)

An aggregate function requires a GROUP BY in standard SQL

This is "Get minimum date per title" in plain language

SELECT title, MIN(date) FROM table GROUP BY title

Most RDBMS and the standard require that column is either in the GROUP BY or in a functions (MIN, COUNT etc): MySQL is the notable exception with some extensions that give unpredictable behaviour

String to Dictionary in Python

This data is JSON! You can deserialize it using the built-in json module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson module.

import json    # or `import simplejson as json` if on Python < 2.6

json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string)    # obj now contains a dict of the data

How to pass List<String> in post method using Spring MVC?

I had the same use case, You can change your method defination in the following way :

@RequestMapping(value = "/saveFruits", method = RequestMethod.POST, 
    consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody Map<String,List<String>> fruits) {
    ..
}

The only problem is it accepts any key in place of "fruits" but You can easily get rid of a wrapper if it is not big functionality.

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Failed to execute removeChild on Node

Your myCoolDiv element isn't a child of the player container. It's a child of the div you created as a wrapper for it (markerDiv in the first part of the code). Which is why it fails, removeChild only removes children, not descendants.

You'd want to remove that wrapper div, or not add it at all.

Here's the "not adding it at all" option:

_x000D_
_x000D_
var markerDiv = document.createElement("div");_x000D_
markerDiv.innerHTML = "<div id='MyCoolDiv' style='color: #2b0808'>123</div>";_x000D_
document.getElementById("playerContainer").appendChild(markerDiv.firstChild);_x000D_
// -------------------------------------------------------------^^^^^^^^^^^_x000D_
_x000D_
setTimeout(function(){ _x000D_
    var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

Or without using the wrapper (although it's quite handy for parsing that HTML):

_x000D_
_x000D_
var myCoolDiv = document.createElement("div");_x000D_
// Don't reall need this: myCoolDiv.id = "MyCoolDiv";_x000D_
myCoolDiv.style.color = "#2b0808";_x000D_
myCoolDiv.appendChild(_x000D_
  document.createTextNode("123")_x000D_
);_x000D_
document.getElementById("playerContainer").appendChild(myCoolDiv);_x000D_
_x000D_
setTimeout(function(){ _x000D_
    // No need for this, we already have it from the above:_x000D_
    // var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

$(this).serialize() -- How to add a value?

Instead of

 data: $(this).serialize() + '&=NonFormValue' + NonFormValue,

you probably want

 data: $(this).serialize() + '&NonFormValue=' + NonFormValue,

You should be careful to URL-encode the value of NonFormValue if it might contain any special characters.

Exception of type 'System.OutOfMemoryException' was thrown. Why?

It runs successfully the first time, but if I run it again, I keep getting a System.OutOfMemoryException. What are some reasons this could be happening?

Regardless of what the others have said, the error has nothing to do with forgetting to dispose your DBCommand or DBConnection, and you will not fix your error by disposing of either of them.

The error has everything to do with your dataset which contains nearly 600,000 rows of data. Apparently your dataset consumes more than 50% of the available memory on your machine. Clearly, you'll run out of memory when you return another dataset of the same size before the first one has been garbage collected. Simple as that.

You can remedy this problem in a few ways:

  • Consider returning fewer records. I personally can't imagine a time when returning 600K records has ever been useful to a user. To minimize the records returned, try:

    • Limiting your query to the first 1000 records. If there are more than 1000 results returned from the query, inform the user to narrow their search results.

    • If your users really insist on seeing that much data at once, try paging the data. Remember: Google never shows you all 22 bajillion results of a search at once, it shows you 20 or so records at a time. Google probably doesn't hold all 22 bajillion results in memory at once, it probably finds its more memory efficient to requery its database to generate a new page.

  • If you just need to iterate through the data and you don't need random access, try returning a datareader instead. A datareader only loads one record into memory at a time.

If none of those are an option, then you need to force .NET to free up the memory used by the dataset before calling your method using one of these methods:

  • Remove all references to your old dataset. Anything holding on to a refenence of your dataset will prevent it from being reclaimed by memory.

  • If you can't null all the references to your dataset, clear all of the rows from the dataset and any objects bound to those rows instead. This removes references to the datarows and allows them to be eaten by the garbage collector.

I don't believe you'll need to call GC.Collect() to force a gen cycle. Not only is it generally a bad idea to call GC.Collect(), because sufficient memory pressure will cause .NET invoke the garbage collector on its own.

Note: calling Dispose on your dataset does not free any memory, nor does it invoke the garbage collector, nor does it remove a reference to your dataset. Dispose is used to clean up unmanaged resources, but the DataSet does not have any unmanaged resources. It only implements IDispoable because it inherents from MarshalByValueComponent, so the Dispose method on the dataset is pretty much useless.

No Exception while type casting with a null in java

You can cast null to any reference type without getting any exception.

The println method does not throw null pointer because it first checks whether the object is null or not. If null then it simply prints the string "null". Otherwise it will call the toString method of that object.

Adding more details: Internally print methods call String.valueOf(object) method on the input object. And in valueOf method, this check helps to avoid null pointer exception:

return (obj == null) ? "null" : obj.toString();

For rest of your confusion, calling any method on a null object should throw a null pointer exception, if not a special case.

TypeScript add Object to array with push

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

Explicitly:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

Or implicitly:

export class Pixel {
    constructor(public x: number, public y: number) {}
}

How to programmatically set style attribute in a view

You can do style attributes like so:

Button myButton = new Button(this, null,android.R.attr.buttonBarButtonStyle);

in place of:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn"
    style="?android:attr/buttonBarButtonStyle"

    />

Can an Option in a Select tag carry multiple values?

you can use multiple attribute

<SELECT NAME="Testing" multiple>  
 <OPTION VALUE="1"> One  
 <OPTION VALUE="2"> Two  
 <OPTION VALUE="3"> Three

ORA-00979 not a group by expression

In addition to the other answers, this error can result if there's an inconsistency in an order by clause. For instance:

select 
    substr(year_month, 1, 4)
    ,count(*) as tot
from
    schema.tbl
group by
    substr(year_month, 1, 4)
order by
    year_month

changing minDate option in JQuery DatePicker not working

There is no need to destroy current instance, just refresh.

$('#datepicker')
    .datepicker('option', 'minDate', new Date)
    .datepicker('refresh');

How to construct a std::string from a std::vector<char>?

I like Stefan’s answer (Sep 11 ’13) but would like to make it a bit stronger:

If the vector ends with a null terminator, you should not use (v.begin(), v.end()): you should use v.data() (or &v[0] for those prior to C++17).

If v does not have a null terminator, you should use (v.begin(), v.end()).

If you use begin() and end() and the vector does have a terminating zero, you’ll end up with a string "abc\0" for example, that is of length 4, but should really be only "abc".

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

(Note: root, base, apex domains are all the same thing. Using interchangeably for google-foo.)

Traditionally, to point your apex domain you'd use an A record pointing to your server's IP. This solution doesn't scale and isn't viable for a cloud platform like Heroku, where multiple and frequently changing backends are responsible for responding to requests.

For subdomains (like www.example.com) you can use CNAME records pointing to your-app-name.herokuapp.com. From there on, Heroku manages the dynamic A records behind your-app-name.herokuapp.com so that they're always up-to-date. Unfortunately, the DNS specification does not allow CNAME records on the zone apex (the base domain). (For example, MX records would break as the CNAME would be followed to its target first.)

Back to root domains, the simple and generic solution is to not use them at all. As a fallback measure, some DNS providers offer to setup an HTTP redirect for you. In that case, set it up so that example.com is an HTTP redirect to www.example.com.

Some DNS providers have come forward with custom solutions that allow CNAME-like behavior on the zone apex. To my knowledge, we have DNSimple's ALIAS record and DNS Made Easy's ANAME record; both behave similarly.

Using those, you could setup your records as (using zonefile notation, even tho you'll probably do this on their web user interface):

@   IN ALIAS your-app-name.herokuapp.com.
www IN CNAME your-app-name.herokuapp.com.

Remember @ here is a shorthand for the root domain (example.com). Also mind you that the trailing dots are important, both in zonefiles, and some web user interfaces.

See also:

Remarks:

  • Amazon's Route 53 also has an ALIAS record type, but it's somewhat limited, in that it only works to point within AWS. At the moment I would not recommend using this for a Heroku setup.

  • Some people confuse DNS providers with domain name registrars, as there's a bit of overlap with companies offering both. Mind you that to switch your DNS over to one of the aforementioned providers, you only need to update your nameserver records with your current domain registrar. You do not need to transfer your domain registration.

How do I jump out of a foreach loop in C#?

It's not a direct answer to your question but there is a much easier way to do what you want. If you are using .NET 3.5 or later, at least. It is called Enumerable.Contains

bool found = sList.Contains("ok");

PHP, pass array through POST

Edit If you are asking about security, see my addendum at the bottom Edit

PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.

$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);

This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.

Addendum

I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.

How to migrate GIT repository from one server to a new one

This is a variation on this answer, currently suggested by gitlab to "migrate" a git repository from one server to another.

  1. Let us assume that your old project is called existing_repo, stored in a existing_repo folder.

  2. Create a repo on your new server. We will assume that the url of that new project is git@newserver:newproject.git

  3. Open a command-line interface, and enter the following:

    cd existing_repo
    git remote rename origin old-origin
    git remote add origin git@newserver:newproject.git
    git push -u origin --all
    git push -u origin --tags
    

The benefits of this approach is that you do not delete the branch that corresponds to your old server.

About catching ANY exception

You can but you probably shouldn't:

try:
    do_something()
except:
    print "Caught it!"

However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

Passing std::string by Value or Reference

I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.

Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

This is a warning spit out by build tools for two reasons.
1. One of the plugin is relying on Task instead of TaskProvider, there is nothing much we can do.
2. You have configured usage of task, where as it supports TaskProvider.

WARNING: API 'variant.getGenerateBuildConfig()' is obsolete and has been replaced with 'variant.getGenerateBuildConfigProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance

WARNING: API 'variant.getMergeResources()' is obsolete and has been replaced with 'variant.getMergeResourcesProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance

Look out for snippets as below & update.

android {
    <library|application>Variants.all { variant ->
        /* Disable Generating Build config */
        // variant.generateBuildConfig.enabled = true // <- Deprecated
        variant.generateBuildConfigProvider.configure {
            it.enabled = true // Replacement
        }
    }
}

Similarly, find usages of 'variant.getJavaCompile()' or 'variant.javaCompile', 'variant.getMergeResources()' or 'variant.mergeResources'. Replace as above.

More information at Task Configuration Avoidance

How to remove/delete a large file from commit history in Git repository?

You can do this using the branch filter command:

git filter-branch --tree-filter 'rm -rf path/to/your/file' HEAD

Passing 'this' to an onclick event

Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.

check this fiddle

http://jsfiddle.net/8cvBM/

mysql server port number

try

$conn = mysql_connect($host, $username, $password, $port);

csv.Error: iterator should return strings, not bytes

You open the file in text mode.

More specifically:

ifile  = open('sample.csv', "rt", encoding=<theencodingofthefile>)

Good guesses for encoding is "ascii" and "utf8". You can also leave the encoding off, and it will use the system default encoding, which tends to be UTF8, but may be something else.

CSS : center form in page horizontally and vertically

The accepted answer didn't work with my form, even when I stripped it down to the bare minimum and copied & pasted the code. If anyone else is having this problem, please give my solution a try. Basically, you set Top and Left to 50% as the OP did, but offset the form's container with negative margins on the top and left equal to 50% of the div's height and width, respectively. This moves the center point of the Top and Left coordinates to the center of the form. I will stress that the height and width of the form must be specified (not relative). In this example, a 300x300px form div with margins of -150px on the top and left is perfectly centered no matter the window size:

HTML

<body>
    <div class="login_div">
        <form class="login_form" action="#">
        </form>
    </div>
</body>

CSS

.login_div {
    position: absolute;

    width: 300px;
    height: 300px;

    /* Center form on page horizontally & vertically */
    top: 50%;
    left: 50%;
    margin-top: -150px;
    margin-left: -150px;
}

.login_form {
    width: 300px;
    height: 300px;

    background: gray;
    border-radius: 10px;

    margin: 0;
    padding: 0;
}

JSFiddle

Now, for those wondering why I used a container for the form, it's because I like to have the option of placing other elements in the form's vicinity and having them centered as well. The form container is completely unnecessary in this example, but would definitely be useful in other cases. Hope this helps!

What is the most efficient/elegant way to parse a flat table into a tree?

Assuming that you know that the root elements are zero, here's the pseudocode to output to text:

function PrintLevel (int curr, int level)
    //print the indents
    for (i=1; i<=level; i++)
        print a tab
    print curr \n;
    for each child in the table with a parent of curr
        PrintLevel (child, level+1)


for each elementID where the parentid is zero
    PrintLevel(elementID, 0)

jQuery form input select by id

Why not just:

$('#b').click(function () {
    var val = $(this).val(); 
})

Or if you don't click it (and I guess you won't) and you will use submit button, you can use prev() function either.

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

How to check if a DateTime field is not null or empty?

DateTime is not standard nullable type. If you want assign null to DateTime type of variable, you have to use DateTime? type which supports null value.

If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:

if (dateTimeVariable == default(DateTime))
{
    //do work for dateTimeVariable == null situation
}

How to check if a service is running via batch file and start it, if it is not running?

I just found this thread and wanted to add to the discussion if the person doesn't want to use a batch file to restart services. In Windows there is an option if you go to Services, service properties, then recovery. Here you can set parameters for the service. Like to restart the service if the service stops. Also, you can even have a second fail attempt do something different as in restart the computer.

Remove gutter space for a specific div only

Okay If you want to change the gutter inside one row, but want those (first and last) inner divs to align with the grid surrounding the .no-gutter row, you could copy-paste-merge most answers into the following snippet:

.row.no-gutter [class*='col-']:first-child:not(:only-child) {
    padding-right: 0;
}
.row.no-gutter [class*='col-']:last-child:not(:only-child) {
    padding-left: 0;
}
.row.no-gutter [class*='col-']:not(:first-child):not(:last-child):not(:only-child) {
    padding-right: 0;
    padding-left: 0;
}

If you like to have a smaller gutter instead of completly none, just change the 0's to what you like... (eg: 5px to get 10px gutter).

How to find an available port?

According to Wikipedia, you should use ports 49152 to 65535 if you don't need a 'well known' port.

AFAIK the only way to determine wheter a port is in use is to try to open it.

Remove new lines from string and replace with one empty space

You can try below code will preserve any white-space and new lines in your text.

$str = "
put returns between paragraphs

for linebreak add 2 spaces at end

";

echo preg_replace( "/\r|\n/", "", $str );

Recommended SQL database design for tags or tagging

Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly.

Table: Item
Columns: ItemID, Title, Content

Table: Tag
Columns: TagID, Title

Table: ItemTag
Columns: ItemID, TagID

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

Percentage Height HTML 5/CSS

bobince's answer will let you know in which cases "height: XX%;" will or won't work.

If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom. Example for square:

<div class="square-container">
  <div class="square-content">
    <!-- put your content in here -->
  </div>
</div>

.square-container {  /* any display: block; element */
  position: relative;
  height: 0;
  padding-bottom: 100%; /* of parent width */
}
.square-content {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
}

The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video

how to check if a datareader is null or empty

if (myReader["Additional"] != DBNull.Value)
{
    ltlAdditional.Text = "contains data";
}
else
{
     ltlAdditional.Text = "is null";
}

How to edit incorrect commit message in Mercurial?

Update: Mercurial has added --amend which should be the preferred option now.


You can rollback the last commit (but only the last one) with hg rollback and then reapply it.

Important: this permanently removes the latest commit (or pull). So if you've done a hg update that commit is no longer in your working directory then it's gone forever. So make a copy first.

Other than that, you cannot change the repository's history (including commit messages), because everything in there is check-summed. The only thing you could do is prune the history after a given changeset, and then recreate it accordingly.

None of this will work if you have already published your changes (unless you can get hold of all copies), and you also cannot "rewrite history" that include GPG-signed commits (by other people).

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)

I just removed the head portion in index.html file and it worked fine.This is the head tag in html file

Why do we need to install gulp globally and locally?

Just because I haven't seen it here, if you are on MacOS or Linux, I suggest you add this to your PATH (in your bashrc etc):

node_modules/.bin

With this relative path entry, if you are sitting in the root folder of any node project, you can run any command line tool (eslint, gulp, etc. etc.) without worrying about "global installs" or npm run etc.

Once I did this, I've never installed a module globally.

How to filter input type="file" dialog by specific file type?

Add a custom attribute to <input type="file" file-accept="jpg gif jpeg png bmp"> and read the filenames within javascript that matches the extension provided by the attribute file-accept. This will be kind of bogus, as a text file with any of the above extension will erroneously deteted as image.

Windows equivalent of $export

There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

Try restarting the mysql or starting it if it wasn't started already. Type this within terminal.

mysql.server restart

To auto start go to the following link below:

How to auto-load MySQL on startup on OS X Yosemite / El Capitan

Create an ISO date object in javascript

This worked for me:

_x000D_
_x000D_
var start = new Date("2020-10-15T00:00:00.000+0000");
 //or
start = new date("2020-10-15T00:00:00.000Z");

collection.find({
    start_date:{
        $gte: start
    }
})...etc
_x000D_
_x000D_
_x000D_ new Date(2020,9,15,0,0,0,0) may lead to wrong date: i mean non ISO format (remember javascript count months from 0 to 11 so it's 9 for october)

css divide width 100% to 3 column

Just in case someone is still looking for the answer,

let the browser take care of that. Try this:

  • display: table on the container element.
  • display: table-cell on the child elements.

The browser will evenly divide it whether you have 3 or 10 columns.

EDIT

the container element should also have: table-layout: fixed otherwise the browser will determine the width of each element (most of the time not that bad).

Can you split a stream into two streams?

Shorter version that uses Lombok

import java.util.function.Consumer;
import java.util.function.Predicate;

import lombok.RequiredArgsConstructor;

/**
 * Forks a Stream using a Predicate into postive and negative outcomes.
 */
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PROTECTED)
public class StreamForkerUtil<T> implements Consumer<T> {
    Predicate<T> predicate;
    Consumer<T> positiveConsumer;
    Consumer<T> negativeConsumer;

    @Override
    public void accept(T t) {
        (predicate.test(t) ? positiveConsumer : negativeConsumer).accept(t);
    }
}

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

From ISO 8601 String to Java Date Object

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
sdf.parse("2013-09-29T18:46:19Z"); //prints-> Mon Sep 30 02:46:19 CST 2013

if you don't set TimeZone.getTimeZone("GMT") then it will output Sun Sep 29 18:46:19 CST 2013

From Java Date Object to ISO 8601 String

And to convert Dateobject to ISO 8601 Standard (yyyy-MM-dd'T'HH:mm:ss'Z') use following code

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));           
System.out.println(sdf.format(new Date())); //-prints-> 2015-01-22T03:23:26Z

Also note that without ' ' at Z yyyy-MM-dd'T'HH:mm:ssZ prints 2015-01-22T03:41:02+0000

How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

If you are using Visual Studio Community 2015 and trying to Install GLUT you should place the header file glut.h in C:\Program Files (x86)\Windows Kits\8.1\Include\um\gl

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

I had this problem. Code worked fine when running locally but not when on server. Using psPing (https://technet.microsoft.com/en-us/sysinternals/psping.aspx) I realised the applications port wasn't returning anything. Turned out to be a firewall issue. I hadn't enabled my applications port in the Windows Firewall.

Administrative Tools > Windows Firewall with Advanced Security added my applications port to the Inbound Rules and it started working.

Somehow the application port number had got changed, so took a while to figure out what was going on - so thought I'd share this possibility in case it saves someone else time...

Drawing Circle with OpenGL

Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius

void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
    int i;
    int triangleAmount = 20; //# of triangles used to draw circle

    //GLfloat radius = 0.8f; //radius
    GLfloat twicePi = 2.0f * PI;

    glBegin(GL_TRIANGLE_FAN);
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= triangleAmount; i++) {
        glVertex2f(
            x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
            y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
        );
    }
    glEnd();
}

File count from a folder

The slickest method woud be to use LINQ:

var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories)
                        select file).Count();

SVG Positioning

There is a shorter alternative to the previous answer. SVG Elements can also be grouped by nesting svg elements:

<svg xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink">
  <svg x="10">
    <rect x="10" y="10" height="100" width="100" style="stroke:#ff0000;fill: #0000ff"/>
  </svg>
  <svg x="200">
    <rect x="10" y="10" height="100" width="100" style="stroke:#009900;fill: #00cc00"/>
  </svg>
</svg>

The two rectangles are identical (apart from the colors), but the parent svg elements have different x values.

See http://tutorials.jenkov.com/svg/svg-element.html.

How to debug a Flask app

Running the app in development mode will show an interactive traceback and console in the browser when there is an error. To run in development mode, set the FLASK_ENV=development environment variable then use the flask run command (remember to point FLASK_APP to your app as well).

For Linux, Mac, Linux Subsystem for Windows, Git Bash on Windows, etc.:

export FLASK_APP=myapp
export FLASK_ENV=development
flask run

For Windows CMD, use set instead of export:

set FLASK_ENV=development

For PowerShell, use $env:

$env:FLASK_ENV = "development"

Prior to Flask 1.0, this was controlled by the FLASK_DEBUG=1 environment variable instead.

If you're using the app.run() method instead of the flask run command, pass debug=True to enable debug mode.

Tracebacks are also printed to the terminal running the server, regardless of development mode.

If you're using PyCharm, VS Code, etc., you can take advantage of its debugger to step through the code with breakpoints. The run configuration can point to a script calling app.run(debug=True, use_reloader=False), or point it at the venv/bin/flask script and use it as you would from the command line. You can leave the reloader disabled, but a reload will kill the debugging context and you will have to catch a breakpoint again.

You can also use pdb, pudb, or another terminal debugger by calling set_trace in the view where you want to start debugging.


Be sure not to use too-broad except blocks. Surrounding all your code with a catch-all try... except... will silence the error you want to debug. It's unnecessary in general, since Flask will already handle exceptions by showing the debugger or a 500 error and printing the traceback to the console.

python numpy ValueError: operands could not be broadcast together with shapes

Convert the arrays to matrices, and then perform the multiplication.

X = np.matrix(X)

y = np.matrix(y)

X*y

How to call an async method from a getter or setter?

I think my example below may follow @Stephen-Cleary 's approach but I wanted to give a coded example. This is for use in a data binding context for example Xamarin.

The constructor of the class - or indeed the setter of another property on which it is dependent - may call an async void that will populate the property on completion of the task without the need for an await or block. When it finally gets a value it will update your UI via the NotifyPropertyChanged mechanism.

I'm not certain about any side effects of calling a aysnc void from a constructor. Perhaps a commenter will elaborate on error handling etc.

class MainPageViewModel : INotifyPropertyChanged
{
    IEnumerable myList;

    public event PropertyChangedEventHandler PropertyChanged;

    public MainPageViewModel()
    {

        MyAsyncMethod()

    }

    public IEnumerable MyList
    {
        set
        {
            if (myList != value)
            {
                myList = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("MyList"));
                }
            }
        }
        get
        {
            return myList;
        }
    }

    async void MyAsyncMethod()
    {
        MyList = await DoSomethingAsync();
    }


}

Get a resource using getResource()

One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

How to create two columns on a web page?

Basically you need 3 divs. First as wrapper, second as left and third as right.

.wrapper {
 width:500px;
 overflow:hidden;
}

.left {
 width:250px;
 float:left;
}

.right {
 width:250px;
 float:right;
}

Example how to make 2 columns http://jsfiddle.net/huhu/HDGvN/


CSS Cheat Sheet for reference

What is define([ , function ]) in JavaScript?

That's probably a requireJS module definition

Check here for more details

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

Sublime Text 2 - View whitespace characters

If you really only want to see trailing spaces, this ST2 plugin will do the trick: https://github.com/SublimeText/TrailingSpaces

How do I make a comment in a Dockerfile?

As others have mentioned, comments are referenced with a # and are documented here. However, unlike some languages, the # must be at the beginning of the line. If they occur part way through the line, they are interpreted as an argument and may result in unexpected behavior.

# This is a comment

COPY test_dir target_dir # This is not a comment, it is an argument to COPY

RUN echo hello world # This is an argument to RUN but the shell may ignore it

It should also be noted that parser directives have recently been added to the Dockerfile which have the same syntax as a comment. They need to appear at the top of the file, before any other comments or commands. Originally, this directive was added for changing the escape character to support Windows:

# escape=`

FROM microsoft/nanoserver
COPY testfile.txt c:\
RUN dir c:\

The first line, while it appears to be a comment, is a parser directive to change the escape character to a backtick so that the COPY and RUN commands can use the backslash in the path. A parser directive is also used with BuildKit to change the frontend parser with a syntax line. See the experimental syntax for more details on how this is being used in practice.

With a multi-line command, the commented lines are ignored, but you need to comment out every line individually:

$ cat Dockerfile
FROM busybox:latest
RUN echo first command \
# && echo second command disabled \
 && echo third command

$ docker build .
Sending build context to Docker daemon  23.04kB
Step 1/2 : FROM busybox:latest
 ---> 59788edf1f3e
Step 2/2 : RUN echo first command  && echo third command
 ---> Running in b1177e7b563d
first command
third command
Removing intermediate container b1177e7b563d
 ---> 5442cfe321ac
Successfully built 5442cfe321ac

How to get active user's UserDetails

While Ralphs Answer provides an elegant solution, with Spring Security 3.2 you no longer need to implement your own ArgumentResolver.

If you have a UserDetails implementation CustomUser, you can just do this:

@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal CustomUser customUser) {

    // .. find messages for this User and return them...
}

See Spring Security Documentation: @AuthenticationPrincipal

How can I git stash a specific file?

EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>. For example:

git stash push -m welcome_cart app/views/cart/welcome.thtml

OLD ANSWER:

You can do that using git stash --patch (or git stash -p) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n to skip the files that you don't want to stash, y when you encounter the one that you want to stash, and q to quit and leave the remaining hunks unstashed. a will stash the shown hunk and the rest of the hunks in that file.

Not the most user-friendly approach, but it gets the work done if you really need it.

Using Alert in Response.Write Function in ASP.NET

string str = "Error mEssage";
Response.Write("<script language=javascript>alert('"+str+"');</script>");

Compare and contrast REST and SOAP web services?

SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

REST is over only HTTP

Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

How to make a view with rounded corners?

The CardView worked for me in API 27 in Android Studio 3.0.1. The colorPrimary was referenced in the res/values/colors.xml file and is just an example. For the layout_width of 0dp it will stretch to the width of the parent. You'll have to configure the constraints and width/height to your needs.

<android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:cardCornerRadius="4dp"
    app:cardBackgroundColor="@color/colorPrimary">

    <!-- put your content here -->

</android.support.v7.widget.CardView>

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

in case of a similar issue when I'm creating dockerfile I faced the same scenario:- I used below changed in mysql_connect function as:-

if($CONN = @mysqli_connect($DBHOST, $DBUSER, $DBPASS)){ //mysql_query("SET CHARACTER SET 'gbk'", $CONN);

VC++ fatal error LNK1168: cannot open filename.exe for writing

Restarting Visual Studio solved the problem for me.

Create an ArrayList of unique values

You can easily do this with a Hashmap. You obviously have a key (which is the String data) and some values.

Loop on all your lines and add them to your Map.

Map<String, List<Integer>> map = new HashMap<>();
...
while (s.hasNext()){
  String stringData = ...
  List<Integer> values = ...
  map.put(stringData,values);
}

Note that in this case, you will keep the last occurence of duplicate lines. If you prefer keeping the first occurence and removing the others, you can add a check with Map.containsKey(String stringData); before putting in the map.

AngularJs - ng-model in a SELECT

You can also put the item with the default value selected out of the ng-repeat like follow :

<div ng-app="app" ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
        <option value="yourDefaultValue">Default one</option>
        <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

and don't forget the value atribute if you leave it blank you will have the same issue.

How to clear Facebook Sharer cache?

I found a solution to my problem. You could go to this site:

https://developers.facebook.com/tools/debug

...then put in the URL of the page you want to share, and click "debug". It will automatically extract all the info on your meta tags and also clear the cache.

Reading content from URL with Node.js

the data object is a buffer of bytes. Simply call .toString() to get human-readable code:

console.log( data.toString() );

reference: Node.js buffers

Install opencv for Python 3.3

You can use the following command on the command prompt (cmd) on Windows:

py -3.3 -m pip install opencv-python

I made a video on how to install OpenCV Python on Windows in 1 minute here:

https://www.youtube.com/watch?v=m2-8SHk-1SM

Hope it helps!

Is there a way I can retrieve sa password in sql server 2005

MSSQL have its own database management tool called as "MSSQL Server Management Studio (SSMS)". Here are steps to reset SA password using SSMS :

1] Open SSMS management console, it will prompt for authentication details,

Select Server Type : "Database Engine", Server name : IP / hostname of your MSSQL server Authentication : Windows Authentication

Once you select Authentication type as "Windows Authentication", the user name and password fields will be grayed out and it will allow you to login SQL server without entering login details. Windows Authentication is possible only when you are logged on same server in RDP on which SQL service is present.

2] once you are in, under "Object Explorer" expand Security and then Logins 3] locate and right click on user SA and select Properties 4] under General section enter desired password in front of "Password:" and "Confirm Password:" 5] hit OK at bottom.

This is the easiest and secure way to reset SA password instead of using any third party non secure tools

Why is SQL Server 2008 Management Studio Intellisense not working?

I recently wrote a tip about troubleshooting IntelliSense. The title says SQL Server 2012 but most of the techniques can be applied to earlier versions of Management Studio as well.

http://www.mssqltips.com/sqlservertip/2591/troubleshooting-intellisense-in-sql-server-management-studio-2012/

Comparing two NumPy arrays for equality, element-wise

If you want to check if two arrays have the same shape AND elements you should use np.array_equal as it is the method recommended in the documentation.

Performance-wise don't expect that any equality check will beat another, as there is not much room to optimize comparing two elements. Just for the sake, i still did some tests.

import numpy as np
import timeit

A = np.zeros((300, 300, 3))
B = np.zeros((300, 300, 3))
C = np.ones((300, 300, 3))

timeit.timeit(stmt='(A==B).all()', setup='from __main__ import A, B', number=10**5)
timeit.timeit(stmt='np.array_equal(A, B)', setup='from __main__ import A, B, np', number=10**5)
timeit.timeit(stmt='np.array_equiv(A, B)', setup='from __main__ import A, B, np', number=10**5)
> 51.5094
> 52.555
> 52.761

So pretty much equal, no need to talk about the speed.

The (A==B).all() behaves pretty much as the following code snippet:

x = [1,2,3]
y = [1,2,3]
print all([x[i]==y[i] for i in range(len(x))])
> True

How to find out which processes are using swap space in Linux?

It's not entirely clear if you mean you want to find the process who has most pages swapped out or process who caused most pages to be swapped out.

For the first you may run top and order by swap (press 'Op'), for the latter you can run vmstat and look for non-zero entries for 'so'.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

Create an S3 client object with your credentials

AWS_S3_CREDS = {
    "aws_access_key_id":"your access key", # os.getenv("AWS_ACCESS_KEY")
    "aws_secret_access_key":"your aws secret key" # os.getenv("AWS_SECRET_KEY")
}
s3_client = boto3.client('s3',**AWS_S3_CREDS)

It is always good to get credentials from os environment

To set Environment variables run the following commands in terminal

if linux or mac

$ export AWS_ACCESS_KEY="aws_access_key"
$ export AWS_SECRET_KEY="aws_secret_key"

if windows

c:System\> set AWS_ACCESS_KEY="aws_access_key"
c:System\> set AWS_SECRET_KEY="aws_secret_key"

how to get multiple checkbox value using jquery

To get an array of values from multiple checked checkboxes, use jQuery map/get functions:

$('input[type=checkbox]:checked').map(function(_, el) {
    return $(el).val();
}).get();

This will return array with checked values, like this one: ['1', '2']

Here is working example on jsfiddle: http://jsfiddle.net/7PV2e/

org.hibernate.MappingException: Unknown entity: annotations.Users

I did not find the accepted answer helpful in resolving the exception encountered in my code. And while not technically incorrect, I was also not satisfied with others' suggestions to introduce redundancy:

  • programmatically re-add the mapped class using configuration.addAnnotatedClass(...)
  • create a hbm.xml file and resource mapping in hibernate_test.cfg.xml that were redundant to the existing annotations
  • scan the package where the (already mapped) class exists using external dependencies not mentioned in the original question

However, I found 2 possible solutions that I wanted to share, both of which independently resolved the exception I encountered in my own code.

I was having the same MappingException as @ron (using a very nearly identical HibernateUtil class):

public final class HibernateUtil {

    private static SessionFactory sessionFactory = null;
    private static ServiceRegistry serviceRegistry = null;

    private HibernateUtil() {}

    public static synchronized SessionFactory getSessionFactory() {
        if ( sessionFactory == null ) {
            Configuration configuration = new Configuration().configure("hibernate_test.cfg.xml");
            serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties())
                    .build();
            sessionFactory = configuration.buildSessionFactory( serviceRegistry );
        }
        return sessionFactory;
    }
// exception handling and closeSessionFactory() omitted for brevity
}

Within my hibernate_test.cfg.xml configuration file, I have the required class mapping:

<mapping class="myPackage.Device"/>

And my Device class is properly annotated with the javax.persistence.Entity annotation:

package myPackage.core;
import javax.persistence.*;

@Entity
@Table( name = "devices" )
public class Device {
    //body omitted for brevity
}

Two Possible Solutions:

First, I am using Hibernate 5.2, and for those using Hibernate 5 this solution using a Metadata object to build a SessionFactory should work. It also appears to be the currently recommended native bootstrap mechanism in the Hibernate Getting Started Guide :

public static synchronized SessionFactory getSessionFactory() {
    if ( sessionFactory == null ) {

        // exception handling omitted for brevity

        serviceRegistry = new StandardServiceRegistryBuilder()
                .configure("hibernate_test.cfg.xml")
                .build();

        sessionFactory = new MetadataSources( serviceRegistry )
                    .buildMetadata()
                    .buildSessionFactory();
    }
    return sessionFactory;
}

Second, while Configuration is semi-deprecated in Hibernate 5, @ron didn't say which version of Hibernate he was using, so this solution could also be of value to some.

I found a very subtle change in the order of operations when instantiating and configuring Configuration and ServiceRegistry objects to make all the difference in my own code.

Original order (Configuration created and configured prior to ServiceRegistry):

public static synchronized SessionFactory getSessionFactory() {
    if ( sessionFactory == null ) {

        // exception handling omitted for brevity

        Configuration configuration = new Configuration().configure("hibernate_test.cfg.xml");

        serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings( configuration.getProperties() )
                .build();

        sessionFactory = configuration.buildSessionFactory( serviceRegistry );
    }
    return sessionFactory;
}

New order (ServiceRegistry created and configured prior to Configuration):

public static synchronized SessionFactory getSessionFactory() {
    if ( sessionFactory == null ) {

        // exception handling omitted for brevity

        serviceRegistry = new StandardServiceRegistryBuilder()
                .configure("hibernate_test.cfg.xml")
                .build();

        sessionFactory = new Configuration().buildSessionFactory( serviceRegistry );
    }
    return sessionFactory;
}

At the risk of TLDR, I will also point out that with respect to hibernate_test.cfg.xml my testing suggests that the configuration.getProperties() method only returns <property /> elements, and <mapping /> elements are excluded. This appears consistent with the specific use of the terms 'property' and 'mapping' within the API documentation for Configuration. I will concede that this behaviour may have something to do with the failure of applySettings() to yield the mapping data to the StandardServiceRegistryBuilder. However, this mapping data should already have been parsed during configuration of the Configuration object and available to it when buildSessionFactory() is called. Therefore, I suspect this may be due to implementation-specific details regarding resource precedence when a ServiceRegistry is passed to a Configuration object's buildSessionFactory() method.

I know this question is several years old now, but I hope this answer saves somebody the hours of research I spent in deriving it. Cheers!

IIS Request Timeout on long ASP.NET operation

I'm posting this here, because I've spent like 3 and 4 hours on it, and I've only found answers like those one above, that say do add the executionTime, but it doesn't solve the problem in the case that you're using ASP .NET Core. For it, this would work:

At web.config file, add the requestTimeout attribute at aspNetCore node.

<system.webServer>
  <aspNetCore requestTimeout="00:10:00" ... (other configs goes here) />
</system.webServer>

In this example, I'm setting the value for 10 minutes.

Reference: https://docs.microsoft.com/en-us/aspnet/core/hosting/aspnet-core-module#configuring-the-asp-net-core-module

C convert floating point to int

If you want to round it to lower, just cast it.

float my_float = 42.8f;
int my_int;
my_int = (int)my_float;          // => my_int=42

For other purpose, if you want to round it to nearest, you can make a little function or a define like this:

#define FLOAT_TO_INT(x) ((x)>=0?(int)((x)+0.5):(int)((x)-0.5))

float my_float = 42.8f;
int my_int;
my_int = FLOAT_TO_INT(my_float); // => my_int=43

Be careful, ideally you should verify float is between INT_MIN and INT_MAX before casting it.

Python: converting a list of dictionaries to json

use json library

import json
json.dumps(list)

by the way, you might consider changing variable list to another name, list is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.

Displaying the Error Messages in Laravel after being Redirected from controller

Move all that in kernel.php if just the above method didn't work for you remember you have to move all those lines in kernel.php in addition to the above solution

let me first display the way it is there in the file already..

protected $middleware = [

    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

now what you have to do is

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
     \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [

    ],

    'api' => [
        'throttle:60,1',
    ],
];

i.e.;

enter image description here

Youtube autoplay not working on mobile devices with embedded HTML5 player

Have a look on code below. Tested and found working on Mobile and Tablet devices.

<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

OpenJDK availability for Windows OS

Found all the windows binaries here :

https://github.com/ojdkbuild/ojdkbuild

These Windows binaries are built to keep them as close as possible in behaviour to java-x-openjdk CentOS packages.

JavaScript Nested function

Function-instantiation is allowed inside and outside of functions. Inside those functions, just like variables, the nested functions are local and therefore cannot be obtained from the outside scope.

function foo() {
    function bar() {
        return 1;
    }
    return bar();
}

foo manipulates bar within itself. bar cannot be touched from the outer scope unless it is defined in the outer scope.

So this will not work:

function foo() {
    function bar() {
        return 1;
    }
}

bar(); // throws error: bar is not defined

TypeError: 'float' object is not subscriptable

PriceList[0][1][2][3][4][5][6]

This says: go to the 1st item of my collection PriceList. That thing is a collection; get its 2nd item. That thing is a collection; get its 3rd...

Instead, you want slicing:

PriceList[:7] = [PizzaChange]*7

Checking if a collection is empty in Java: which is the best method?

If you have the Apache common utilities in your project rather use the first one. Because its shorter and does exactly the same as the latter one. There won't be any difference between both methods but how it looks inside the source code.

Also a empty check using

listName.size() != 0

Is discouraged because all collection implementations have the

listName.isEmpty()

function that does exactly the same.

So all in all, if you have the Apache common utils in your classpath anyway, use

if (CollectionUtils.isNotEmpty(listName)) 

in any other case use

if(listName != null && listName.isEmpty())

You will not notice any performance difference. Both lines do exactly the same.

Popup Message boxes

A couple of "enhancements" I use for debugging, especially when running projects (ie not in debug mode).

  1. Default the message-box title to the name of the calling method. This is handy for stopping a thread at a given point, but must be cleaned-up before release.
  2. Automatically copy the caller-name and message to the clipboard, because you can't search an image!

    package forumposts;
    
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;
    import javax.swing.JOptionPane;
    
    public final class MsgBox
    {
        public static void info(String message) {
            info(message, theNameOfTheMethodThatCalledMe());
        }
        public static void info(String message, String caller) {
            show(message, caller, JOptionPane.INFORMATION_MESSAGE);
        }
    
        static void error(String message) {
            error(message, theNameOfTheMethodThatCalledMe());
        }
        public static void error(String message, String caller) {
            show(message, caller, JOptionPane.ERROR_MESSAGE);
        }
    
        public static void show(String message, String title, int iconId) {
            setClipboard(title+":"+NEW_LINE+message);
            JOptionPane.showMessageDialog(null, message, title, iconId);
        }
        private static final String NEW_LINE = System.lineSeparator();
    
        public static String theNameOfTheMethodThatCalledMe() {
            return Thread.currentThread().getStackTrace()[3].getMethodName();
        }
    
        public static void setClipboard(String message) {
            CLIPBOARD.setContents(new StringSelection(message), null);
            // nb: we don't respond to the "your content was splattered"
            //     event, so it's OK to pass a null owner.
        }
        private static final Toolkit AWT_TOOLKIT = Toolkit.getDefaultToolkit();
        private static final Clipboard CLIPBOARD = AWT_TOOLKIT.getSystemClipboard();
    
    }
    

The full class also has debug and warning methods, but I cut them for brevity and you get the main points anyway. You can use a public static boolean isDebugEnabled to suppress debug messages. If done properly the optimizer will (almost) remove these method calls from your production code. See: http://c2.com/cgi/wiki?ConditionalCompilationInJava

Cheers. Keith.

How can I find a specific file from a Linux terminal?

In general, the best way to find any file in any arbitrary location is to start a terminal window and type in the classic Unix command "find":

find / -name index.html -print

Since the file you're looking for is the root file in the root directory of your web server, it's probably easier to find your web server's document root. For example, look under:

/var/www/*

Or type:

find /var/www -name index.html -print

SQL Server format decimal places with commas

without considering this to be a good idea...

select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))

Function

-- Author:      bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50)) 
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int

Select @i=CHARINDEX('.',@NumStr)
if @i=0 
    begin
    set @i=LEN(@NumStr)
    Set @Outstr=''
    end
else
    begin   
     Set @Outstr=SUBSTRING(@NUmStr,@i,50)
     Set @i=@i -1
    end 


Set @run=0

While @i>0
    begin
      if @Run=3
        begin
          Set @Outstr=','+@Outstr
          Set @run=0
        end
      Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr  
      Set @i=@i-1
      Set @run=@run + 1     
    end

    RETURN @OutStr

END
GO

Subscript out of bounds - general definition and solution?

It just means that either alter > ncol( reach_mat ) or i > nrow( reach_mat ), in other words, your indices exceed the array boundary (i is greater than the number of rows, or alter is greater than the number of columns).

Just run the above tests to see what and when is happening.

Using Service to run background and create notification

Your error is in UpdaterServiceManager in onCreate and showNotification method.

You are trying to show notification from Service using Activity Context. Whereas Every Service has its own Context, just use the that. You don't need to pass a Service an Activity's Context.I don't see why you need a specific Activity's Context to show Notification.

Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.

You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference

How do I make the first letter of a string uppercase in JavaScript?

This does the same action:

var newStr = string.slice(0,1).toUpperCase() + string.slice(1);

How to resolve merge conflicts in Git repository?

Bonus:

In speaking of pull/fetch/merge in the above answers, I would like to share an interesting and productive trick,

git pull --rebase

This above command is the most useful command in my git life which saved a lots of time.

Before pushing your newly committed change to remote server, try git pull --rebase rather git pull and manual merge and it will automatically sync latest remote server changes (with a fetch + merge) and will put your local latest commit at the top in git log. No need to worry about manual pull/merge.

In case of conflict, just use

git mergetool
git add conflict_file
git rebase --continue

Find details at: http://gitolite.com/git-pull--rebase

ADB error: cannot connect to daemon

I was using Genymotion 2.9.0. I updated to 3.0.0 Now it is working. So please check Genymotion version.

How to parse a JSON string to an array using Jackson

The complete example with an array. Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class Sorting {

    private String property;

    private String direction;

    public Sorting() {

    }

    public Sorting(String property, String direction) {
        this.property = property;
        this.direction = direction;
    }

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public static void main(String[] args) throws JsonParseException, IOException {
        final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
        ObjectMapper mapper = new ObjectMapper();
        Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
        System.out.println(sortings);
    }
}

ActiveXObject in Firefox or Chrome (not IE!)

ActiveX resolved in Chrome!
Hello all this is not the solution but the successful workaround and I have implemented as well.
This required some implementation on client machine as well that why is most suitable for intranet environment and not recommended for public sites. Even though one can implement it for public sites as well the only problem is end user has to download/implement solution.
Lets understand the key problem
Chrome cannot communicate with ActiceX
Solution: Since Chorme cannot communicate with ActiveX but still it can communicate with the API hosted on the client machine. So develop API using .Net MVC or any other technology so that through Ajax call it can communicate with the API and API communicate with the ActiveX object situated on the client machine. Since API also resides in Client machine that why there is no problem in communication. This API works as mediator between Chrome browser and ActiveX.
During API implementation you might encounter CORS issues, Use JSONP to deal with it.
Pictorial view of the solution Pictorial view of the solution


Other solution : Use URI Scheme like MailTo: or MS-Word to deal with outlook and word application. If your requirement is different then you can implement your customized URI Scheme.

How to run a program in Atom Editor?

For C/C++ programs there's very good package gpp-compiler.

Shortcuts:

  • To compile and run: F5
  • To debug: F6

The name 'ViewBag' does not exist in the current context

I had the same problem and crimbo gave me the right clue, it was caused by the ./Views/Web.config file which was present but not containing the right namespaces I guess...

I created a blank MVC5 project and imported its ./Views/Web.config into my existing project and the red waves under every ViewBag use are gone !

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

I'm sorry to say, but the time discontinuity has moved a bit in

JDK 6 two years ago, and in JDK 7 just recently in update 25.

Lesson to learn: avoid non-UTC times at all costs, except maybe for display.

Do I need a content-type header for HTTP GET requests?

Short answer: Most likely, no you do not need a content-type header for HTTP GET requests. But the specs does not seem to rule out a content-type header for HTTP GET, either.

Supporting materials:

  1. "Content-Type" is part of the representation (i.e. payload) metadata. Quoted from RFC 7231 section 3.1:

    3.1. Representation Metadata

    Representation header fields provide metadata about the representation. When a message includes a payload body, the representation header fields describe how to interpret the representation data enclosed in the payload body. ...

    The following header fields convey representation metadata:

    +-------------------+-----------------+
    | Header Field Name | Defined in...   |
    +-------------------+-----------------+
    | Content-Type      | Section 3.1.1.5 |
    | ...               | ...             |
    

    Quoted from RFC 7231 section 3.1.1.5(by the way, the current chosen answer had a typo in the section number):

    The "Content-Type" header field indicates the media type of the associated representation

  2. In that sense, a Content-Type header is not really about an HTTP GET request (or a POST or PUT request, for that matter). It is about the payload inside such a whatever request. So, if there will be no payload, there needs no Content-Type. In practice, some implementation went ahead and made that understandable assumption. Quoted from Adam's comment:

    "While ... the spec doesn't say you can't have Content-Type on a GET, .Net seems to enforce it in it's HttpClient. See this SO q&a."

  3. However, strictly speaking, the specs itself does not rule out the possibility of HTTP GET contains a payload. Quoted from RFC 7231 section 4.3.1:

    4.3.1 GET

    ...

    A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

    So, if your HTTP GET happens to include a payload for whatever reason, a Content-Type header is probably reasonable, too.

MySQL LEFT JOIN Multiple Conditions

Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result

SELECT a.* FROM a 
    LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']} 
    WHERE a.keyword LIKE '%".$keyword."%' 
    GROUP BY group_id

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

Going back to Servlet days, web.xml can have only one <context-param>, so only one context object gets created when server loads an application and the data in that context is shared among all resources (Ex: Servlets and JSPs). It is same as having Database driver name in the context, which will not change. In similar way, when we declare contextConfigLocation param in <contex-param> Spring creates one Application Context object.

 <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>com.myApp.ApplicationContext</param-value>
 </context-param>

You can have multiple Servlets in an application. For example you might want to handle /secure/* requests in one way and /non-seucre/* in other way. For each of these Servlets you can have a context object, which is a WebApplicationContext.

<servlet>
    <servlet-name>SecureSpringDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>com.myapp.secure.SecureContext</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>SecureSpringDispatcher</servlet-name>
    <url-pattern>/secure/*</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>NonSecureSpringDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>com.myapp.non-secure.NonSecureContext</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>NonSecureSpringDispatcher</servlet-name>
    <url-pattern>/non-secure/*</url-patten>
</servlet-mapping>

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

just add login password to connect to RabbitMq

 CachingConnectionFactory connectionFactory = 
         new CachingConnectionFactory("rabbit_host");

 connectionFactory.setUsername("login");
 connectionFactory.setPassword("password");

How to reset the state of a Redux store?

The accepted answer helped me solve my case. However, I encountered case where not-the-whole-state had to be cleared. So - I did it this way:

const combinedReducer = combineReducers({
    // my reducers 
});

const rootReducer = (state, action) => {
    if (action.type === RESET_REDUX_STATE) {
        // clear everything but keep the stuff we want to be preserved ..
        delete state.something;
        delete state.anotherThing;
    }
    return combinedReducer(state, action);
}

export default rootReducer;

Hope this helps someone else :)

How can I view an old version of a file with Git?

If you like GUIs, you can use gitk:

  1. start gitk with:

    gitk /path/to/file
    
  2. Choose the revision in the top part of the screen, e.g. by description or date. By default, the lower part of the screen shows the diff for that revision, (corresponding to the "patch" radio button).

  3. To see the file for the selected revision:

    • Click on the "tree" radio button. This will show the root of the file tree at that revision.
    • Drill down to your file.

How to create a drop shadow only on one side of an element?

If your background is solid (or you can reproduce it using CSS), you can use linear gradient that way:

_x000D_
_x000D_
div {_x000D_
  background-image: linear-gradient(to top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.3) 5px, #fff 5px, #fff 100%)_x000D_
}
_x000D_
<div>_x000D_
<p>Foobar</p>_x000D_
<p>test</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will generate a 5px gradient at the bottom of the element, from black at 30% opacity to completely transparent. The rest of the element has white background. Of course, changing the last 2 color stops of the linear gradient, you could make the background completely transparent.

CSS Auto hide elements after 5 seconds

Of course you can, just use setTimeout to change a class or something to trigger the transition.

HTML:

<p id="aap">OHAI!</p>

CSS:

p {
    opacity:1;
    transition:opacity 500ms;
}
p.waa {
    opacity:0;
}

JS to run on load or DOMContentReady:

setTimeout(function(){
    document.getElementById('aap').className = 'waa';
}, 5000);

Example fiddle here.

webpack command not working

The quickest way, just to get this working is to use the web pack from another location, this will stop you having to install it globally or if npm run webpack fails.

When you install webpack with npm it goes inside the "node_modules\.bin" folder of your project.

in command prompt (as administrator)

  1. go to the location of the project where your webpack.config.js is located.
  2. in command prompt write the following
"C:\Users\..\ProjectName\node_modules\.bin\webpack" --config webpack.config.vendor.js

Internet Explorer 11- issue with security certificate error prompt

This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level

You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property

You can do that by following steps:

  1. Click on Gear icon at the top of the browser window.
  2. Select Internet Options.
  3. Select the Security tab at the top.
  4. Click the Custom Level... button.
  5. Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
  6. Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
  7. Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
  8. Close and restart the browser.

enter image description here

What does $ mean before a string?

It creates an interpolated string.

From MSDN

Used to construct strings. An interpolated string expression looks like a template string that contains expressions. An interpolated string expression creates a string by replacing the contained expressions with the ToString represenations of the expressions’ results.

ex :

 var name = "Sam";
 var msg = $"hello, {name}";

 Console.WriteLine(msg); // hello, Sam

You can use expressions within the interpolated string

 var msg = $"hello, {name.ToLower()}";
 Console.WriteLine(msg); // hello, sam

The nice thing about it is that you don't need to worry about the order of parameters as you do with String.Format.

  var s = String.Format("{0},{1},{2}...{88}",p0,p1,..,p88);

Now if you want to remove some parameters you have to go and update all the counts, which is not the case anymore.

Note that the good old string.format is still relevant if you want to specify cultural info in your formatting.

What's the difference between unit tests and integration tests?

A unit test tests code that you have complete control over whereas an integration test tests how your code uses or "integrates" with some other code.

So you would write unit tests to make sure your own libraries work as intended, and then write integration tests to make sure your code plays nicely with other code you are making use of, for instance a library.

Functional tests are related to integration tests, but refer more specifically to tests that test an entire system or application with all of the code running together, almost a super integration test.

Fastest Convert from Collection to List<T>

What version of the framework? With 3.5 you could presumably use:

List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();

(edited to remove simpler version; I checked and ManagementObjectCollection only implements the non-generic IEnumerable form)

What is the best way to add a value to an array in state

handleValueChange = (value) => {
      let myArr= [...this.state.myArr]
      myArr.push(value)
      this.setState({
         myArr
     })

This might do the work.

standard size for html newsletter template

Ideally the email content should be about 550px wide to fit within most email clients preview window. If you know for sure your target market can view bigger then you can design bigger. Loads of email examples over on http://www.beautiful-email-newsletters.com/

Using ResourceManager

There's surprisingly simple way of reading resource by string:

ResourceNamespace.ResxFileName.ResourceManager.GetString("ResourceKey")

It's clean and elegant solution for reading resources by keys where "dot notation" cannot be used (for instance when resource key is persisted in the database).

Excel "External table is not in the expected format."

That excel file address may have an incorrect extension. You can change the extension from xls to xlsx or vice versa and try again.

How to make primary key as autoincrement for Room Persistence lib

For example, if you have a users entity you want to store, with fields (firstname, lastname , email) and you want autogenerated id, you do this.

@Entity(tableName = "users")
data class Users(
   @PrimaryKey(autoGenerate = true)
   val id: Long,
   val firstname: String,
   val lastname: String,
   val email: String
)

Room will then autogenerate and auto-increment the id field.

VBA code to set date format for a specific column as "yyyy-mm-dd"

You are applying the formatting to the workbook that has the code, not the added workbook. You'll want to get in the habit of fully qualifying sheet and range references. The code below does that and works for me in Excel 2010:

Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
    .Range("A1") = "Acctdate"
    .Range("B1") = "Ledger"
    .Range("C1") = "CY"
    .Range("D1") = "BusinessUnit"
    .Range("E1") = "OperatingUnit"
    .Range("F1") = "LOB"
    .Range("G1") = "Account"
    .Range("H1") = "TreatyCode"
    .Range("I1") = "Amount"
    .Range("J1") = "TransactionCurrency"
    .Range("K1") = "USDEquivalentAmount"
    .Range("L1") = "KeyCol"
    .Range("A2", "A50000").Value = Me.TextBox3.Value
    .Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub

How do you run a command as an administrator from the Windows command line?

Browse to C:\windows\System32 and right click on cmd.exe and run as Administrator. Worked for me on Windows 7.

If you are trying to run a script with elevated privileges you could do the same for the script file or use the scheduler's run as a different user option to run the script.

Change Row background color based on cell value DataTable

DataTables has functionality for this since v 1.10

https://datatables.net/reference/option/createdRow

Example:

$('#tid_css').DataTable({
  // ...
  "createdRow": function(row, data, dataIndex) {
    if (data["column_index"] == "column_value") {
      $(row).css("background-color", "Orange");
      $(row).addClass("warning");
    }
  },
  // ...
});

Python unittest - opposite of assertRaises?

I've found it useful to monkey-patch unittest as follows:

def assertMayRaise(self, exception, expr):
  if exception is None:
    try:
      expr()
    except:
      info = sys.exc_info()
      self.fail('%s raised' % repr(info[0]))
  else:
    self.assertRaises(exception, expr)

unittest.TestCase.assertMayRaise = assertMayRaise

This clarifies intent when testing for the absence of an exception:

self.assertMayRaise(None, does_not_raise)

This also simplifies testing in a loop, which I often find myself doing:

# ValueError is raised only for op(x,x), op(y,y) and op(z,z).
for i,(a,b) in enumerate(itertools.product([x,y,z], [x,y,z])):
  self.assertMayRaise(None if i%4 else ValueError, lambda: op(a, b))

How to pick just one item from a generator?

Create a generator using

g = myfunct()

Everytime you would like an item, use

next(g)

(or g.next() in Python 2.5 or below).

If the generator exits, it will raise StopIteration. You can either catch this exception if necessary, or use the default argument to next():

next(g, default_value)

How do you compare structs for equality in C?

if the 2 structures variable are initialied with calloc or they are set with 0 by memset so you can compare your 2 structures with memcmp and there is no worry about structure garbage and this will allow you to earn time

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

How to prevent going back to the previous activity?

finish() gives you method to close current Activity not whole application. And you better don't try to look for methods to kill application. Little advice.

Have you tried conjunction of Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY? Remember to use this flags in Intent starting activity!

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Update for latest SDK:

Now @zeuter's answer is correct for Facebook SDK v4.7+:

LoginManager.getInstance().logOut();

Original answer:

Please do not use SessionTracker. It is an internal (package private) class, and is not meant to be consumed as part of the public API. As such, its API may change at any time without any backwards compatibility guarantees. You should be able to get rid of all instances of SessionTracker in your code, and just use the active session instead.

To answer your question, if you don't want to keep any session data, simply call closeAndClearTokenInformation when your app closes.

Entity Framework rollback and remove bad migration

First, Update your last perfect migration via this command :

Update-Database –TargetMigration

Example:

Update-Database -20180906131107_xxxx_xxxx

And, then delete your unused migration manually.

Executing an EXE file using a PowerShell script

& "C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode

or

[System.Diagnostics.Process]::Start("C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe", "C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode")

UPDATE: sorry I missed "(I invoked the command using the "&" operator)" sentence. I had this problem when I was evaluating the path dynamically. Try Invoke-Expression construction:

Invoke-Expression "& `"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe`" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode"

Why won't my PHP app send a 404 error?

I came up to this problem.. I think that redirecting to a non existing link on your server might do the trick ! Because the server would return his 404:
header('Redirect abbb.404.nonexist'); < that doesnt exist for sure

npm not working after clearing cache

Try npm cache clean --force if it doesn't work then manually delete %appdata%\npm-cache folder.

and install npm install npm@latest -g

It worked for me.

visit this link

Do while loop in SQL Server 2008

I am not sure about DO-WHILE IN MS SQL Server 2008 but you can change your WHILE loop logic, so as to USE like DO-WHILE loop.

Examples are taken from here: http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/

  1. Example of WHILE Loop

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
        PRINT @intFlag
        SET @intFlag = @intFlag + 1
    END
    GO
    

    ResultSet:

    1
    2
    3
    4
    5
    
  2. Example of WHILE Loop with BREAK keyword

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
        PRINT @intFlag
        SET @intFlag = @intFlag + 1
        IF @intFlag = 4
            BREAK;
    END
    GO
    

    ResultSet:

    1
    2
    3
    
  3. Example of WHILE Loop with CONTINUE and BREAK keywords

    DECLARE @intFlag INT
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
        PRINT @intFlag
        SET @intFlag = @intFlag + 1
        CONTINUE;
        IF @intFlag = 4 -- This will never executed
            BREAK;
    END
    GO
    

    ResultSet:

    1
    2
    3
    4
    5
    

But try to avoid loops at database level. Reference.

How to put Google Maps V2 on a Fragment using ViewPager

The following approach works for me.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * A fragment that launches other parts of the demo application.
 */
public class MapFragment extends Fragment {

MapView mMapView;
private GoogleMap googleMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // inflat and return the layout
    View v = inflater.inflate(R.layout.fragment_location_info, container,
            false);
    mMapView = (MapView) v.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume();// needed to get the map to display immediately

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    googleMap = mMapView.getMap();
    // latitude and longitude
    double latitude = 17.385044;
    double longitude = 78.486671;

    // create marker
    MarkerOptions marker = new MarkerOptions().position(
            new LatLng(latitude, longitude)).title("Hello Maps");

    // Changing marker icon
    marker.icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

    // adding marker
    googleMap.addMarker(marker);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
    googleMap.animateCamera(CameraUpdateFactory
            .newCameraPosition(cameraPosition));

    // Perform any camera updates here
    return v;
}

@Override
public void onResume() {
    super.onResume();
    mMapView.onResume();
}

@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mMapView.onLowMemory();
}
}

fragment_location_info.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

C program to check little vs. big endian

In short, yes.

Suppose we are on a 32-bit machine.

If it is little endian, the x in the memory will be something like:

       higher memory
          ----->
    +----+----+----+----+
    |0x01|0x00|0x00|0x00|
    +----+----+----+----+
    A
    |
   &x

so (char*)(&x) == 1, and *y+48 == '1'.

If it is big endian, it will be:

    +----+----+----+----+
    |0x00|0x00|0x00|0x01|
    +----+----+----+----+
    A
    |
   &x

so this one will be '0'.

Detect Browser Language in PHP

All of the above with fallback to 'en':

$lang = substr(explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE'])[0],0,2)?:'en';

...or with default language fallback and known language array:

function lang( $l = ['en'], $u ){
    return $l[
        array_keys(
            $l,
            substr(
                explode(
                    ',',
                    $u ?: $_SERVER['HTTP_ACCEPT_LANGUAGE']
                )[0],
                0,
                2
            )
        )[0]
    ] ?: $l[0];
}

One Line:

function lang($l=['en'],$u){return $l[array_keys($l,substr(explode(',',$u?:$_SERVER['HTTP_ACCEPT_LANGUAGE'])[0],0,2))[0]]?:$l[0];}

Examples:

// first known lang is always default
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'en-us';
lang(['de']); // 'de'
lang(['de','en']); // 'en'

// manual set accept-language
lang(['de'],'en-us'); // 'de'
lang(['de'],'de-de, en-us'); // 'de'
lang(['en','fr'],'de-de, en-us'); // 'en'
lang(['en','fr'],'fr-fr, en-us'); // 'fr'
lang(['de','en'],'fr-fr, en-us'); // 'de'

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Go to the directory where you put additional libraries and delete duplicated libraries.

Simulate limited bandwidth from within Chrome?

I'd recommend Charles Proxy - you can choose to slowdown individual sites, also has a whole bunch of HTTP inspection tools.

Edit:

As of June 2014, Chrome now has the ability to do this natively in DevTools - you'll need Chrome 38 though.

The option is accessible from the Network tab via a drop down at the end of the toolbar.

How to set specific window (frame) size in java swing?

Try this, but you can adjust frame size with bounds and edit title.

package co.form.Try;

import javax.swing.JFrame;

public class Form {

    public static void main(String[] args) {
        JFrame obj =new JFrame();
        obj.setBounds(10,10,700,600); 
        obj.setTitle("Application Form");
        obj.setResizable(false);                
        obj.setVisible(true);       
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

Closing database connections in Java

Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.

You should do this with any object that implements AutoClosable.

try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
    String sqlToExecute = "SELECT * FROM persons";
    try (ResultSet resultSet = statement.execute(sqlToExecute)) {
        if (resultSet.next()) {
            System.out.println(resultSet.getString("name");
        }
    }
} catch (SQLException e) {
    System.out.println("Failed to select persons.");
}

The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.

PHP to write Tab Characters inside a file?

This should do:

$chunk = "abc\tdef\tghi";

Here is a link to an article with more extensive examples.

Difference between return and exit in Bash functions

Sometimes, you run a script using . or source.

. a.sh

If you include an exit in the a.sh, it will not just terminate the script, but end your shell session.

If you include a return in the a.sh, it simply stops processing the script.

How to set image to fit width of the page using jsPDF?

This is how I've achieved in Reactjs.

Main problem were ratio and scale If you do a quick window.devicePixelRatio, it's default value is 2 which was causing the half image issue.

const printDocument = () => {
  const input = document.getElementById('divToPrint');
  const divHeight = input.clientHeight
  const divWidth = input.clientWidth
  const ratio = divHeight / divWidth;

  html2canvas(input, { scale: '1' }).then((canvas) => {
    const imgData = canvas.toDataURL('image/jpeg');
    const pdfDOC = new JSPDF("l", "mm", "a0"); //  use a4 for smaller page

    const width = pdfDOC.internal.pageSize.getWidth();
    let height = pdfDOC.internal.pageSize.getHeight();
    height = ratio * width;

    pdfDOC.addImage(imgData, 'JPEG', 0, 0, width - 20, height - 10);
    pdfDOC.save('summary.pdf');   //Download the rendered PDF.
  })
}

How can I add a new column and data to a datatable that already contains data?

Should it not be foreach instead of for!?

//call SQL helper class to get initial data  
DataTable dt = sql.ExecuteDataTable("sp_MyProc"); 

dt.Columns.Add("MyRow", **typeof**(System.Int32)); 

foreach(DataRow dr in dt.Rows) 
{ 
    //need to set value to MyRow column 
    dr["MyRow"] = 0;   // or set it to some other value 
} 

Reloading module giving NameError: name 'reload' is not defined

If you don't want to use external libs, then one solution is to recreate the reload method from python 2 for python 3 as below. Use this in the top of the module (assumes python 3.4+).

import sys
if(sys.version_info.major>=3):
    def reload(MODULE):        
        import importlib
        importlib.reload(MODULE)

BTW reload is very much required if you use python files as config files and want to avoid restarts of the application.....

Get last 3 characters of string

The easiest way would be using Substring

string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);

Using the overload with one int as I put would get the substring of a string, starting from the index int. In your case being str.Length - 3, since you want to get the last three chars.

Creating a textarea with auto-resize

I'm able to set the TextArea size in IE9 and Chrome with the following jQuery function. It binds to the textarea objects from the selector defined in the $(document).ready() function.

function autoResize(obj, size) {
    obj.keyup(function () {
        if ($(this).val().length > size-1) {
            $(this).val( function() {
                $(this).height(function() {
                    return this.scrollHeight + 13;
                });
                alert('The maximum comment length is '+size+' characters.');
                return $(this).val().substring(0, size-1);
            });
        }
        $(this).height(function() {
            if  ($(this).val() == '') {
                return 15;
            } else {
                $(this).height(15);
                return ($(this).attr('scrollHeight')-2);
            }
        });
    }).keyup();
}

In my $(document).ready() function I have the following call for all of my textarea calls on this page.

$('textarea').each( function() {
        autoResize($(this), 250);
});

Where 250 is the character limit on my text area. This will grow as large as the text size will allow (based on your character count and font size). It will also shrink your text area appropriately when you remove characters from your textarea or if the user pastes too much text initially.

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

I started digging myself and I found one potential advantage of using setUp(). If any exceptions are thrown during the execution of setUp(), JUnit will print a very helpful stack trace. On the other hand, if an exception is thrown during object construction, the error message simply says JUnit was unable to instantiate the test case and you don't see the line number where the failure occurred, probably because JUnit uses reflection to instantiate the test classes.

None of this applies to the example of creating an empty collection, since that will never throw, but it is an advantage of the setUp() method.

When to use AtomicReference in Java?

Here's a very simple use case and has nothing to do with thread safety.

To share an object between lambda invocations, the AtomicReference is an option:

public void doSomethingUsingLambdas() {

    AtomicReference<YourObject> yourObjectRef = new AtomicReference<>();

    soSomethingThatTakesALambda(() -> {
        yourObjectRef.set(youObject);
    });

    soSomethingElseThatTakesALambda(() -> {
        YourObject yourObject = yourObjectRef.get();
    });
}

I'm not saying this is good design or anything (it's just a trivial example), but if you have have the case where you need to share an object between lambda invocations, the AtomicReference is an option.

In fact you can use any object that holds a reference, even a Collection that has only one item. However, the AtomicReference is a perfect fit.

Adding attribute in jQuery

$('#yourid').prop('disabled', true);

Turn on torch/flash on iPhone

From iOS 6.0 and above, toggling torch flash on/off,

- (void) toggleFlash {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch] && [device hasFlash]){
        [device lockForConfiguration:nil];
        [device setFlashMode:(device.flashActive) ? AVCaptureFlashModeOff : AVCaptureFlashModeOn];
        [device setTorchMode:(device.torchActive) ? AVCaptureTorchModeOff : AVCaptureTorchModeOn];
        [device unlockForConfiguration];
    }
}

P.S. This approach is only suggestible if you don't have on/off function. Remember there's one more option Auto. i.e. AVCaptureFlashModeAuto and AVCaptureTorchModeAuto. To support auto mode as well, you've keep track of current mode and based on that change mode of flash & torch.

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

It sounds like your site has CSS or JS that depends on running in quirks mode. Which is why you need garbage above your doctype to render "correctly". I suggest removing said garbage and then fixing your CSS+JS to actually work in standards mode; you'll save yourself a lot of pain in the long run.

change values in array when doing foreach

With the Array object methods you can modify the Array content yet compared to the basic for loops, these methods lack one important functionality. You can not modify the index on the run.

For example if you will remove the current element and place it to another index position within the same array you can easily do this. If you move the current element to a previous position there is no problem in the next iteration you will get the same next item as if you hadn't done anything.

Consider this code where we move the item at index position 5 to index position 2 once the index counts up to 5.

var ar = [0,1,2,3,4,5,6,7,8,9];
ar.forEach((e,i,a) => {
i == 5 && a.splice(2,0,a.splice(i,1)[0])
console.log(i,e);
}); // 0 0 - 1 1 - 2 2 - 3 3 - 4 4 - 5 5 - 6 6 - 7 7 - 8 8 - 9 9

However if we move the current element to somewhere beyond the current index position things get a little messy. Then the very next item will shift into the moved items position and in the next iteration we will not be able to see or evaluate it.

Consider this code where we move the item at index position 5 to index position 7 once the index counts up to 5.

var a = [0,1,2,3,4,5,6,7,8,9];
a.forEach((e,i,a) => {
i == 5 && a.splice(7,0,a.splice(i,1)[0])
console.log(i,e);
}); // 0 0 - 1 1 - 2 2 - 3 3 - 4 4 - 5 5 - 6 7 - 7 5 - 8 8 - 9 9

So we have never met 6 in the loop. Normally in a for loop you are expected decrement the index value when you move the array item forward so that your index stays at the same position in the next run and you can still evaluate the item shifted into the removed item's place. This is not possible with array methods. You can not alter the index. Check the following code

var a = [0,1,2,3,4,5,6,7,8,9];
a.forEach((e,i,a) => {
i == 5 && (a.splice(7,0,a.splice(i,1)[0]), i--);
console.log(i,e);
}); // 0 0 - 1 1 - 2 2 - 3 3 - 4 4 - 4 5 - 6 7 - 7 5 - 8 8 - 9 9

As you see when we decrement i it will not continue from 5 but 6, from where it was left.

So keep this in mind.

What does the explicit keyword mean?

It is always a good coding practice to make your one argument constructors (including those with default values for arg2,arg3,...) as already stated. Like always with C++: if you don't - you'll wish you did...

Another good practice for classes is to make copy construction and assignment private (a.k.a. disable it) unless you really need to implement it. This avoids having eventual copies of pointers when using the methods that C++ will create for you by default. An other way to do this is derive from boost::noncopyable.

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

What is the difference between explicit and implicit cursors in Oracle?

1.CURSOR: When PLSQL issues sql statements it creates private work area to parse & execute the sql statement is called cursor.

2.IMPLICIT: When any PL/SQLexecutable block issues sql statement. PL/SQL creates implicit cursor and manages automatically means implcit open & close takes place. It used when sql statement return only one row.It has 4 attributes SQL%ROWCOUNT, SQL%FOUND, SQL%NOTFOUND, SQL%ISOPEN.

3.EXPLICIT: It is created & managed by the programmer. It needs every time explicit open,fetch & close. It is used when sql statement returns more than one row. It has also 4 attributes CUR_NAME%ROWCOUNT, CUR_NAME%FOUND, CUR_NAME%NOTFOUND, CUR_NAME%ISOPEN. It process several rows by using loop. The programmer can pass the parameter too to explicit cursor.

  • Example: Explicit Cursor

 

declare 
   cursor emp_cursor 
   is 
   select id,name,salary,dept_id 
   from employees; 
   v_id employees.id%type; 
   v_name employees.name%type; 
   v_salary employees.salary%type; 
   v_dept_id employees.dept_id%type; 
   begin 
   open emp_cursor; 
   loop 
   fetch emp_cursor into v_id,v_name,v_salary,v_dept_id; 
   exit when emp_cursor%notfound;
   dbms_output.put_line(v_id||', '||v_name||', '||v_salary||','||v_dept_id); 
   end loop;                    
   close emp_cursor; 
   end;

Could not load NIB in bundle

Visit the properties of the .xib files in the file inspector ,the property "Target Membership" pitch on the select box, then your xib file was linked with your target

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

I resolve this is by changing the version no of recyleview to recyclerview-v7:24.2.1. Please check your dependencies and use the proper version number.

Javascript change Div style

function abc() {
    var color = document.getElementById("test").style.color;
    if (color === "red")
         document.getElementById("test").style.color="black";
    else
         document.getElementById("test").style.color="red";
}

Java - how do I write a file to a specified directory

Just put the full directory location in the File object.

File file = new File("z:\\results.txt");

Upload a file to Amazon S3 with NodeJS

Thanks to David as his solution helped me come up with my solution for uploading multi-part files from my Heroku hosted site to S3 bucket. I did it using formidable to handle incoming form and fs to get the file content. Hopefully, it may help you.

api.service.ts

public upload(files): Observable<any> {  
    const formData: FormData = new FormData(); 
    files.forEach(file => {
      // create a new multipart-form for every file 
      formData.append('file', file, file.name);           
    });   
    return this.http.post(uploadUrl, formData).pipe(
      map(this.extractData),
      catchError(this.handleError)); 
  }
}

server.js

app.post('/api/upload', upload);
app.use('/api/upload', router);

upload.js

const IncomingForm = require('formidable').IncomingForm;
const fs = require('fs');
const AWS = require('aws-sdk');

module.exports = function upload(req, res) {
    var form = new IncomingForm();

    const bucket = new AWS.S3(
      {
        signatureVersion: 'v4',
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        region: 'us-east-1'       
      }
    ); 

    form.on('file', (field, file) => {

        const fileContent = fs.readFileSync(file.path);

        const s3Params = {
            Bucket: process.env.AWS_S3_BUCKET,
            Key: 'folder/' + file.name,
            Expires: 60,             
            Body: fileContent,
            ACL: 'public-read'
        };

        bucket.upload(s3Params, function(err, data) {
            if (err) {
                throw err;
            }            
            console.log('File uploaded to: ' + data.Location);
            fs.unlink(file.path, function (err) {
              if (err) {
                  console.error(err);
              }
              console.log('Temp File Delete');
          });
        });
    });              

    // The second callback is called when the form is completely parsed. 
    // In this case, we want to send back a success status code.
    form.on('end', () => {        
      res.status(200).json('upload ok');
    });

    form.parse(req);
}

upload-image.component.ts

import { Component, OnInit, ViewChild, Output, EventEmitter, Input } from '@angular/core';
import { ApiService } from '../api.service';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-upload-image',
  templateUrl: './upload-image.component.html',
  styleUrls: ['./upload-image.component.css']
})

export class UploadImageComponent implements OnInit {
  public files: Set<File> = new Set();
  @ViewChild('file', { static: false }) file;
  public uploadedFiles: Array<string> = new Array<string>();
  public uploadedFileNames: Array<string> = new Array<string>();
  @Output() filesOutput = new EventEmitter<Array<string>>();
  @Input() CurrentImage: string;
  @Input() IsPublic: boolean;
  @Output() valueUpdate = new EventEmitter();
  strUploadedFiles:string = '';
  filesUploaded: boolean = false;     

  constructor(private api: ApiService, public snackBar: MatSnackBar,) { }

  ngOnInit() {    
  }

  updateValue(val) {  
    this.valueUpdate.emit(val);  
  }  

  reset()
  {
    this.files = new Set();
    this.uploadedFiles = new Array<string>();
    this.uploadedFileNames = new Array<string>();
    this.filesUploaded = false;
  }

  upload() { 

    this.api.upload(this.files).subscribe(res => {   
      this.filesOutput.emit(this.uploadedFiles); 
      if (res == 'upload ok')
      {
        this.reset(); 
      }     
    }, err => {
      console.log(err);
    });
  }

  onFilesAdded() {
    var txt = '';
    const files: { [key: string]: File } = this.file.nativeElement.files;

    for (let key in files) {
      if (!isNaN(parseInt(key))) {

        var currentFile = files[key];
        var sFileExtension = currentFile.name.split('.')[currentFile.name.split('.').length - 1].toLowerCase();
        var iFileSize = currentFile.size;

        if (!(sFileExtension === "jpg" 
              || sFileExtension === "png") 
              || iFileSize > 671329) {
            txt = "File type : " + sFileExtension + "\n\n";
            txt += "Size: " + iFileSize + "\n\n";
            txt += "Please make sure your file is in jpg or png format and less than 655 KB.\n\n";
            alert(txt);
            return false;
        }

        this.files.add(files[key]);
        this.uploadedFiles.push('https://gourmet-philatelist-assets.s3.amazonaws.com/folder/' + files[key].name);
        this.uploadedFileNames.push(files[key].name);
        if (this.IsPublic && this.uploadedFileNames.length == 1)
        {
          this.filesUploaded = true;
          this.updateValue(files[key].name);
          break;
        } 
        else if (!this.IsPublic && this.uploadedFileNames.length == 3)
        {
          this.strUploadedFiles += files[key].name;          
          this.updateValue(this.strUploadedFiles); 
          this.filesUploaded = true;
          break;
        }
        else
        {
          this.strUploadedFiles += files[key].name + ",";          
          this.updateValue(this.strUploadedFiles); 
        }      
      }
    }    
  }

  addFiles() {
    this.file.nativeElement.click();  
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000,
      verticalPosition: 'top'
    });
  }   

}

upload-image.component.html

<input type="file" #file style="display: none" (change)="onFilesAdded()" multiple />
&nbsp;<button mat-raised-button color="primary" 
         [disabled]="filesUploaded" (click)="$event.preventDefault(); addFiles()">
  Add Files
</button>
&nbsp;<button class="btn btn-success" [disabled]="uploadedFileNames.length == 0" (click)="$event.preventDefault(); upload()">
  Upload
</button>

How to use UIPanGestureRecognizer to move object? iPhone/iPad

-(IBAction)Method
{
      UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
      [panRecognizer setMinimumNumberOfTouches:1];
      [panRecognizer setMaximumNumberOfTouches:1];
      [ViewMain addGestureRecognizer:panRecognizer];
      [panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
{

     CGPoint translation = [recognizer translationInView:self.view];
     recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
                                     recognizer.view.center.y + translation.y);
     [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

     if (recognizer.state == UIGestureRecognizerStateEnded) {

         CGPoint velocity = [recognizer velocityInView:self.view];
         CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
         CGFloat slideMult = magnitude / 200;
         NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

         float slideFactor = 0.1 * slideMult; // Increase for more of a slide
         CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor), 
                                     recognizer.view.center.y + (velocity.y * slideFactor));
         finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
         finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);

         [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
             recognizer.view.center = finalPoint;
         } completion:nil];

    }

}

Get filename in batch for loop

or Just %~F will give you the full path and full file name.

For example, if you want to register all *.ax files in the current directory....

FOR /R C:. %F in (*.ax) do regsvr32 "%~F"

This works quite nicely in Win7 (64bit) :-)

Jquery, set value of td in a table?

You can try below code:

$("Your button id or class").live("click", function(){

    $('#detailInfo').html('set your value as you want');

});

Good Luck...

how to add or embed CKEditor in php page

After reading the Quick Start Guide

In your HTML page add an element that CKEditor should replace:

<textarea name="content" id="editor"></textarea>

Load the classic editor build (here CDN location is used):

<script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>

Call the ClassicEditor.create() method.

<script>
    ClassicEditor
        .create( document.querySelector( '#editor' ) )
        .catch( error => {
            console.error( error );
        } );
</script>

Example

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor 5 - Classic editor</title>
    <script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>
</head>
<body>
    <h1>Classic editor</h1>
    <textarea name="content" id="editor">
        <p>This is some sample content.</p>
    </textarea>
    <script>
        ClassicEditor
            .create( document.querySelector( '#editor' ) )
            .catch( error => {
                console.error( error );
            } );
    </script>
</body>
</html>

This example is for the specific classic editor. FOr other variants, only CDN will change.

Creating a triangle with for loops

A fun, simple solution:

for (int i = 0; i < 5; i++) 
  System.out.println("    *********".substring(i, 5 + 2*i));

Can't change z-index with JQuery

because your jQuery code is wrong. Correctly would be:

var theParent = $(this).parent().get(0); 
$(theParent).css('z-index', 3000);

bootstrap button shows blue outline when clicked

I just had the same issue and the following code worked for me:

_x000D_
_x000D_
.btn:active, .btn:focus, .btn:active:focus, .btn.active:focus {_x000D_
    outline: none !important;_x000D_
}_x000D_
_x000D_
.btn {_x000D_
  margin:32px;_x000D_
}
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<button type="button" class="btn btn-default">Button</button>
_x000D_
_x000D_
_x000D_

Hoping it will help!

How to list all databases in the mongo shell?

Couple of commands are there to list all dbs in MongoDB shell.

first , launch Mongodb shell using 'mongo' command.

mongo

Then use any of the below commands to list all the DBs.

  • show dbs
  • show databases
  • db.adminCommand( { listDatabases: 1 , nameOnly : true} )

A snap shot

For more details please check here

Thank you.

Which Architecture patterns are used on Android?

Here is a great article on Common Design Patterns for Android:

Creational patterns:

  • Builder (e.g. AlertDialog.Builder)
  • Dependency Injection (e.g. Dagger 2)
  • Singleton

Structural patterns:

  • Adapter (e.g. RecyclerView.Adapter)
  • Facade (e.g. Retrofit)

Behavioral patterns:

  • Command (e.g. EventBus)
  • Observer (e.g. RxAndroid)
  • Model View Controller
  • Model View ViewModel (similar to the MVC pattern above)

What does ':' (colon) do in JavaScript?

var o = {
    r: 'some value',
    t: 'some other value'
};

is functionally equivalent to

var o = new Object();
o.r = 'some value';
o.t = 'some other value';

Graphical HTTP client for windows

Honestly, for simplistic stuff like that I typically whip up a quick HTML form in a local file and load that up in a browser.

Virtual member call in a constructor

Another interesting thing I found is that the ReSharper error can be 'satisfied' by doing something like below which is dumb to me. However, as mentioned by many earlier, it still is not a good idea to call virtual properties/methods in constructor.

public class ConfigManager
{
   public virtual int MyPropOne { get; private set; }
   public virtual string MyPropTwo { get; private set; }

   public ConfigManager()
   {
    Setup();
   }

   private void Setup()
   {
    MyPropOne = 1;
    MyPropTwo = "test";
   }
}

How to create an integer-for-loop in Ruby?

Try Below Simple Ruby Magics :)

(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }

Moment.js - how do I get the number of years since a date, not rounded up?

I prefer this small method.

function getAgeFromBirthday(birthday) {
    if(birthday){
      var totalMonths = moment().diff(birthday, 'months');
      var years = parseInt(totalMonths / 12);
      var months = totalMonths % 12;
        if(months !== 0){
           return parseFloat(years + '.' + months);
         }
    return years;
      }
    return null;
}

What does <![CDATA[]]> in XML mean?

CDATA stands for Character Data. You can use this to escape some characters which otherwise will be treated as regular XML. The data inside this will not be parsed. For example, if you want to pass a URL that contains & in it, you can use CDATA to do it. Otherwise, you will get an error as it will be parsed as regular XML.

Get value from JToken that may not exist (best practices)

I would write GetValue as below

public static T GetValue<T>(this JToken jToken, string key, T defaultValue = default(T))
{
    dynamic ret = jToken[key];
    if (ret == null) return defaultValue;
    if (ret is JObject) return JsonConvert.DeserializeObject<T>(ret.ToString());
    return (T)ret;
}

This way you can get the value of not only the basic types but also complex objects. Here is a sample

public class ClassA
{
    public int I;
    public double D;
    public ClassB ClassB;
}
public class ClassB
{
    public int I;
    public string S;
}

var jt = JToken.Parse("{ I:1, D:3.5, ClassB:{I:2, S:'test'} }");

int i1 = jt.GetValue<int>("I");
double d1 = jt.GetValue<double>("D");
ClassB b = jt.GetValue<ClassB>("ClassB");

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

When I understand this correctly, you replace the default constructor with a parameterized one and therefore have to describe the JSON keys which are used to call the constructor with.

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

This is caused by the account the SQL Server service is run under. For example;

If the SQL Server Service is run under DOMAIN\MyUserAccount then this will need to be a login and set with the relevant Language.

If this account isn't set then SQL Server will default to the sa account and the Language that runs under.

I found that our sa account was set to English which had Monday as DW = 2. The DOMAIN\MyUserAccount Account was setup and changed to British English and DW for Monday was being returned as 1.

Hope this helps

Why are there no ++ and --? operators in Python?

Clarity!

Python is a lot about clarity and no programmer is likely to correctly guess the meaning of --a unless s/he's learned a language having that construct.

Python is also a lot about avoiding constructs that invite mistakes and the ++ operators are known to be rich sources of defects. These two reasons are enough not to have those operators in Python.

The decision that Python uses indentation to mark blocks rather than syntactical means such as some form of begin/end bracketing or mandatory end marking is based largely on the same considerations.

For illustration, have a look at the discussion around introducing a conditional operator (in C: cond ? resultif : resultelse) into Python in 2005. Read at least the first message and the decision message of that discussion (which had several precursors on the same topic previously).

Trivia: The PEP frequently mentioned therein is the "Python Extension Proposal" PEP 308. LC means list comprehension, GE means generator expression (and don't worry if those confuse you, they are none of the few complicated spots of Python).

Inserting an image with PHP and FPDF

I figured it out, and it's actually pretty straight forward.

Set your variable:

$image1 = "img/products/image1.jpg";

Then ceate a cell, position it, then rather than setting where the image is, use the variable you created above with the following:

$this->Cell( 40, 40, $pdf->Image($image1, $pdf->GetX(), $pdf->GetY(), 33.78), 0, 0, 'L', false );

Now the cell will move up and down with content if other cells around it move.

Hope this helps others in the same boat.

Where is NuGet.Config file located in Visual Studio project?

There are multiple nuget packages read in the following order:

  1. First the NuGetDefaults.Config file. You will find this in %ProgramFiles(x86)%\NuGet\Config.
  2. The computer-level file.
  3. The user-level file. You will find this in %APPDATA%\NuGet\nuget.config.
  4. Any file named nuget.config beginning from the root of your drive up to the directory where nuget.exe is called.
  5. The config file you specify in the -configfile option when calling nuget.exe

You can find more information here.

How to extract this specific substring in SQL Server?

select substring(your_field, CHARINDEX(';',your_field)+1 ,CHARINDEX('[',your_field)-CHARINDEX(';',your_field)-1) from your_table

Can't get the others to work. I believe you just want what is in between ';' and '[' in all cases regardless of how long the string in between is. After specifying the field in the substring function, the second argument is the starting location of what you will extract. That is, where the ';' is + 1 (fourth position - the c), because you don't want to include ';'. The next argument takes the location of the '[' (position 14) and subtracts the location of the spot after the ';' (fourth position - this is why I now subtract 1 in the query). This basically says substring(field,location I want substring to begin, how long I want substring to be). I've used this same function in other cases. If some of the fields don't have ';' and '[', you'll want to filter those out in the "where" clause, but that's a little different than the question. If your ';' was say... ';;;', you would use 3 instead of 1 in the example. Hope this helps!

read file from assets

It maybe too late but for the sake of others who look for the peachy answers :

public static String loadAssetFile(Context context, String fileName) {
    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(context.getAssets().open(fileName)));
        StringBuilder out= new StringBuilder();
        String eachline = bufferedReader.readLine();
        while (eachline != null) {
            out.append(eachline);
            eachline = bufferedReader.readLine();
        }
        return out.toString();
    } catch (IOException e) {
        Log.e("Load Asset File",e.toString());
    }
    return null;
}

Calling dynamic function with dynamic number of parameters

Use the apply method of a function:-

function mainfunc (func){
    window[func].apply(null, Array.prototype.slice.call(arguments, 1));
} 

Edit: It occurs to me that this would be much more useful with a slight tweak:-

function mainfunc (func){
    this[func].apply(this, Array.prototype.slice.call(arguments, 1));
} 

This will work outside of the browser (this defaults to the global space). The use of call on mainfunc would also work:-

function target(a) {
    alert(a)
}

var o = {
    suffix: " World",
    target: function(s) { alert(s + this.suffix); }
};

mainfunc("target", "Hello");

mainfunc.call(o, "target", "Hello");

IIS URL Rewrite and Web.config

1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.

2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):

This rule will do SINGLE EXACT rewrite (internal redirect) /page to /page.html. URL in browser will remain unchanged.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRewrite" stopProcessing="true">
                <match url="^page$" />
                <action type="Rewrite" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page it will check if /page.html exists, and if it does then rewrite occurs):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="DynamicRewrite" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
                </conditions>
                <action type="Rewrite" url="/{R:1}.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Ruby max integer

There is no maximum since Ruby 2.4, as Bignum and Fixnum got unified into Integer. see Feature #12005

> (2 << 1000).is_a? Fixnum
(irb):322: warning: constant ::Fixnum is deprecated
=> true

> 1.is_a? Bignum
(irb):314: warning: constant ::Bignum is deprecated
=> true

> (2 << 1000).class
=> Integer

There won't be any overflow, what would happen is an out of memory.

Location of WSDL.exe

If you have Windows 10 and VS2015, below you can see the Location of WSDL.exe

Path in your pc C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7 Tools