Programs & Examples On #Patch

A patch is a piece of software designed to fix problems with, or update a computer program or its supporting data. This includes fixing security vulnerabilities and other bugs, and improving the usability or performance.

Using python's mock patch.object to change the return value of a method called within another method

To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:

Given the following function to test, located in module.a_function.to_test.py:

from some_other.module import SomeOtherClass

def add_results():
    my_object = SomeOtherClass('some_contextual_parameters')
    result_a = my_object.method_a()
    result_b = my_object.method_b()
    
    return result_a + result_b

To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass by using patch.object() in combination with sys.modules:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  mocked_other_class().method_a.return_value = 4
  mocked_other_class().method_b.return_value = 7

  self.assertEqual(add_results(), 11)

This works no matter the number of methods of SomeOtherClass you need to patch, with independent results.

Also, using the same patching method, an actual instance of SomeOtherClass can be returned if need be:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  other_class_instance = SomeOtherClass('some_controlled_parameters')
  mocked_other_class.return_value = other_class_instance 
  ...

How to generate a git patch for a specific commit?

To generate path from a specific commit (not the last commit):

git format-patch -M -C COMMIT_VALUE~1..COMMIT_VALUE

How to apply `git diff` patch without Git installed?

I use

patch -p1 --merge < patchfile

This way, conflicts may be resolved as usual.

What is the main difference between PATCH and PUT request?

put:
If I want to update my first name, then I send a put request:

{ "first": "Nazmul", "last": "hasan" } 

But here is a problem with using put request: When I want to send put request I have to send all two parameters that is first and last (whereas I only need to update first) so it is mandatory to send them all again with put request.

patch:
patch request, on the other hand, says: only specify the data which you need to update and it won't be affecting or changing other data.
So no need to send all values again. Do I only need to change first name? Well, It only suffices to specify first in patch request.

How do I apply a diff patch on Windows?

EDIT: Looking at the replies so far, it seems that Tortoise will only do it right if it's a file that's already versioned. That's not the case here. I need to be able to apply a patch to a file that did not come out of an SVN repository. I just tried using Tortoise because I happen to know that SVN uses diffs and has to know how to both create them and apply them.

You can install Cygwin, then use the command-line patch tool to apply the patch. See also this Unix man page, which applies to patch.

How to move certain commits to be based on another branch in git?

The simplest thing you can do is cherry picking a range. It does the same as the rebase --onto but is easier for the eyes :)

git cherry-pick quickfix1..quickfix2

Create patch or diff file from git repository and apply it to another different git repository

you can apply two commands

  1. git diff --patch > mypatch.patch // to generate the patch
  2. git apply mypatch.patch // to apply the patch

How to check Oracle patches are installed?

Maybe you need "sys." before:

select * from sys.registry$history;

JSON.stringify doesn't work with normal Javascript array

I posted a fix for this here

You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):

// Upgrade for JSON.stringify, updated to allow arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

how to modify an existing check constraint?

Create a new constraint first and then drop the old one.
That way you ensure that:

  • constraints are always in place
  • existing rows do not violate new constraints
  • no illegal INSERT/UPDATEs are attempted after you drop a constraint and before a new one is applied.

MySQL: Get column name or alias from query

I think this should do what you need (builds on the answer above) . I am sure theres a more pythony way to write it, but you should get the general idea.

cursor.execute(query)
columns = cursor.description
result = []
for value in cursor.fetchall():
    tmp = {}
    for (index,column) in enumerate(value):
        tmp[columns[index][0]] = column
    result.append(tmp)
pprint.pprint(result)

How do you list the primary key of a SQL Server table?

Is using MS SQL Server you can do the following:

--List all tables primary keys
select * from information_schema.table_constraints
where constraint_type = 'Primary Key'

You can also filter on the table_name column if you want a specific table.

Git: Create a branch from unstaged/uncommitted changes on master

In the latest GitHub client for Windows, if you have uncommitted changes, and choose to create a new branch.
It prompts you how to handle this exact scenario:

enter image description here

The same applies if you simply switch the branch too.

Compare two dates with JavaScript

The Date object will do what you want - construct one for each date, then compare them using the >, <, <= or >=.

The ==, !=, ===, and !== operators require you to use date.getTime() as in

var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();

to be clear just checking for equality directly with the date objects won't work

var d1 = new Date();
var d2 = new Date(d1);

console.log(d1 == d2);   // prints false (wrong!) 
console.log(d1 === d2);  // prints false (wrong!)
console.log(d1 != d2);   // prints true  (wrong!)
console.log(d1 !== d2);  // prints true  (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)

I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.

HTML5 Dynamically create Canvas

Via Jquery:

$('<canvas/>', { id: 'mycanvas', height: 500, width: 200});

http://jsfiddle.net/8DEsJ/736/

Google Chrome "window.open" workaround?

Why is this still so complicated in 2021? For me I wanted to open in a new chrome window fullscreen so I used the below:

window.open("http://my.url.com", "", "fullscreen=yes");

This worked as exepected opening a new chrome window. Without the options at the end it will only open a new tab

Get exit code for command in bash/ksh

It should be $cmd instead of $($cmd). Works fine with that on my box.

Edit: Your script works only for one-word commands, like ls. It will not work for "ls cpp". For this to work, replace cmd="$1"; $cmd with "$@". And, do not run your script as command="some cmd"; safeRun command, run it as safeRun some cmd.

Also, when you have to debug your bash scripts, execute with '-x' flag. [bash -x s.sh].

Differences Between vbLf, vbCrLf & vbCr Constants

 Constant   Value               Description
 ----------------------------------------------------------------
 vbCr       Chr(13)             Carriage return
 vbCrLf     Chr(13) & Chr(10)   Carriage return–linefeed combination
 vbLf       Chr(10)             Line feed
  • vbCr : - return to line beginning
    Represents a carriage-return character for print and display functions.

  • vbCrLf : - similar to pressing Enter
    Represents a carriage-return character combined with a linefeed character for print and display functions.

  • vbLf : - go to next line
    Represents a linefeed character for print and display functions.


Read More from Constants Class

Retrieve WordPress root directory path?

I like @Omry Yadan's solution but I think it can be improved upon to use a loop in case you want to continue traversing up the directory tree until you find where wp-config.php actually lives. Of course, if you don't find it and end up in the server's root then all is lost and we return a sane value (false).

function wp_get_web_root() {

  $base = dirname(__FILE__);
  $path = false;

  while(!$path && '/' != $base) {
    if(@file_exists(dirname($base)).'/wp-config.php') {
      $path = dirname($base);
    } else {
      $base = dirname($base);
    }
  }

  return $path;
}

Unable to use Intellij with a generated sources folder

The fix

Go to Project Structure - Modules - Source Folders and find the target/generated-sources/antlr4/com/mycompany - click Edit properties and set Package prefix to com.mycompany.

This is exactly the reason why we can set Package prefix on source dirs.


Different but related problem here

How to force Sequential Javascript Execution?

Put your code in a string, iterate, eval, setTimeout and recursion to continue with the remaining lines. No doubt I'll refine this or just throw it out if it doesn't hit the mark. My intention is to use it to simulate really, really basic user testing.

The recursion and setTimeout make it sequential.

Thoughts?

var line_pos = 0;
var string =`
    console.log('123');
    console.log('line pos is '+ line_pos);
SLEEP
    console.log('waited');
    console.log('line pos is '+ line_pos);
SLEEP
SLEEP
    console.log('Did i finish?');
`;

var lines = string.split("\n");
var r = function(line_pos){
    for (i = p; i < lines.length; i++) { 
        if(lines[i] == 'SLEEP'){
            setTimeout(function(){r(line_pos+1)},1500);
            return;
        }
        eval (lines[line_pos]);
    }
    console.log('COMPLETED READING LINES');
    return;
}
console.log('STARTED READING LINES');
r.call(this,line_pos);

OUTPUT

STARTED READING LINES
123
124
1 p is 0
undefined
waited
p is 5
125
Did i finish?
COMPLETED READING LINES

How to set the size of a column in a Bootstrap responsive table

you can use the following Bootstrap class with

<tr class="w-25">

</tr>

for more details check the following page https://getbootstrap.com/docs/4.1/utilities/sizing/

Open Jquery modal dialog on click event

May be helpful... :)

$(document).ready(function() {
    $('#buutonId').on('click', function() {
        $('#modalId').modal('open');
    });
});

Posting JSON Data to ASP.NET MVC

If you've got ther JSON data coming in as a string (e.g. '[{"id":1,"name":"Charles"},{"id":8,"name":"John"},{"id":13,"name":"Sally"}]')

Then I'd use JSON.net and use Linq to JSON to get the values out...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

    if (Request["items"] != null)
    {
        var items = Request["items"].ToString(); // Get the JSON string
        JArray o = JArray.Parse(items); // It is an array so parse into a JArray
        var a = o.SelectToken("[0].name").ToString(); // Get the name value of the 1st object in the array
        // a == "Charles"
    }
}
}

Bootstrap 4 - Responsive cards in card-columns

Update 2019 - Bootstrap 4

You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.

.card-columns {
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(sm) {
    column-count: 2;
  }
}

SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX

Or, CSS only like this...

@media (min-width: 576px) {
    .card-columns {
        column-count: 2;
    }
}

@media (min-width: 768px) {
    .card-columns {
        column-count: 3;
    }
}

@media (min-width: 992px) {
    .card-columns {
        column-count: 4;
    }
}

@media (min-width: 1200px) {
    .card-columns {
        column-count: 5;
    }
}

CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ

Spin or rotate an image on hover

Here is my code, this flips on hover and flips back off-hover.

CSS:

.flip-container {
  background: transparent;
  display: inline-block;
}

.flip-this {
  position: relative;
  width: 100%;
  height: 100%;
  transition: transform 0.6s;
  transform-style: preserve-3d;
}

.flip-container:hover .flip-this {
  transition: 0.9s;
  transform: rotateY(180deg);
}

HTML:

<div class="flip-container">
    <div class="flip-this">
        <img width="100" alt="Godot icon" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/Godot_icon.svg/512px-Godot_icon.svg.png">
    </div>
</div>

Fiddle this

JavaScript variable number of arguments to function

While @roufamatic did show use of the arguments keyword and @Ken showed a great example of an object for usage I feel neither truly addressed what is going on in this instance and may confuse future readers or instill a bad practice as not explicitly stating a function/method is intended to take a variable amount of arguments/parameters.

function varyArg () {
    return arguments[0] + arguments[1];
}

When another developer is looking through your code is it very easy to assume this function does not take parameters. Especially if that developer is not privy to the arguments keyword. Because of this it is a good idea to follow a style guideline and be consistent. I will be using Google's for all examples.

Let's explicitly state the same function has variable parameters:

function varyArg (var_args) {
    return arguments[0] + arguments[1];
}

Object parameter VS var_args

There may be times when an object is needed as it is the only approved and considered best practice method of an data map. Associative arrays are frowned upon and discouraged.

SIDENOTE: The arguments keyword actually returns back an object using numbers as the key. The prototypal inheritance is also the object family. See end of answer for proper array usage in JS

In this case we can explicitly state this also. Note: this naming convention is not provided by Google but is an example of explicit declaration of a param's type. This is important if you are looking to create a more strict typed pattern in your code.

function varyArg (args_obj) {
    return args_obj.name+" "+args_obj.weight;
}
varyArg({name: "Brian", weight: 150});

Which one to choose?

This depends on your function's and program's needs. If for instance you are simply looking to return a value base on an iterative process across all arguments passed then most certainly stick with the arguments keyword. If you need definition to your arguments and mapping of the data then the object method is the way to go. Let's look at two examples and then we're done!

Arguments usage

function sumOfAll (var_args) {
    return arguments.reduce(function(a, b) {
        return a + b;
    }, 0);
}
sumOfAll(1,2,3); // returns 6

Object usage

function myObjArgs(args_obj) {
    // MAKE SURE ARGUMENT IS AN OBJECT OR ELSE RETURN
    if (typeof args_obj !== "object") {
        return "Arguments passed must be in object form!";
    }

    return "Hello "+args_obj.name+" I see you're "+args_obj.age+" years old.";
}
myObjArgs({name: "Brian", age: 31}); // returns 'Hello Brian I see you're 31 years old

Accessing an array instead of an object ("...args" The rest parameter)

As mentioned up top of the answer the arguments keyword actually returns an object. Because of this any method you want to use for an array will have to be called. An example of this:

Array.prototype.map.call(arguments, function (val, idx, arr) {});

To avoid this use the rest parameter:

function varyArgArr (...var_args) {
    return var_args.sort();
}
varyArgArr(5,1,3); // returns 1, 3, 5

How to access JSON decoded array in PHP

$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"


$data = json_decode($json);
echo $data[0]->c_name;      // "John"

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

Is there an equivalent to background-size: cover and contain for image elements?

im not allowed to 'add a comment' so doing this , but yea what Eru Penkman did is pretty much spot on , to get it like background cover all you need to do is change

_x000D_
_x000D_
.tall-img{_x000D_
    margin-top:-50%;_x000D_
    width:100%;_x000D_
}_x000D_
.wide-img{_x000D_
    margin-left:-50%;_x000D_
    height:100%;_x000D_
}
_x000D_
_x000D_
_x000D_

TO

_x000D_
_x000D_
.wide-img{_x000D_
    margin-left:-42%;_x000D_
    height:100%;_x000D_
}_x000D_
.tall-img{_x000D_
    margin-top:-42%;_x000D_
    width:100%;_x000D_
}
_x000D_
_x000D_
_x000D_

Find the max of 3 numbers in Java with different data types

Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).

disable a hyperlink using jQuery

function EnableHyperLink(id) {
        $('#' + id).attr('onclick', 'Pagination("' + id + '")');//onclick event which u 
        $('#' + id).addClass('enable-link');
        $('#' + id).removeClass('disable-link');
    }

    function DisableHyperLink(id) {
        $('#' + id).addClass('disable-link');
        $('#' + id).removeClass('enable-link');
        $('#' + id).removeAttr('onclick');
    }

.disable-link
{
    text-decoration: none !important;
    color: black !important;
    cursor: default;
}
.enable-link
{
    text-decoration: underline !important;
    color: #075798 !important;
    cursor: pointer !important;
}

Function overloading in Python: Missing

Oftentimes you see the suggestion use use keyword arguments, with default values, instead. Look into that.

Convert List to Pandas Dataframe Column

Use:

L = ['Thanks You', 'Its fine no problem', 'Are you sure']

#create new df 
df = pd.DataFrame({'col':L})
print (df)

                   col
0           Thanks You
1  Its fine no problem
2         Are you sure

df = pd.DataFrame({'oldcol':[1,2,3]})

#add column to existing df 
df['col'] = L
print (df)
   oldcol                  col
0       1           Thanks You
1       2  Its fine no problem
2       3         Are you sure

Thank you DYZ:

#default column name 0
df = pd.DataFrame(L)
print (df)
                     0
0           Thanks You
1  Its fine no problem
2         Are you sure

How to do this in Laravel, subquery where in

Laravel 4.2 and beyond, may use try relationship querying:-

Products::whereHas('product_category', function($query) {
$query->whereIn('category_id', ['223', '15']);
});

public function product_category() {
return $this->hasMany('product_category', 'product_id');
}

How do I dynamically assign properties to an object in TypeScript?

To preserve your previous type, temporary cast your object to any

  var obj = {}
  (<any>obj).prop = 5;

The new dynamic property will only be available when you use the cast:

  var a = obj.prop; ==> Will generate a compiler error
  var b = (<any>obj).prop; ==> Will assign 5 to b with no error;

How to turn off caching on Firefox?

I use CTRL-SHIFT-DELETE which activates the privacy feature, allowing you to clear your cache, reset cookies, etc, all at once. You can even configure it so that it just DOES it, instead of popping up a dialog box asking you to confirm.

Gradle does not find tools.jar

On windows 10, I encounter the same problem and this how I fixed the issue;

  1. Access Advance System Settings>Environment Variables>System Variables
  2. Select PATH overwrite the default C:\ProgramData\Oracle\Java\javapath
  3. With your own jdk installation that is JAVA_HOME=C:\Program Files\Java\jdk1.8.0_162

open read and close a file in 1 line of code

Using more_itertools.with_iter, it is possible to open, read, close and assign an equivalent output in one line (excluding the import statement):

import more_itertools as mit


output = "".join(line for line in mit.with_iter(open("pagehead.section.htm", "r")))

Although possible, I would look for another approach other than assigning the contents of a file to a variable, i.e. lazy iteration - this can be done using a traditional with block or in the example above by removing join() and iterating output.

How to start a background process in Python?

You probably want the answer to "How to call an external command in Python".

The simplest approach is to use the os.system function, e.g.:

import os
os.system("some_command &")

Basically, whatever you pass to the system function will be executed the same as if you'd passed it to the shell in a script.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I also got the same issue of IE9 rendering in IE7 Document standards for local host. I tried many conditional comments tags but unsuccesful. In the end I just removed all conditional tags and just added meta tag immediatly after head like below and it worked like charm.

<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Hope it helps

Python - round up to the nearest ten

round does take negative ndigits parameter!

>>> round(46,-1)
50

may solve your case.

How to deep watch an array in angularjs?

$watchCollection accomplishes what you want to do. Below is an example copied from angularjs website http://docs.angularjs.org/api/ng/type/$rootScope.Scope While it's convenient, the performance needs to be taken into consideration especially when you watch a large collection.

  $scope.names = ['igor', 'matias', 'misko', 'james'];
  $scope.dataCount = 4;

  $scope.$watchCollection('names', function(newNames, oldNames) {
     $scope.dataCount = newNames.length;
  });

  expect($scope.dataCount).toEqual(4);
  $scope.$digest();

  //still at 4 ... no changes
  expect($scope.dataCount).toEqual(4);

  $scope.names.pop();
  $scope.$digest();

  //now there's been a change
  expect($scope.dataCount).toEqual(3);

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

How to upgrade safely php version in wamp server

  1. Simply Download the PHP version that you want from this url: http://wampserver.aviatechno.net/
  2. Goto your wamp\bin\php directory and extract it like this(Note: you need to rename your folder to phpversionOfPhp list of installed version in the directory
  3. Start wamp and click wamp icon and choose the version of php you want to use: https://gyazo.com/de5727d7e254795e238422783dec3758

Remove duplicate rows in MySQL

Simple and fast for all cases:

CREATE TEMPORARY TABLE IF NOT EXISTS _temp_duplicates AS (SELECT dub.id FROM table_with_duplications dub GROUP BY dub.field_must_be_uniq_1, dub.field_must_be_uniq_2 HAVING COUNT(*)  > 1);

DELETE FROM table_with_duplications WHERE id IN (SELECT id FROM _temp_duplicates);

Support for "border-radius" in IE

Yes! When IE9 is released in Jan 2011.

Let's say you want an even 15px on all four sides:

.myclass {
 border-style: solid;
 border-width: 2px;
 -moz-border-radius: 15px;
 -webkit-border-radius: 15px;
 border-radius: 15px;
}

IE9 will use the default border-radius, so just make sure you include that in all your styles calling a border radius. Then your site will be ready for IE9.

-moz-border-radius is for Firefox, -webkit-border-radius is for Safari and Chrome.

Furthermore: don't forget to declare your IE coding is ie9:

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

Some lazy developers have <meta http-equiv="X-UA-Compatible" content="IE=7" />. If that tag exists, border-radius will never work in IE.

How do I schedule jobs in Jenkins?

Jenkins lets you set up multiple times, separated by line breaks.

If you need it to build daily at 7 am, along with every Sunday at 4 pm, the below works well.

H 7 * * *

H 16 * * 0

How to retrieve Jenkins build parameters using the Groovy API?

Get all of the parameters:

System.getenv().each{
  println it
}

Or more sophisticated:

def myvariables = getBinding().getVariables()
for (v in myvariables) {
   echo "${v} " + myvariables.get(v)
}

You will need to disable "Use Groovy Sandbox" for both.

Binding ng-model inside ng-repeat loop in AngularJS

<h4>Order List</h4>
<ul>
    <li ng-repeat="val in filter_option.order">
        <span>
            <input title="{{filter_option.order_name[$index]}}" type="radio" ng-model="filter_param.order_option" ng-value="'{{val}}'" />
            &nbsp;{{filter_option.order_name[$index]}}
        </span>
        <select title="" ng-model="filter_param[val]">
            <option value="asc">Asc</option>
            <option value="desc">Desc</option>
        </select>
    </li>
</ul>

how to kill the tty in unix

I had the same question as you but I wanted to kill the gnome terminal which I was in. I read the manual on "who" and found that you can list all of the sessions logged into your computer with the '-a' option and then the '-l' option prints the system login processes.

who -la

What who gave me You should get something like this. Then all you have to do is kill the process with the 'kill' command.

kill <PID>

How can I write to the console in PHP?

I think it can be used --

function jsLogs($data) {
    $html = "";
    $coll;

    if (is_array($data) || is_object($data)) {
        $coll = json_encode($data);
    } else {
        $coll = $data;
    }

    $html = "<script>console.log('PHP: ${coll}');</script>";

    echo($html);
    # exit();
}

# For String
jsLogs("testing string"); #PHP: testing string

# For Array
jsLogs(array("test1", "test2")); # PHP: ["test1","test2"]

# For Object
jsLogs(array("test1"=>array("subtest1", "subtest2"))); #PHP: {"test1":["subtest1","subtest2"]}

How to modify list entries during for loop?

One more for loop variant, looks cleaner to me than one with enumerate():

for idx in range(len(list)):
    list[idx]=... # set a new value
    # some other code which doesn't let you use a list comprehension

ASP.NET MVC 404 Error Handling

In IIS, you can specify a redirect to "certain" page based on error code. In you example, you can configure 404 - > Your customized 404 error page.

What's the best way to get the last element of an array without deleting it?

As of PHP version 7.3 the functions array_key_first and array_key_last has been introduced.

Since arrays in PHP are not strict array types, i.e. fixed sized collections of fixed sized fields starting at index 0, but dynamically extended associative array, the handling of positions with unknown keys is hard and workarounds do not perform very well. In contrast real arrays would be internally addressed via pointer arithmethics very rapidly and the last index is already known at compile-time by declaration.

At least the problem with the first and last position is solved by builtin functions now since version 7.3. This even works without any warnings on array literals out of the box:

$first = array_key_first( [1, 2, 'A'=>65, 'B'=>66, 3, 4 ] );
$last  = array_key_last ( [1, 2, 'A'=>65, 'B'=>66, 3, 4 ] );

Obviously the last value is:

$array[array_key_last($array)];

I do not understand how execlp() works in Linux

The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:

execl("/bin/ls", "ls", "-la", NULL);

The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:

execlp("ls", "ls", "-la", NULL);

jQuery UI Dialog - missing close icon

I was facing same issue , In my case JQuery-ui.js version was 1.10.3, After referring jquery-ui-1.12.1.min.js close button started to visible.

Closing Excel Application Process in C# after Data Access

private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        MessageBox.Show("Unable to release the Object " + ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}

Entity Framework The underlying provider failed on Open

I was facing the same error today, what I was doing wrong was that I was not adding Password tag in the connection string. As soon as I added the Password tag with correct password the error went away. Hope it helps someone.

find path of current folder - cmd

for /f "delims=" %%i in ("%0") do set "curpath=%%~dpi"
echo "%curpath%"

or

echo "%cd%"

The double quotes are needed if the path contains any & characters.

Determine which element the mouse pointer is on top of in JavaScript

Demo :D

Move your mouse in the snippet window :D

_x000D_
_x000D_
<script>
document.addEventListener('mouseover', function (e) {
    console.log ("You are in ", e.target.tagName);
});
</script>
_x000D_
_x000D_
_x000D_

C++ deprecated conversion from string constant to 'char*'

The following illustrates the solution, assign your string to a variable pointer to a constant array of char (a string is a constant pointer to a constant array of char - plus length info):

#include <iostream>

void Swap(const char * & left, const char * & right) {
    const char *const temp = left;
    left = right;
    right = temp;
}

int main() {
    const char * x = "Hello"; // These works because you are making a variable
    const char * y = "World"; // pointer to a constant string
    std::cout << "x = " << x << ", y = " << y << '\n';
    Swap(x, y);
    std::cout << "x = " << x << ", y = " << y << '\n';
}

How to open every file in a folder

Os

You can list all files in the current directory using os.listdir:

import os
for filename in os.listdir(os.getcwd()):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

Glob

Or you can list only some files, depending on the file pattern using the glob module:

import glob
for filename in glob.glob('*.txt'):
   with open(os.path.join(os.cwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

It doesn't have to be the current directory you can list them in any path you want:

path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

Pipe Or you can even use the pipe as you specified using fileinput

import fileinput
for line in fileinput.input():
    # do your stuff

And then use it with piping:

ls -1 | python parse.py

less than 10 add 0 to number

I was bored and playing around JSPerf trying to beat the currently selected answer prepending a zero no matter what and using slice(-2). It's a clever approach but the performance gets a lot worse as the string gets longer.

For numbers zero to ten (one and two character strings) I was able to beat by about ten percent, and the fastest approach was much better when dealing with longer strings by using charAt so it doesn't have to traverse the whole string.

This follow is not quit as simple as slice(-2) but is 86%-89% faster when used across mostly 3 digit numbers (3 character strings).

var prepended = ( 1 === string.length && string.charAt( 0 ) !== "0" ) ? '0' + string : string;

How to refresh or show immediately in datagridview after inserting?

this.donorsTableAdapter.Fill(this.sbmsDataSet.donors);

Java Byte Array to String to Byte Array

Its simple to convert byte array to string and string back to byte array in java. we need to know when to use 'new' in the right way. It can be done as follows:

byte array to string conversion:

byte[] bytes = initializeByteArray();
String str = new String(bytes);

String to byte array conversion:

String str = "Hello"
byte[] bytes = str.getBytes();

For more details, look at: http://evverythingatonce.blogspot.in/2014/01/tech-talkbyte-array-and-string.html

How to merge many PDF files into a single one?

First, get Pdftk:

sudo apt-get install pdftk

Now, as shown on example page, use

pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf

for merging pdf files into one.

Linux find file names with given string recursively

This is a very simple solution using the tree command in the directory you want to search for. -f shows the full file path and | is used to pipe the output of tree to grep to find the file containing the string filename in the name.

tree -f | grep filename

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

This is purely driver registration/deregistration issue in mysql`s driver or tomcats webapp-classloader. Copy mysql driver into tomcats lib folder (so its loaded by jvm directly, not by tomcat), and message will be gone. That makes mysql jdbc driver to be unloaded only at JVM shutdown, and noone cares about memory leaks then.

Delete a row from a SQL Server table

Try with paramter

.....................
.....................

    using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + @IDNumber, con))
             {
                   command.Paramter.Add("@IDNumber",IDNumber)
                   command.ExecuteNonQuery();
             }

.....................
.....................

No need to close connection in using statement

How do I view executed queries within SQL Server Management Studio?

You need a SQL profiler, which actually runs outside SQL Management Studio. If you have a paid version of SQL Server (like the developer edition), it should be included in that as another utility.

If you're using a free edition (SQL Express), they have freeware profiles that you can download. I've used AnjLab's profiler (available at http://sites.google.com/site/sqlprofiler), and it seemed to work well.

Oracle "Partition By" Keyword

EMPNO     DEPTNO DEPT_COUNT

 7839         10          4
 5555         10          4
 7934         10          4
 7782         10          4 --- 4 records in table for dept 10
 7902         20          4
 7566         20          4
 7876         20          4
 7369         20          4 --- 4 records in table for dept 20
 7900         30          6
 7844         30          6
 7654         30          6
 7521         30          6
 7499         30          6
 7698         30          6 --- 6 records in table for dept 30

Here we are getting count for respective deptno. As for deptno 10 we have 4 records in table emp similar results for deptno 20 and 30 also.

Full-screen iframe with a height of 100%

3 approaches for creating a fullscreen iframe:


  • Approach 1 - Viewport-percentage lengths

    In supported browsers, you can use viewport-percentage lengths such as height: 100vh.

    Where 100vh represents the height of the viewport, and likewise 100vw represents the width.

    Example Here

    _x000D_
    _x000D_
    body {_x000D_
        margin: 0;            /* Reset default margin */_x000D_
    }_x000D_
    iframe {_x000D_
        display: block;       /* iframes are inline by default */_x000D_
        background: #000;_x000D_
        border: none;         /* Reset default border */_x000D_
        height: 100vh;        /* Viewport-relative units */_x000D_
        width: 100vw;_x000D_
    }
    _x000D_
    <iframe></iframe>
    _x000D_
    _x000D_
    _x000D_


  • Approach 2 - Fixed positioning

    This approach is fairly straight-forward. Just set the positioning of the fixed element and add a height/width of 100%.

    Example Here

    _x000D_
    _x000D_
    iframe {_x000D_
        position: fixed;_x000D_
        background: #000;_x000D_
        border: none;_x000D_
        top: 0; right: 0;_x000D_
        bottom: 0; left: 0;_x000D_
        width: 100%;_x000D_
        height: 100%;_x000D_
    }
    _x000D_
    <iframe></iframe>
    _x000D_
    _x000D_
    _x000D_


  • Approach 3

    For this last method, just set the height of the body/html/iframe elements to 100%.

    Example Here

    _x000D_
    _x000D_
    html, body {_x000D_
        height: 100%;_x000D_
        margin: 0;         /* Reset default margin on the body element */_x000D_
    }_x000D_
    iframe {_x000D_
        display: block;       /* iframes are inline by default */_x000D_
        background: #000;_x000D_
        border: none;         /* Reset default border */_x000D_
        width: 100%;_x000D_
        height: 100%;_x000D_
    }
    _x000D_
    <iframe></iframe>
    _x000D_
    _x000D_
    _x000D_

Import txt file and having each line as a list

with open('path/to/file') as infile: # try open('...', 'rb') as well
    answer = [line.strip().split(',') for line in infile]

If you want the numbers as ints:

with open('path/to/file') as infile:
    answer = [[int(i) for i in line.strip().split(',')] for line in infile]

how to check if the input is a number or not in C?

The sscanf() solution is better in terms of code lines. My answer here is a user-build function that does almost the same as sscanf(). Stores the converted number in a pointer and returns a value called "val". If val comes out as zero, then the input is in unsupported format, hence conversion failed. Hence, use the pointer value only when val is non-zero.

It works only if the input is in base-10 form.

#include <stdio.h>
#include <string.h>
int CONVERT_3(double* Amt){

    char number[100];

    // Input the Data
    printf("\nPlease enter the amount (integer only)...");
    fgets(number,sizeof(number),stdin);

    // Detection-Conversion begins
    int iters = strlen(number)-2;
    int val = 1;
    int pos;
    double Amount = 0;
    *Amt = 0;
    for(int i = 0 ; i <= iters ; i++ ){
        switch(i){
            case 0:
                if(number[i]=='+'){break;}
                if(number[i]=='-'){val = 2; break;}
                if(number[i]=='.'){val = val + 10; pos = 0; break;}
                if(number[i]=='0'){Amount = 0; break;}
                if(number[i]=='1'){Amount = 1; break;}
                if(number[i]=='2'){Amount = 2; break;}
                if(number[i]=='3'){Amount = 3; break;}
                if(number[i]=='4'){Amount = 4; break;}
                if(number[i]=='5'){Amount = 5; break;}
                if(number[i]=='6'){Amount = 6; break;}
                if(number[i]=='7'){Amount = 7; break;}
                if(number[i]=='8'){Amount = 8; break;}
                if(number[i]=='9'){Amount = 9; break;}
            default:
                switch(number[i]){
                    case '.':
                        val = val + 10;
                        pos = i;
                        break;
                    case '0':
                        Amount = (Amount)*10;
                        break;
                    case '1':
                        Amount = (Amount)*10 + 1;
                        break;
                    case '2':
                        Amount = (Amount)*10 + 2;
                        break;
                    case '3':
                        Amount = (Amount)*10 + 3;
                        break;
                    case '4':
                        Amount = (Amount)*10 + 4;
                        break;
                    case '5':
                        Amount = (Amount)*10 + 5;
                        break;
                    case '6':
                        Amount = (Amount)*10 + 6;
                        break;
                    case '7':
                        Amount = (Amount)*10 + 7;
                        break;
                    case '8':
                        Amount = (Amount)*10 + 8;
                        break;
                    case '9':
                        Amount = (Amount)*10 + 9;
                        break;
                    default:
                        val = 0;
                }
        }
        if( (!val) | (val>20) ){val = 0; break;}// val == 0
    }

    if(val==1){*Amt = Amount;}
    if(val==2){*Amt = 0 - Amount;}
    if(val==11){
        int exp = iters - pos;
        long den = 1;
        for( ; exp-- ; ){
            den = den*10;
        }
        *Amt = Amount/den;
    }
    if(val==12){
        int exp = iters - pos;
        long den = 1;
        for( ; exp-- ; ){
            den = den*10;
        }
        *Amt = 0 - (Amount/den);
    }

    return val;
}


int main(void) {
    double AM = 0;
    int c = CONVERT_3(&AM);
    printf("\n\n%d    %lf\n",c,AM);

    return(0);
}

What is the difference between Sessions and Cookies in PHP?

Cookies are stored in browser as a text file format.It stores limited amount of data, up to 4kb[4096bytes].A single Cookie can not hold multiple values but yes we can have more than one cookie.

Cookies are easily accessible so they are less secure. The setcookie() function must appear BEFORE the tag.

Sessions are stored in server side.There is no such storage limit on session .Sessions can hold multiple variables.Since they are not easily accessible hence are more secure than cookies.

CSS3 scrollbar styling on a div

You're setting overflow: hidden. This will hide anything that's too large for the <div>, meaning scrollbars won't be shown. Give your <div> an explicit width and/or height, and change overflow to auto:

.scroll {
   width: 200px;
   height: 400px;
   overflow: scroll;
}

If you only want to show a scrollbar if the content is longer than the <div>, change overflow to overflow: auto. You can also only show one scrollbar by using overflow-y or overflow-x.

How do you monitor network traffic on the iPhone?

The best solution I have found that Works:

Connect your device thru USB

And type these commands:

  1. rvictl -s UDID - (id of device 20 chars, you can locate 4t in iTunes or organiser in Xcode)

  2. sudo launchctl list com.apple.rpmuxd

  3. sudo tcpdump -n -t -i rvi0 -q tcp
    OR just sudo tcpdump -i rvi0 -n

If rvictl is not working install Xcode

For more info: Remote Virtual Interface

http://useyourloaf.com/blog/2012/02/07/remote-packet-capture-for-ios-devices.html

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

Rounding a double to turn it into an int (java)

Rounding double to the "nearest" integer like this:

1.4 -> 1

1.6 -> 2

-2.1 -> -2

-1.3 -> -1

-1.5 -> -2

private int round(double d){
    double dAbs = Math.abs(d);
    int i = (int) dAbs;
    double result = dAbs - (double) i;
    if(result<0.5){
        return d<0 ? -i : i;            
    }else{
        return d<0 ? -(i+1) : i+1;          
    }
}

You can change condition (result<0.5) as you prefer.

Add an object to a python list

Is your problem similar to this:

l = [[0]] * 4
l[0][0] += 1
print l # prints "[[1], [1], [1], [1]]"

If so, you simply need to copy the objects when you store them:

import copy
l = [copy.copy(x) for x in [[0]] * 4]
l[0][0] += 1
print l # prints "[[1], [0], [0], [0]]"

The objects in question should implement a __copy__ method to copy objects. See the documentation for copy. You may also be interested in copy.deepcopy, which is there as well.

EDIT: Here's the problem:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(wM) # appends the wM object to the list
    wM.reset()           # clears  the wM object

You need to append a copy:

import copy
arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(copy.copy(wM)) # appends a copy to the list
    wM.reset()                      # clears the wM object

But I'm still confused as to where wM is coming from. Won't you just be copying the same wM object over and over, except clearing it after the first time so all the rest will be empty? Or does model() modify the wM (which sounds like a terrible design flaw to me)? And why are you throwing away result?

.htaccess redirect all pages to new domain

If you want to redirect from some location to subdomain you can use:

Redirect 301 /Old-Location/ http://subdomain.yourdomain.com

Add a properties file to IntelliJ's classpath

Perhaps this is a bit off-topic, seeing as the question has already been answered, but I have experienced a similar problem. In my case only some of the unit test resources were copied to the output folder upon compilation. My persistence.xml in the META-INF folder got copied but nothing else.

In the end I "solved" the problem by renaming the problematic files, rebuiling the project and then changing the file names back to the original ones. Do not ask me why this worked but it did. My best guess is that, somehow, my IntelliJ project had gotten a bit out of sync with the file system and the renaming operation triggered some kind of internal "resource rescan".

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

The SUBTOTAL function can be used if you want to get the count respecting any filters you use on the page.

=SUBTOTAL(103, A1:A200)

will help you get count of non-empty rows, respecting filters.

103 - is similar to COUNTA, but ignores empty rows and also respects filters.

Reference : SUBTOTAL function

Detecting scroll direction

I personally use this code to detect scroll direction in javascript... Just you have to define a variable to store lastscrollvalue and then use this if&else

let lastscrollvalue;

function headeronscroll() {

    // document on which scroll event will occur
    var a = document.querySelector('.refcontainer'); 

    if (lastscrollvalue == undefined) {

        lastscrollvalue = a.scrollTop;

        // sets lastscrollvalue
    } else if (a.scrollTop > lastscrollvalue) {

        // downscroll rules will be here
        lastscrollvalue = a.scrollTop;

    } else if (a.scrollTop < lastscrollvalue) {

        // upscroll rules will be here
        lastscrollvalue = a.scrollTop;

    }
}

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

commons-logging-1.1.1.jar or jcl-over-slf4j-1.7.6.jar al

If you are using maven, use the below code.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>${slf4j.version}</version>
</dependency>

apc vs eaccelerator vs xcache

I think APC is the way to go unless you are using Zend Optimizer on the site. APC is incompatible with Zend Optimizer so in that case you will need to go with something like eAccelerator.

Command /usr/bin/codesign failed with exit code 1

What worked for me was to realize that Xcode did not have access to the certificates. Please check that your certs are accessible by Xcode. Go to Keychain Access -> Certificates -> Open the Cert and double click on the private key -> Select Access Control

enter image description here

Can I define a class name on paragraph using Markdown?

It should also be mentioned that <span> tags allow inside them -- block-level items negate MD natively inside them unless you configure them not to do so, but in-line styles natively allow MD within them. As such, I often do something akin to...

This is a superfluous paragraph thing.

<span class="class-red">And thus I delve into my topic, Lorem ipsum lollipop bubblegum.</span>

And thus with that I conclude.

I am not 100% sure if this is universal but seems to be the case in all MD editors I've used.

Java: convert seconds to minutes, hours and days

It should be like:

    public static void calculateTime(long seconds) {
            int day = (int)TimeUnit.SECONDS.toDays(seconds);        
            long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
            long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
            long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);

            System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);

        }

Explanation:

TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours with out consideration for days. Minus the hours for days you already got i.e, day*24. You now got remaining hours. Same for minute and second. You need to minus the already got hour and minutes respectively.

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

How to make URL/Phone-clickable UILabel?

You can make a custom UIButton and setText what ever you want and add a method with that.

UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(kLeftMargin, 10, self.view.bounds.size.width - kLeftMargin - kRightMargin, 52)];
[sampleButton setTitle:@"URL Text" forState:UIControlStateNormal];
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]];


[sampleButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sampleButton];


-(void)buttonPressed:(id)sender{
  // open url
}

Use LIKE %..% with field values in MySQL

Use:

SELECT t1.Notes, 
       t2.Name
  FROM Table1 t1
  JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')

Get absolute path of initially run script

If you want to get current working directory use getcwd()

http://php.net/manual/en/function.getcwd.php

__FILE__ will return path with filename for example on XAMPP C:\xampp\htdocs\index.php instead of C:\xampp\htdocs\

Calculate distance between two points in google maps V3

OFFLINE SOLUTION - Haversine Algorithm

In Javascript

var _eQuatorialEarthRadius = 6378.1370;
var _d2r = (Math.PI / 180.0);

function HaversineInM(lat1, long1, lat2, long2)
{
    return (1000.0 * HaversineInKM(lat1, long1, lat2, long2));
}

function HaversineInKM(lat1, long1, lat2, long2)
{
    var dlong = (long2 - long1) * _d2r;
    var dlat = (lat2 - lat1) * _d2r;
    var a = Math.pow(Math.sin(dlat / 2.0), 2.0) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r) * Math.pow(Math.sin(dlong / 2.0), 2.0);
    var c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
    var d = _eQuatorialEarthRadius * c;

    return d;
}

var meLat = -33.922982;
var meLong = 151.083853;


var result1 = HaversineInKM(meLat, meLong, -32.236457779983745, 148.69094705162837);
var result2 = HaversineInKM(meLat, meLong, -33.609020205923713, 150.77061469270831);

C#

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");

        var meLat = -33.922982;
        double meLong = 151.083853;


        var result1 = HaversineInM(meLat, meLong, -32.236457779983745, 148.69094705162837);
        var result2 = HaversineInM(meLat, meLong, -33.609020205923713, 150.77061469270831);

        Console.WriteLine(result1);
        Console.WriteLine(result2);
    }

    static double _eQuatorialEarthRadius = 6378.1370D;
    static double _d2r = (Math.PI / 180D);

    private static int HaversineInM(double lat1, double long1, double lat2, double long2)
    {
        return (int)(1000D * HaversineInKM(lat1, long1, lat2, long2));
    }

    private static  double HaversineInKM(double lat1, double long1, double lat2, double long2)
    {
        double dlong = (long2 - long1) * _d2r;
        double dlat = (lat2 - lat1) * _d2r;
        double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
        double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
        double d = _eQuatorialEarthRadius * c;

        return d;
    }
}

Reference: https://en.wikipedia.org/wiki/Great-circle_distance

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

I suppose your dictMap is of type HashMap, which makes it default to HashMap<Object, Object>. If you want it to be more specific, declare it as HashMap<String, ArrayList>, or even better, as HashMap<String, ArrayList<T>>

ASP.NET Core Identity - get current user

I have put something like this in my Controller class and it worked:

IdentityUser user = await userManager.FindByNameAsync(HttpContext.User.Identity.Name);

where userManager is an instance of Microsoft.AspNetCore.Identity.UserManager class (with all weird setup that goes with it).

CSS: Force float to do a whole new line

This is what I did. Seems to work in forcing a new line, but I'm not an html/css guru by any measure.

<p>&nbsp;</p>

Concatenating strings in Razor

the plus works just fine, i personally prefer using the concat function.

var s = string.Concat(string 1, string 2, string, 3, etc)

Laravel - Forbidden You don't have permission to access / on this server

With me the problem appeared to be about the fact that there was no index.php file in the public_html folder. When I typed in this address however: http://azxcvfj.org/public , it worked (this address is just an example. It points to nowhere). This made me think and eventually I solved it by doing the following.

I made a .htaccess file in the app's root folder (the public_html folder) with this contents:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ public/index.php [L]
</IfModule>

And this worked. With this file you are basically saying to the server (Apache) that whenever someone is trying to access the public html folder(http://azxcvfj.org) that someone who is being redirected is redirected to http://azxcvfj.org/public/index.php

How to overplot a line on a scatter plot in python?

plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

versus

plt.plot(X_plot, X_plot*results.params[1] + results.params[0])

How to do logging in React Native?

There are two options to debug or get output of your react native application when using

Emulator or Real Device

For First Using Emulator: use

react-native log-android or react-native log-ios

to get the log output

on real device.shake your device

so the menu will come from where you select remote debug and it will open this screen in your browser. so you can see your log output in console tab.enter image description here

How to create multiple output paths in Webpack config

You definitely can return array of configurations from your webpack.config file. But it's not an optimal solution if you just want a copy of artifacts to be in the folder of your project's documentation, since it makes webpack build your code twice doubling the overall time to build.

In this case I'd recommend to use the FileManagerWebpackPlugin plugin instead:

const FileManagerPlugin = require('filemanager-webpack-plugin');
// ...
plugins: [
    // ...
    new FileManagerPlugin({
      onEnd: {
        copy: [{
          source: './dist/*.*',
          destination: './public/',
        }],
      },
    }),
],

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

MySQL LIKE IN()?

Paul Dixon's answer worked brilliantly for me. To add to this, here are some things I observed for those interested in using REGEXP:

To Accomplish multiple LIKE filters with Wildcards:

 SELECT * FROM fiberbox WHERE field LIKE '%1740 %'
                           OR field LIKE '%1938 %'
                           OR field LIKE '%1940 %';  

Use REGEXP Alternative:

 SELECT * FROM fiberbox WHERE field REGEXP '1740 |1938 |1940 ';

Values within REGEXP quotes and between the | (OR) operator are treated as wildcards. Typically, REGEXP will require wildcard expressions such as (.*)1740 (.*) to work as %1740 %.

If you need more control over placement of the wildcard, use some of these variants:

To Accomplish LIKE with Controlled Wildcard Placement:

SELECT * FROM fiberbox WHERE field LIKE '1740 %'
                          OR field LIKE '%1938 '
                          OR field LIKE '%1940 % test';  

Use:

SELECT * FROM fiberbox WHERE field REGEXP '^1740 |1938 $|1940 (.*) test';
  • Placing ^ in front of the value indicates start of the line.

  • Placing $ after the value indicates end of line.

  • Placing (.*) behaves much like the % wildcard.

  • The . indicates any single character, except line breaks. Placing . inside () with * (.*) adds a repeating pattern indicating any number of characters till end of line.

There are more efficient ways to narrow down specific matches, but that requires more review of Regular Expressions. NOTE: Not all regex patterns appear to work in MySQL statements. You'll need to test your patterns and see what works.

Finally, To Accomplish Multiple LIKE and NOT LIKE filters:

SELECT * FROM fiberbox WHERE field LIKE '%1740 %'
                          OR field LIKE '%1938 %'
                          OR field NOT LIKE '%1940 %'
                          OR field NOT LIKE 'test %'
                          OR field = '9999';

Use REGEXP Alternative:

SELECT * FROM fiberbox WHERE field REGEXP '1740 |1938 |^9999$'
                          OR field NOT REGEXP '1940 |^test ';

OR Mixed Alternative:

SELECT * FROM fiberbox WHERE field REGEXP '1740 |1938 '
                          OR field NOT REGEXP '1940 |^test '
                          OR field NOT LIKE 'test %'
                          OR field = '9999';

Notice I separated the NOT set in a separate WHERE filter. I experimented with using negating patterns, forward looking patterns, and so on. However, these expressions did not appear to yield the desired results. In the first example above, I use ^9999$ to indicate exact match. This allows you to add specific matches with wildcard matches in the same expression. However, you can also mix these types of statements as you can see in the second example listed.

Regarding performance, I ran some minor tests against an existing table and found no differences between my variations. However, I imagine performance could be an issue with bigger databases, larger fields, greater record counts, and more complex filters.

As always, use logic above as it makes sense.

If you want to learn more about regular expressions, I recommend www.regular-expressions.info as a good reference site.

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

This seems to be problem in your case. The relative path of your activity in manifest is not correct:

<activity android:name="android.app.POMActivity"

replace this with :

<activity android:name=".POMActivity"

or

<activity android:name="com.irrlicht.example1.POMActivity"

How to install APK from PC?

Just connect the device to the PC with a USB cable, then copy the .apk file to the device. On the device, touch the APK file in the file explorer to install it.

You could also offer the .apk on your website. People can download it, then touch it to install.

Get difference between two dates in months using Java

You can try this:

Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);

I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar from a Date and just get the month's diff.

Push Notifications in Android Platform

My understanding/experience with Android push notification are:

  1. C2DM GCM - If your target android platform is 2.2+, then go for it. Just one catch, device users have to be always logged with a Google Account to get the messages.

  2. MQTT - Pub/Sub based approach, needs an active connection from device, may drain battery if not implemented sensibly.

  3. Deacon - May not be good in a long run due to limited community support.

Edit: Added on November 25, 2013

GCM - Google says...

For pre-3.0 devices, this requires users to set up their Google account on their mobile devices. A Google account is not a requirement on devices running Android 4.0.4 or higher.*

What's the difference between implementation and compile in Gradle?

+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| Name               | Role                 | Consumable? | Resolveable? | Description                             |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| api                | Declaring            |      no     |      no      | This is where you should declare        |
|                    | API                  |             |              | dependencies which are transitively     |
|                    | dependencies         |             |              | exported to consumers, for compile.     |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| implementation     | Declaring            |      no     |      no      | This is where you should                |
|                    | implementation       |             |              | declare dependencies which are          |
|                    | dependencies         |             |              | purely internal and not                 |
|                    |                      |             |              | meant to be exposed to consumers.       |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| compileOnly        | Declaring compile    |     yes     |      yes     | This is where you should                |
|                    | only                 |             |              | declare dependencies                    |
|                    | dependencies         |             |              | which are only required                 |
|                    |                      |             |              | at compile time, but should             |
|                    |                      |             |              | not leak into the runtime.              |
|                    |                      |             |              | This typically includes dependencies    |
|                    |                      |             |              | which are shaded when found at runtime. |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| runtimeOnly        | Declaring            |      no     |      no      | This is where you should                |
|                    | runtime              |             |              | declare dependencies which              |
|                    | dependencies         |             |              | are only required at runtime,           |
|                    |                      |             |              | and not at compile time.                |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| testImplementation | Test dependencies    |      no     |      no      | This is where you                       |
|                    |                      |             |              | should declare dependencies             |
|                    |                      |             |              | which are used to compile tests.        |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| testCompileOnly    | Declaring test       |     yes     |      yes     | This is where you should                |
|                    | compile only         |             |              | declare dependencies                    |
|                    | dependencies         |             |              | which are only required                 |
|                    |                      |             |              | at test compile time,                   |
|                    |                      |             |              | but should not leak into the runtime.   |
|                    |                      |             |              | This typically includes dependencies    |
|                    |                      |             |              | which are shaded when found at runtime. |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| testRuntimeOnly    | Declaring test       |      no     |      no      | This is where you should                |
|                    | runtime dependencies |             |              | declare dependencies which              |
|                    |                      |             |              | are only required at test               |
|                    |                      |             |              | runtime, and not at test compile time.  |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+

GitHub - List commits by author

If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:

Screenshot showing where to click to filter down commits

You can also click the 'n commits' link below their name on the repo's "contributors" page:

Another screenshot

Alternatively, you can directly append ?author=<theusername> or ?author=<emailaddress> to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:

Screenshot with only Dave Methvin's commits

For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress> to the URL - the author's name will not be clickable from the commits list.


You can also get the list of commits by a particular author from the command line using

git log --author=[your git name]

Example:

git log --author=Prem

Filtering Table rows using Jquery

I chose @nrodic's answer (thanks, by the way), but it has several drawbacks:

1) If you have rows containing "cat", "dog", "mouse", "cat dog", "cat dog mouse" (each on separate row), then when you search explicitly for "cat dog mouse", you'll be displayed "cat", "dog", "mouse", "cat dog", "cat dog mouse" rows.

2) .toLowerCase() was not implemented, that is, when you enter lower case string, rows with matching upper case text will not be showed.

So I came up with a fork of @nrodic's code, where

var data = this.value; //plain text, not an array

and

jo.filter(function (i, v) {
    var $t = $(this);
    var stringsFromRowNodes = $t.children("td:nth-child(n)")
    .text().toLowerCase();
    var searchText = data.toLowerCase();
    if (stringsFromRowNodes.contains(searchText)) {
        return true;
        }
    return false;
})
//show the rows that match.
.show();

Here goes the full code: http://jsfiddle.net/jumasheff/081qyf3s/

Is there any option to limit mongodb memory usage?

If you are running MongoDB 3.2 or later version, you can limit the wiredTiger cache as mentioned above.

In /etc/mongod.conf add the wiredTiger part

...
# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
        cacheSizeGB: 1
...

This will limit the cache size to 1GB, more info in Doc

This solved the issue for me, running ubuntu 16.04 and mongoDB 3.2

PS: After changing the config, restart the mongo daemon.

$ sudo service mongod restart

# check the status
$ sudo service mongod status

php: Get html source code with cURL

Try the following:

$ch = curl_init("http://www.example-webpage.com/file.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);

I would only recommend this for small files. Big files are read as a whole and are likely to produce a memory error.


EDIT: after some discussion in the comments we found out that the problem was that the server couldn't resolve the host name and the page was in addition a HTTPS resource so here comes your temporary solution (until your server admin fixes the name resolving).

what i did is just pinging graph.facebook.com to see the IP address, replace the host name with the IP address and instead specify the header manually. This however renders the SSL certificate invalid so we have to suppress peer verification.

//$url = "https://graph.facebook.com/19165649929?fields=name";
$url = "https://66.220.146.224/19165649929?fields=name";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: graph.facebook.com'));
$output = curl_exec($ch);
curl_close($ch); 

Keep in mind that the IP address might change and this is an error source. you should also do some error handling using curl_error();.

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

How do I pass JavaScript variables to PHP?

We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

So it's better to use the AJAX to parse the JavaScript value into the php Code.

Or alternatively we can make this done with the help of COOKIES in our code.

Thanks & Cheers.

MySQL error - #1062 - Duplicate entry ' ' for key 2

In addition to Sabeen's answer:

The first column id is your primary key.
Don't insert '' into the primary key, but insert null instead.

INSERT INTO users
  (`id`,`title`,`firstname`,`lastname`,`company`,`address`,`city`,`county`
   ,`postcode`,`phone`,`mobile`,`category`,`email`,`password`,`userlevel`) 
VALUES     
  (null,'','John','Doe','company','Streeet','city','county'
  ,'postcode','phone','','category','[email protected]','','');

If it's an autoincrement key this will fix your problem.
If not make id an autoincrement key, and always insert null into it to trigger an autoincrement.

MySQL has a setting to autoincrement keys only on null insert or on both inserts of 0 and null. Don't count on this setting, because your code may break if you change server.
If you insert null your code will always work.

See: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Bootstrap - 5 column layout

Put some margin-left in all green divs but not in the first

Processing Symbol Files in Xcode

In Xcode Version 6.1.1 (6A2008a), after "Processing Symbol Files", a folder containing symbols associated with the device (including iOS version and CPU type) was created in ~/Library/Developer/Xcode/iOS DeviceSupport/ like this:

enter image description here

Submit form without reloading page

I guess this is what you need. Try this .

<form action="" method="get">
                <input name="search" type="text">
                <input type="button" value="Search" onclick="return updateTable();">
                </form>

and your javascript code is the same

function updateTable()
    {   
        var photoViewer = document.getElementById('photoViewer');
        var photo = document.getElementById('photo1').href;
        var numOfPics = 5;
        var columns = 3; 
        var rows = Math.ceil(numOfPics/columns);
        var content="";
        var count=0;

        content = "<table class='photoViewer' id='photoViewer'>";
            for (r = 0; r < rows; r++) {
                content +="<tr>";
                for (c = 0; c < columns; c++) {
                    count++;
                    if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
                        content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
                }
                content +="</tr>";
            }
        content += "</table>";

        photoViewer.innerHTML = content; 
}

How to assign colors to categorical variables in ggplot2 that have stable mapping?

Based on the very helpful answer by joran I was able to come up with this solution for a stable color scale for a boolean factor (TRUE, FALSE).

boolColors <- as.character(c("TRUE"="#5aae61", "FALSE"="#7b3294"))
boolScale <- scale_colour_manual(name="myboolean", values=boolColors)

ggplot(myDataFrame, aes(date, duration)) + 
  geom_point(aes(colour = myboolean)) +
  boolScale

Since ColorBrewer isn't very helpful with binary color scales, the two needed colors are defined manually.

Here myboolean is the name of the column in myDataFrame holding the TRUE/FALSE factor. date and duration are the column names to be mapped to the x and y axis of the plot in this example.

Getting index value on razor foreach

//this gets you both the item (myItem.value) and its index (myItem.i)
@foreach (var myItem in Model.Members.Select((value,i) => new {i, value}))
{
    <li>The index is @myItem.i and a value is @myItem.value.Name</li>
}

More info on my blog post http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/

OnClick vs OnClientClick for an asp:CheckBox?

I was cleaning up warnings and messages and see that VS does warn about it: Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.

How to insert data to MySQL having auto incremented primary key?

Check out this post

According to it

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

What is the best way to call a script from another script?

This is possible in Python 2 using

execfile("test2.py")

See the documentation for the handling of namespaces, if important in your case.

In Python 3, this is possible using (thanks to @fantastory)

exec(open("test2.py").read())

However, you should consider using a different approach; your idea (from what I can see) doesn't look very clean.

Corrupt jar file

Also, make sure that the java version used at runtime is an equivalent or later version than the java used during compilation

Android lollipop change navigation bar color

Here is how to do it programatically:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {                
   getWindow().setNavigationBarColor(getResources().getColor(R.color.your_awesome_color));
}

Using Compat library:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.primary));
}

Here is how to do it with xml in the values-v21/style.xml folder:

<item name="android:navigationBarColor">@color/your_color</item>

How to Resize a Bitmap in Android?

Try this: This function resizes a bitmap proportionally. When the last parameter is set to "X" the newDimensionXorY is treated as s new width and when set to "Y" a new height.

public Bitmap getProportionalBitmap(Bitmap bitmap, 
                                    int newDimensionXorY, 
                                    String XorY) {
    if (bitmap == null) {
        return null;
    }

    float xyRatio = 0;
    int newWidth = 0;
    int newHeight = 0;

    if (XorY.toLowerCase().equals("x")) {
        xyRatio = (float) newDimensionXorY / bitmap.getWidth();
        newHeight = (int) (bitmap.getHeight() * xyRatio);
        bitmap = Bitmap.createScaledBitmap(
            bitmap, newDimensionXorY, newHeight, true);
    } else if (XorY.toLowerCase().equals("y")) {
        xyRatio = (float) newDimensionXorY / bitmap.getHeight();
        newWidth = (int) (bitmap.getWidth() * xyRatio);
        bitmap = Bitmap.createScaledBitmap(
            bitmap, newWidth, newDimensionXorY, true);
    }
    return bitmap;
}

What is the difference between encrypting and signing in asymmetric encryption?

Signing indicates you really are the source or vouch for of the object signed. Everyone can read the object, though.

Encrypting means only those with the corresponding private key can read it, but without signing there is no guarantee you are behind the encrypted object.

Decimal or numeric values in regular expression validation

A digit in the range 1-9 followed by zero or more other digits:

^[1-9]\d*$

To allow numbers with an optional decimal point followed by digits. A digit in the range 1-9 followed by zero or more other digits then optionally followed by a decimal point followed by at least 1 digit:

^[1-9]\d*(\.\d+)?$

Notes:

  • The ^ and $ anchor to the start and end basically saying that the whole string must match the pattern

  • ()? matches 0 or 1 of the whole thing between the brackets

Update to handle commas:

In regular expressions . has a special meaning - match any single character. To match literally a . in a string you need to escape the . using \. This is the meaning of the \. in the regexp above. So if you want to use comma instead the pattern is simply:

^[1-9]\d*(,\d+)?$

Further update to handle commas and full stops

If you want to allow a . between groups of digits and a , between the integral and the fractional parts then try:

^[1-9]\d{0,2}(\.\d{3})*(,\d+)?$

i.e. this is a digit in the range 1-9 followed by up to 2 other digits then zero or more groups of a full stop followed by 3 digits then optionally your comma and digits as before.

If you want to allow a . anywhere between the digits then try:

^[1-9][\.\d]*(,\d+)?$

i.e. a digit 1-9 followed by zero or more digits or full stops optionally followed by a comma and one or more digits.

Stop form from submitting , Using Jquery

Try the code below. e.preventDefault() was added. This removes the default event action for the form.

 $(document).ready(function () {
    $("form").submit(function (e) {
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
        });
        e.preventDefault();
    });
});

Also, you mentioned you wanted the form to not submit under the premise of validation, but I see no code validation here?

Here is an example of some added validation

 $(document).ready(function () {
    $("form").submit(function (e) {
      /* put your form field(s) you want to validate here, this checks if your input field of choice is blank */
    if(!$('#inputID').val()){ 
       e.preventDefault(); // This will prevent the form submission
     } else{
        // In the event all validations pass. THEN process AJAX request.
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
       });
     }


    });
 });

PostgreSQL function for last inserted ID

you can use RETURNING clause in INSERT statement,just like the following

wgzhao=# create table foo(id int,name text);
CREATE TABLE
wgzhao=# insert into foo values(1,'wgzhao') returning id;
 id 
----
  1
(1 row)

INSERT 0 1
wgzhao=# insert into foo values(3,'wgzhao') returning id;
 id 
----
  3
(1 row)

INSERT 0 1

wgzhao=# create table bar(id serial,name text);
CREATE TABLE
wgzhao=# insert into bar(name) values('wgzhao') returning id;
 id 
----
  1
(1 row)

INSERT 0 1
wgzhao=# insert into bar(name) values('wgzhao') returning id;
 id 
----
  2
(1 row)

INSERT 0 

What is a simple C or C++ TCP server and client example?

Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX): https://github.com/DFHack/clsocket

What is the max size of localStorage values?

Quoting from the Wikipedia article on Web Storage:

Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity (10 MB per origin in Google Chrome(https://plus.google.com/u/0/+FrancoisBeaufort/posts/S5Q9HqDB8bh), Mozilla Firefox, and Opera; 10 MB per storage area in Internet Explorer) and better programmatic interfaces.

And also quoting from a John Resig article [posted January 2007]:

Storage Space

It is implied that, with DOM Storage, you have considerably more storage space than the typical user agent limitations imposed upon Cookies. However, the amount that is provided is not defined in the specification, nor is it meaningfully broadcast by the user agent.

If you look at the Mozilla source code we can see that 5120KB is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 2KB cookie.

However, the size of this storage area can be customized by the user (so a 5MB storage area is not guaranteed, nor is it implied) and the user agent (Opera, for example, may only provide 3MB - but only time will tell.)

Each for object?

A javascript Object does not have a standard .each function. jQuery provides a function. See http://api.jquery.com/jQuery.each/ The below should work

$.each(object, function(index, value) {
    console.log(value);
}); 

Another option would be to use vanilla Javascript using the Object.keys() and the Array .map() functions like this

Object.keys(object).map(function(objectKey, index) {
    var value = object[objectKey];
    console.log(value);
});

See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/keys and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

These are usually better than using a vanilla Javascript for-loop, unless you really understand the implications of using a normal for-loop and see use for it's specific characteristics like looping over the property chain.

But usually, a for-loop doesn't work better than jQuery or Object.keys().map(). I'll go into two potential issues with using a plain for-loop below.


Right, so also pointed out in other answers, a plain Javascript alternative would be

for(var index in object) { 
    var attr = object[index]; 
}

There are two potential issues with this:

1 . You want to check whether the attribute that you are finding is from the object itself and not from up the prototype chain. This can be checked with the hasOwnProperty function like so

for(var index in object) { 
   if (object.hasOwnProperty(index)) {
       var attr = object[index];
   }
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty for more information.

The jQuery.each and Object.keys functions take care of this automatically.

2 . Another potential issue with a plain for-loop is that of scope and non-closures. This is a bit complicated, but take for example the following code. We have a bunch of buttons with ids button0, button1, button2 etc, and we want to set an onclick on them and do a console.log like this:

<button id='button0'>click</button>
<button id='button1'>click</button>
<button id='button2'>click</button>

var messagesByButtonId = {"button0" : "clicked first!", "button1" : "clicked middle!", "button2" : "clicked last!"];
for(var buttonId in messagesByButtonId ) { 
   if (messagesByButtonId.hasOwnProperty(buttonId)) {
       $('#'+buttonId).click(function() {
           var message = messagesByButtonId[buttonId];
           console.log(message);
       });
   }
}

If, after some time, we click any of the buttons we will always get "clicked last!" in the console, and never "clicked first!" or "clicked middle!". Why? Because at the time that the onclick function is executed, it will display messagesByButtonId[buttonId] using the buttonId variable at that moment. And since the loop has finished at that moment, the buttonId variable will still be "button2" (the value it had during the last loop iteration), and so messagesByButtonId[buttonId] will be messagesByButtonId["button2"], i.e. "clicked last!".

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures for more information on closures. Especially the last part of that page that covers our example.

Again, jQuery.each and Object.keys().map() solve this problem automatically for us, because it provides us with a function(index, value) (that has closure) so we are safe to use both index and value and rest assured that they have the value that we expect.

How can I print out just the index of a pandas dataframe?

You can use lamba function:

index = df.index[lambda x : for x in df.index() ]
print(index)

How can I pass data from Flask to JavaScript in a template?

Some js files come from the web or library, they are not written by yourself. The code they get variable like this:

var queryString = document.location.search.substring(1);
var params = PDFViewerApplication.parseQueryString(queryString);
var file = 'file' in params ? params.file : DEFAULT_URL;

This method makes js files unchanged(keep independence), and pass variable correctly!

Get single row result with Doctrine NativeQuery

I use fetchObject() here a small example using Symfony 4.4

    <?php 
    use Doctrine\DBAL\Driver\Connection;

    class MyController{

    public function index($username){
      $queryBuilder = $connection->createQueryBuilder();
      $queryBuilder
        ->select('id', 'name')
        ->from('app_user')
        ->where('name = ?')
        ->setParameter(0, $username)
        ->setMaxResults(1);
      $stmUser = $queryBuilder->execute();

      dump($stmUser->fetchObject());

      //get_class_methods($stmUser) -> to see all methods
    }
  }

Response:

{ 
"id": "2", "name":"myuser"
}

How to extract the nth word and count word occurrences in a MySQL string?

No, there isn't a syntax for extracting text using regular expressions. You have to use the ordinary string manipulation functions.

Alternatively select the entire value from the database (or the first n characters if you are worried about too much data transfer) and then use a regular expression on the client.

Can I loop through a table variable in T-SQL?

You can loop through the table variable or you can cursor through it. This is what we usually call a RBAR - pronounced Reebar and means Row-By-Agonizing-Row.

I would suggest finding a SET-BASED answer to your question (we can help with that) and move away from rbars as much as possible.

Remove items from one list in another

You don't need an index, as the List<T> class allows you to remove items by value rather than index by using the Remove function.

foreach(car item in list1) list2.Remove(item);

What does $1 mean in Perl?

These are called "match variables". As previously mentioned they contain the text from your last regular expression match.

More information is in Essential Perl. (Ctrl + F for 'Match Variables' to find the corresponding section.)

Regex expressions in Java, \\s vs. \\s+

Those two replaceAll calls will always produce the same result, regardless of what x is. However, it is important to note that the two regular expressions are not the same:

  • \\s - matches single whitespace character
  • \\s+ - matches sequence of one or more whitespace characters.

In this case, it makes no difference, since you are replacing everything with an empty string (although it would be better to use \\s+ from an efficiency point of view). If you were replacing with a non-empty string, the two would behave differently.

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

First of all, a caveat. Why do you want to use telnet? telnet is an old protocol, unsafe and impractical for remote access. It's been (almost)totally replaced by ssh.

To answer your questions, it depends. It depends on the telnet client you use. If you use microsoft telnet, you can't. Microsoft telnet does not have any mean to send commands from a batch file or a command line.

Send form data with jquery ajax json

Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo '<pre>';
    print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="[email protected]" />
<button type="submit">Send!</button>

With AJAX you are able to do exactly the same thing, only without page refresh.

How do I convert a Swift Array to a String?

If you question is something like this: tobeFormattedString = ["a", "b", "c"] Output = "abc"

String(tobeFormattedString)

How to pass the password to su/sudo/ssh without overriding the TTY?

You can provide password as parameter to expect script.

jQuery Mobile Page refresh mechanism

This answer did the trick for me http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php.

In the context of a multi-pages template, I modify the content of a <div id="foo">...</div> in a Javascript 'pagebeforeshow' handler and trigger a refresh at the end of the script:

$(document).bind("pagebeforeshow", function(event,pdata) {
  var parsedUrl = $.mobile.path.parseUrl( location.href );
  switch ( parsedUrl.hash ) {
    case "#p_02":
      ... some modifications of the content of the <div> here ...
      $("#foo").trigger("create");
    break;
  }
});

Git Bash doesn't see my PATH

For me the most convenient was to: 1) Create directory "bin" in the root of C: drive 2) Add "C:/bin;" to PATH in "My Computer -> Properties -> Environemtal Variables"

Cannot edit in read-only editor VS Code

I received the same error like @jgritten. Just like the comment before me by @jgritten, I 'unstaged' and reopened vscode and the files. Now I 'staged' it again. The error "Cannot edit in read-only editor" didnt come.

Hope this reassures anyone who might have similar error after staging the file using git in vscode.

How do I make the method return type generic?

This question is very similar to Item 29 in Effective Java - "Consider typesafe heterogeneous containers." Laz's answer is the closest to Bloch's solution. However, both put and get should use the Class literal for safety. The signatures would become:

public <T extends Animal> void addFriend(String name, Class<T> type, T animal);
public <T extends Animal> T callFriend(String name, Class<T> type);

Inside both methods you should check that the parameters are sane. See Effective Java and the Class javadoc for more info.

Best way to check if a character array is empty

The second one is fastest. Using strlen will be close if the string is indeed empty, but strlen will always iterate through every character of the string, so if it is not empty, it will do much more work than you need it to.

As James mentioned, the third option wipes the string out before checking, so the check will always succeed but it will be meaningless.

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

I did it by passing the cookie through the HttpContext:

HttpContext localContext = new BasicHttpContext();

localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

response = client.execute(httppost, localContext);

Python, Unicode, and the Windows console

Despite the other plausible-sounding answers that suggest changing the code page to 65001, that does not work. (Also, changing the default encoding using sys.setdefaultencoding is not a good idea.)

See this question for details and code that does work.

How to decode HTML entities using jQuery?

The easiest way is to set a class selector to your elements an then use following code:

$(function(){
    $('.classSelector').each(function(a, b){
        $(b).html($(b).text());
    });
});

Nothing any more needed!

I had this problem and found this clear solution and it works fine.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

Your class MyClass creates a new MyClassToBeTested, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.

How to return a specific status code and no contents from Controller?

The best way to do it is:

return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");

'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/

Once you choose your StatusCode, return it with a message.

How to implement a Keyword Search in MySQL?

Personally, I wouldn't use the LIKE string comparison on the ID field or any other numeric field. It doesn't make sense for a search for ID# "216" to return 16216, 21651, 3216087, 5321668..., and so on and so forth; likewise with salary.

Also, if you want to use prepared statements to prevent SQL injections, you would use a query string like:

SELECT * FROM job WHERE `position` LIKE CONCAT('%', ? ,'%') OR ...

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

do not forget to insert (or unCommanet) this line at the beginning of your pod file:

platform :iOS, '9.0'

that saves my day

How can I remove specific rules from iptables?

You may also use the rule's number (--line-numbers):

iptables -L INPUT --line-numbers

Example output :

Chain INPUT (policy ACCEPT) 
    num  target prot opt source destination
    1    ACCEPT     udp  --  anywhere  anywhere             udp dpt:domain 
    2    ACCEPT     tcp  --  anywhere  anywhere             tcp dpt:domain 
    3    ACCEPT     udp  --  anywhere  anywhere             udp dpt:bootps 
    4    ACCEPT     tcp  --  anywhere  anywhere             tcp dpt:bootps

So if you would like to delete second rule :

iptables -D INPUT 2

Update

If you use(d) a specific table (eg nat), you have to add it to the delete command (thx to @ThorSummoner for the comment)

sudo iptables -t nat -D PREROUTING 1

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Try

ALLOWED_HOSTS = ['*']

Less secure if you're not firewalled off or on a public LAN, but it's what I use and it works.

EDIT: Interestingly enough I've been needing to add this to a few of my 1.8 projects even when DEBUG = True. Very unsure why.

EDIT: This is due to a Django security update as mentioned in my comment.

how do I check in bash whether a file was created more than x time ago?

The find one is good but I think you can use anotherway, especially if you need to now how many seconds is the file old

date -d "now - $( stat -c "%Y" $filename ) seconds" +%s

using GNU date

Create a file from a ByteArrayOutputStream

You can do it with using a FileOutputStream and the writeTo method.

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}

Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

Convert seconds to HH-MM-SS with JavaScript?

After looking at all the answers and not being happy with most of them, this is what I came up with. I know I am very late to the conversation, but here it is anyway.

function secsToTime(secs){
  var time = new Date(); 
  // create Date object and set to today's date and time
  time.setHours(parseInt(secs/3600) % 24);
  time.setMinutes(parseInt(secs/60) % 60);
  time.setSeconds(parseInt(secs%60));
  time = time.toTimeString().split(" ")[0];
  // time.toString() = "HH:mm:ss GMT-0800 (PST)"
  // time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
  // time.toTimeString().split(" ")[0]; = "HH:mm:ss"
  return time;
}

I create a new Date object, change the time to my parameters, convert the Date Object to a time string, and removed the additional stuff by splitting the string and returning only the part that need.

I thought I would share this approach, since it removes the need for regex, logic and math acrobatics to get the results in "HH:mm:ss" format, and instead it relies on built in methods.

You may want to take a look at the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

In C can a long printf statement be broken up into multiple lines?

I don't think using one printf statement to print string literals as seen above is a good programming practice; rather, one can use the piece of code below:

printf("name: %s\t",sp->name);
printf("args: %s\t",sp->args);
printf("value: %s\t",sp->value);
printf("arraysize: %s\t",sp->name); 

open failed: EACCES (Permission denied)

In my case it was permissions issue. The catch is that on device with Android 4.0.4 I got access to file without any error or exception. And on device with Android 5.1 it failed with ACCESS exception (open failed: EACCES (Permission denied)). Handled it with adding follow permission to manifest file:

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

So I guess that it's the difference between permissions management in OS versions that causes to failures.

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.

So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.

EditText onClickListener in Android

Why did not anyone mention setOnTouchListener? Using setOnTouchListener is easy and all right, and just return true if the listener has consumed the event, false otherwise.

What are the differences between git branch, fork, fetch, merge, rebase and clone?

A clone is simply a copy of a repository. On the surface, its result is equivalent to svn checkout, where you download source code from some other repository. The difference between centralized VCS like Subversion and DVCSs like Git is that in Git, when you clone, you are actually copying the entire source repository, including all the history and branches. You now have a new repository on your machine and any commits you make go into that repository. Nobody will see any changes until you push those commits to another repository (or the original one) or until someone pulls commits from your repository, if it is publicly accessible.

A branch is something that is within a repository. Conceptually, it represents a thread of development. You usually have a master branch, but you may also have a branch where you are working on some feature xyz, and another one to fix bug abc. When you have checked out a branch, any commits you make will stay on that branch and not be shared with other branches until you merge them with or rebase them onto the branch in question. Of course, Git seems a little weird when it comes to branches until you look at the underlying model of how branches are implemented. Rather than explain it myself (I've already said too much, methinks), I'll link to the "computer science" explanation of how Git models branches and commits, taken from the Git website:

http://eagain.net/articles/git-for-computer-scientists/

A fork isn't a Git concept really, it's more a political/social idea. That is, if some people aren't happy with the way a project is going, they can take the source code and work on it themselves separate from the original developers. That would be considered a fork. Git makes forking easy because everyone already has their own "master" copy of the source code, so it's as simple as cutting ties with the original project developers and doesn't require exporting history from a shared repository like you might have to do with SVN.

EDIT: since I was not aware of the modern definition of "fork" as used by sites such as GitHub, please take a look at the comments and also Michael Durrant's answer below mine for more information.

How do I import a Swift file from another Swift file?

As @high6 and @erik-p-hansen pointed out in the answer given by @high6, this can be overcome by importing the target for the module where the PrimeNumberModel class is, which is probably the same name as your project in a simple project.

While looking at this, I came across the article Write your first Unit Test in Swift on swiftcast.tv by Clayton McIlrath. It discusses access modifiers, shows an example of the same problem you are having (but for a ViewController rather than a model file) and shows how to both import the target and solve the access modifier problem by including the destination file in the target, meaning you don't have to make the class you are trying to test public unless you actually want to do so.

How to check db2 version

Try the first or the second:

SELECT * FROM TABLE(SYSPROC.ENV_GET_INST_INFO());
SELECT * FROM TABLE(SYSPROC.ENV_GET_PROD_INFO());
SELECT * FROM TABLE(SYSPROC.ENV_GET_SYS_INFO());

How to fix a collation conflict in a SQL Server query?

I resolved a similar issue by wrapping the query in another query...

Initial query was working find giving individual columns of output, with some of the columns coming from sub queries with Max or Sum function, and other with "distinct" or case substitutions and such.

I encountered the collation error after attempting to create a single field of output with...

select
rtrim(field1)+','+rtrim(field2)+','+...

The query would execute as I wrote it, but the error would occur after saving the sql and reloading it.

Wound up fixing it with something like...

select z.field1+','+z.field2+','+... as OUTPUT_REC
from (select rtrim(field1), rtrim(field2), ... ) z

Some fields are "max" of a subquery, with a case substitution if null and others are date fields, and some are left joins (might be NULL)...in other words, mixed field types. I believe this is the cause of the issue being caused by OS collation and Database collation being slightly different, but by converting all to trimmed strings before the final select, it sorts it out, all in the SQL.

Make a Bash alias that takes a parameter?

TL;DR: Do this instead

Its far easier and more readable to use a function than an alias to put arguments in the middle of a command.

$ wrap_args() { echo "before $@ after"; }
$ wrap_args 1 2 3
before 1 2 3 after

If you read on, you'll learn things that you don't need to know about shell argument processing. Knowledge is dangerous. Just get the outcome you want, before the dark side forever controls your destiny.

Clarification

bash aliases do accept arguments, but only at the end:

$ alias speak=echo
$ speak hello world
hello world

Putting arguments into the middle of command via alias is indeed possible but it gets ugly.

Don't try this at home, kiddies!

If you like circumventing limitations and doing what others say is impossible, here's the recipe. Just don't blame me if your hair gets frazzled and your face ends up covered in soot mad-scientist-style.

The workaround is to pass the arguments that alias accepts only at the end to a wrapper that will insert them in the middle and then execute your command.

Solution 1

If you're really against using a function per se, you can use:

$ alias wrap_args='f(){ echo before "$@" after;  unset -f f; }; f'
$ wrap_args x y z
before x y z after

You can replace $@ with $1 if you only want the first argument.

Explanation 1

This creates a temporary function f, which is passed the arguments (note that f is called at the very end). The unset -f removes the function definition as the alias is executed so it doesn't hang around afterwards.

Solution 2

You can also use a subshell:

$ alias wrap_args='sh -c '\''echo before "$@" after'\'' _'

Explanation 2

The alias builds a command like:

sh -c 'echo before "$@" after' _

Comments:

  • The placeholder _ is required, but it could be anything. It gets set to sh's $0, and is required so that the first of the user-given arguments don't get consumed. Demonstration:

    sh -c 'echo Consumed: "$0" Printing: "$@"' alcohol drunken babble
    Consumed: alcohol Printing: drunken babble
    
  • The single-quotes inside single-quotes are required. Here's an example of it not working with double quotes:

    $ sh -c "echo Consumed: $0 Printing: $@" alcohol drunken babble
    Consumed: -bash Printing:
    

    Here the values of the interactive shell's $0 and $@ are replaced into the double quoted before it is passed to sh. Here's proof:

    echo "Consumed: $0 Printing: $@"
    Consumed: -bash Printing:
    

    The single quotes ensure that these variables are not interpreted by interactive shell, and are passed literally to sh -c.

    You could use double-quotes and \$@, but best practice is to quote your arguments (as they may contain spaces), and \"\$@\" looks even uglier, but may help you win an obfuscation contest where frazzled hair is a prerequisite for entry.

How to load/reference a file as a File instance from the classpath

This also works, and doesn't require a /path/to/file URI conversion. If the file is on the classpath, this will find it.

File currFile = new File(getClass().getClassLoader().getResource("the_file.txt").getFile());

How is the default max Java heap size determined?

For the IBM JVM, the command is the following:

java -verbose:sizes -version

For more information about the IBM SDK for Java 8: http://www-01.ibm.com/support/knowledgecenter/SSYKE2_8.0.0/com.ibm.java.lnx.80.doc/diag/appendixes/defaults.html?lang=en

Java program to get the current date without timestamp

I did as follows and it worked:

calendar1.set(Calendar.HOUR_OF_DAY, 0);
calendar1.set(Calendar.AM_PM, 0);
calendar1.set(Calendar.HOUR, 0);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND, 0);
Date date1 = calendar1.getTime();       // Convert it to date

Do this for other instances to which you want to compare. This logic worked for me; I had to compare the dates whether they are equal or not, but you can do different comparisons (before, after, equals, etc.)

How to show soft-keyboard when edittext is focused

It worked for me. You can try with this also to show the keyboard:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

Exception: Can't bind to 'ngFor' since it isn't a known native property

I missed let in front of talk:

<div *ngFor="let talk of talks">

Note that as of beta.17 usage of #... to declare local variables inside of structural directives like NgFor is deprecated. Use let instead.

<div *ngFor="#talk of talks"> now becomes <div *ngFor="let talk of talks">

Original answer:

I missed # in front of talk:

<div *ngFor="#talk of talks">

It is so easy to forget that #. I wish the Angular exception error message would instead say:
you forgot that # again.

How can I add private key to the distribution certificate?

since xcode5 organizer no longer team section exists. but the bold sentence was the answer for me. God thanks there is another mac to restore and import to problemmatic mac. now all is ok.

How to get the latest record in each group using GROUP BY?

This is a standard problem.

Note that MySQL allows you to omit columns from the GROUP BY clause, which Standard SQL does not, but you do not get deterministic results in general when you use the MySQL facility.

SELECT *
  FROM Messages AS M
  JOIN (SELECT To_ID, From_ID, MAX(TimeStamp) AS Most_Recent
          FROM Messages
         WHERE To_ID = 12345678
         GROUP BY From_ID
       ) AS R
    ON R.To_ID = M.To_ID AND R.From_ID = M.From_ID AND R.Most_Recent = M.TimeStamp
 WHERE M.To_ID = 12345678

I've added a filter on the To_ID to match what you're likely to have. The query will work without it, but will return a lot more data in general. The condition should not need to be stated in both the nested query and the outer query (the optimizer should push the condition down automatically), but it can do no harm to repeat the condition as shown.

System.Net.Http: missing from namespace? (using .net 4.5)

HttpClient lives in the System.Net.Http namespace.

You'll need to add:

using System.Net.Http;

And make sure you are referencing System.Net.Http.dll in .NET 4.5.


The code posted doesn't appear to do anything with webClient. Is there something wrong with the code that is actually compiling using HttpWebRequest?


Update

To open the Add Reference dialog right-click on your project in Solution Explorer and select Add Reference.... It should look something like:

enter image description here

Twitter Bootstrap onclick event on buttons-radio

I needed to do the same thing for a chart where you could select the period of the data that should be displayed.

Therefore I introduced the CSS class 'btn-group-radio' and used the following unobtrusive javascript one-liner:

// application.js
$(document).ready(function() {
  $('.btn-group-radio .btn').click(function() {
    $(this).addClass('active').siblings('.btn').removeClass('active');
  });
});

And here is the HTML:

<!-- some arbitrary view -->
<div class="btn-group btn-group-radio">
  <%= link_to '1W', charts_path('1W'), class: 'btn btn-default active', remote: true %>
  <%= link_to '1M', charts_path('1M'), class: 'btn btn-default', remote: true %>
  <%= link_to '3M', charts_path('3M'), class: 'btn btn-default', remote: true %>
  <%= link_to '6M', charts_path('6M'), class: 'btn btn-default', remote: true %>
  <%= link_to '1Y', charts_path('1Y'), class: 'btn btn-default', remote: true %>
  <%= link_to 'All', charts_path('all'), class: 'btn btn-default', remote: true %>
</div>

Is a URL allowed to contain a space?

URLs are defined in RFC 3986, though other RFCs are relevant as well but RFC 1738 is obsolete.

They may not have spaces in them, along with many other characters. Since those forbidden characters often need to be represented somehow, there is a scheme for encoding them into a URL by translating them to their ASCII hexadecimal equivalent with a "%" prefix.

Most programming languages/platforms provide functions for encoding and decoding URLs, though they may not properly adhere to the RFC standards. For example, I know that PHP does not.

use mysql SUM() in a WHERE clause

You can only use aggregates for comparison in the HAVING clause:

GROUP BY ...
  HAVING SUM(cash) > 500

The HAVING clause requires you to define a GROUP BY clause.

To get the first row where the sum of all the previous cash is greater than a certain value, use:

SELECT y.id, y.cash
  FROM (SELECT t.id,
               t.cash,
               (SELECT SUM(x.cash)
                  FROM TABLE x
                 WHERE x.id <= t.id) AS running_total
         FROM TABLE t
     ORDER BY t.id) y
 WHERE y.running_total > 500
ORDER BY y.id
   LIMIT 1

Because the aggregate function occurs in a subquery, the column alias for it can be referenced in the WHERE clause.

How can I set the request header for curl?

Just use the -H parameter several times:

curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.com

Quick Sort Vs Merge Sort

Quick sort is typically faster than merge sort when the data is stored in memory. However, when the data set is huge and is stored on external devices such as a hard drive, merge sort is the clear winner in terms of speed. It minimizes the expensive reads of the external drive and also lends itself well to parallel computing.

Sequelize OR condition object

String based operators will be deprecated in the future (You've probably seen the warning in console).

Getting this to work with symbolic operators was quite confusing for me, and I've updated the docs with two examples.

Post.findAll({
  where: {
    [Op.or]: [{authorId: 12}, {authorId: 13}]
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Post.findAll({
  where: {
    authorId: {
      [Op.or]: [12, 13]
    }
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Google Maps V3 marker with label

I doubt the standard library supports this.

But you can use the google maps utility library:

http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#MarkerWithLabel

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);

var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

var marker = new MarkerWithLabel({
   position: myLatlng,
   map: map,
   draggable: true,
   raiseOnDrag: true,
   labelContent: "A",
   labelAnchor: new google.maps.Point(3, 30),
   labelClass: "labels", // the CSS class for the label
   labelInBackground: false
 });

The basics about marker can be found here: https://developers.google.com/maps/documentation/javascript/overlays#Markers

What's the right way to create a date in Java?

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

How to set the height of an input (text) field in CSS?

Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height rule, some won't.

You can try line-height (may need display:block; or display:inline-block;) or top and bottom padding also. If none of those work, that's pretty much it - use a graphic, position the input in the center and set border:none; so it looks like the form control is big but it actually isn't...

How to get all properties values of a JavaScript Object (without knowing the keys)?

The question doesn't specify whether wanting inherited and non-enumerable properties also.

There is a question for getting everything, inherited properties and non-enumerable properties also, that Google cannot easily find.

If we are to get all inherited and non-enumerable properties, my solution for that is:

function getAllPropertyNames(obj) {
    let result = new Set();
    while (obj) {
        Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
        obj = Object.getPrototypeOf(obj);
    }
    return [...result];
}

And then iterate over them, just use a for-of loop:

_x000D_
_x000D_
function getAllPropertyNames(obj) {
  let result = new Set();
  while (obj) {
    Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
    obj = Object.getPrototypeOf(obj);
  }
  return [...result];
}

let obj = {
  abc: 123,
  xyz: 1.234,
  foobar: "hello"
};

for (p of getAllPropertyNames(obj)) console.log(p);
_x000D_
_x000D_
_x000D_

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I am also having the same problem and I solved by as below.
in macro have a variable called rownumber and initially i set it as zero. this is the error because no excel sheet contains row number as zero. when i set as 1 and increment what i want.
now its working fine.

Simple Deadlock Examples

Let me explain more clearly using an example having more than 2 threads.

Let us say you have n threads each holding locks L1, L2, ..., Ln respectively. Now let's say, starting from thread 1, each thread tries to acquire its neighbour thread's lock. So, thread 1 gets blocked for trying to acquire L2 (as L2 is owned by thread 2), thread 2 gets blocked for L3 and so on. The thread n gets blocked for L1. This is now a deadlock as no thread is able to execute.

class ImportantWork{
   synchronized void callAnother(){     
   }
   synchronized void call(ImportantWork work) throws InterruptedException{
     Thread.sleep(100);
     work.callAnother();
   }
}
class Task implements Runnable{
  ImportantWork myWork, otherWork;
  public void run(){
    try {
      myWork.call(otherWork);
    } catch (InterruptedException e) {      
    }
  }
}
class DeadlockTest{
  public static void main(String args[]){
    ImportantWork work1=new ImportantWork();
    ImportantWork work2=new ImportantWork();
    ImportantWork work3=new ImportantWork();
    Task task1=new Task(); 
    task1.myWork=work1;
    task1.otherWork=work2;

    Task task2=new Task(); 
    task2.myWork=work2;
    task2.otherWork=work3;

    Task task3=new Task(); 
    task3.myWork=work3;
    task3.otherWork=work1;

    new Thread(task1).start();
    new Thread(task2).start();
    new Thread(task3).start();
  }
}

In the above example, you can see that there are three threads holding Runnables task1, task2, and task3. Before the statement sleep(100) the threads acquire the three work objects' locks when they enter the call() method (due to the presence of synchronized). But as soon as they try to callAnother() on their neighbour thread's object, they are blocked, leading to a deadlock, because those objects' locks have already been taken.

disable Bootstrap's Collapse open/close animation

Maybe not a direct answer to the question, but a recent addition to the official documentation describes how jQuery can be used to disable transitions entirely just by:

$.support.transition = false

Setting the .collapsing CSS transitions to none as mentioned in the accepted answer removed the animation. But this — in Firefox and Chromium for me — creates an unwanted visual issue on collapse of the navbar.

For instance, visit the Bootstrap navbar example and add the CSS from the accepted answer:

.collapsing {
     -webkit-transition: none;
     transition: none;
}

What I currently see is when the navbar collapses, the bottom border of the navbar momentarily becomes two pixels instead of one, then disconcertingly jumps back to one. Using jQuery, this artifact doesn't appear.

Functions that return a function

Returning b is returning a function object. In Javascript, functions are just objects, like any other object. If you find that not helpful, just replace the word "object" with "thing". You can return any object from a function. You can return a true/false value. An integer (1,2,3,4...). You can return a string. You can return a complex object with multiple properties. And you can return a function. a function is just a thing.

In your case, returning b returns the thing, the thing is a callable function. Returning b() returns the value returned by the callable function.

Consider this code:

function b() {
   return 42;
}

Using the above definition, return b(); returns the value 42. On the other hand return b; returns a function, that itself returns the value of 42. They are two different things.

c# why can't a nullable int be assigned null as a value

What Harry S says is exactly right, but

int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));

would also do the trick. (We Resharper users can always spot each other in crowds...)

How do you reinstall an app's dependencies using npm?

You can do this with one simple command:

npm ci

Documentation:

npm ci
Install a project with a clean slate

Can't connect to MySQL server on 'localhost' (10061) after Installation

for who person that want use mysql or mariadb with out any error i suggest use version 5.5 just download a zip file mariadb-5.5.65-winx64.zip from https://downloads.mariadb.org/mariadb/5.5.65/ and to install follow this tutorial setp by step https://www.youtube.com/watch?v=uEPs6JsTZFc (this tutorial works well for version 5.5 too )

Populating a database in a Laravel migration file

Here is a very good explanation of why using Laravel's Database Seeder is preferable to using Migrations: https://web.archive.org/web/20171018135835/http://laravelbook.com/laravel-database-seeding/

Although, following the instructions on the official documentation is a much better idea because the implementation described at the above link doesn't seem to work and is incomplete. http://laravel.com/docs/migrations#database-seeding

How can I trim beginning and ending double quotes from a string?

Also with Apache StringUtils.strip():

 StringUtils.strip(null, *)          = null
 StringUtils.strip("", *)            = ""
 StringUtils.strip("abc", null)      = "abc"
 StringUtils.strip("  abc", null)    = "abc"
 StringUtils.strip("abc  ", null)    = "abc"
 StringUtils.strip(" abc ", null)    = "abc"
 StringUtils.strip("  abcyx", "xyz") = "  abc"

So,

final String SchrodingersQuotedString = "may or may not be quoted";
StringUtils.strip(SchrodingersQuotedString, "\""); //quoted no more

This method works both with quoted and unquoted strings as shown in my example. The only downside is, it will not look for strictly matched quotes, only leading and trailing quote characters (ie. no distinction between "partially and "fully" quoted strings).

How do I check particular attributes exist or not in XML?

Another way to handle the situation is exception handling.

Every time a non-existent value is called, your code will recover from the exception and just continue with the loop. In the catch-block you can handle the error the same way you write it down in your else-statement when the expression (... != null) returns false. Of course throwing and handling exceptions is a relatively costly operation which might not be ideal depending on the performance requirements.

Remove folder and its contents from git/GitHub's history

If you are here to copy-paste code:

This is an example which removes node_modules from history

git filter-branch --tree-filter "rm -rf node_modules" --prune-empty HEAD
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
echo node_modules/ >> .gitignore
git add .gitignore
git commit -m 'Removing node_modules from git history'
git gc
git push origin master --force

What git actually does:

The first line iterates through all references on the same tree (--tree-filter) as HEAD (your current branch), running the command rm -rf node_modules. This command deletes the node_modules folder (-r, without -r, rm won't delete folders), with no prompt given to the user (-f). The added --prune-empty deletes useless (not changing anything) commits recursively.

The second line deletes the reference to that old branch.

The rest of the commands are relatively straightforward.

Find in Files: Search all code in Team Foundation Server

Assuming you have Notepad++, an often-missed feature is 'Find in files', which is extremely fast and comes with filters, regular expressions, replace and all the N++ goodies.

CSS align one item right with flexbox

To align one flex child to the right set it withmargin-left: auto;

From the flex spec:

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

.wrap div:last-child {
  margin-left: auto;
}

Updated fiddle

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note:

You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

Demo

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
  border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
  flex: 1;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_