Programs & Examples On #Arc4random

The arc4random() function returns pseudo-random numbers in the range of 0 to (2*32)-1

How does one make random number between range for arc4random_uniform()?

I modified @DaRk-_-D0G's answer to work with Swift 2.0

/**
Arc Random for Double and Float
*/
public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
    var r: T = 0
    arc4random_buf(&r, sizeof(T))
    return r
}
public extension Int {
    /**
    Create a random num Int
    :param: lower number Int
    :param: upper number Int
    :return: random number Int
    By DaRkDOG
    */
    public static func random (lower: Int , upper: Int) -> Int {
        return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
    }

}
public extension Double {
    /**
    Create a random num Double
    :param: lower number Double
    :param: upper number Double
    :return: random number Double
    By DaRkDOG
    */
    public static func random(lower: Double, upper: Double) -> Double {
        let r = Double(arc4random(UInt64)) / Double(UInt64.max)
        return (r * (upper - lower)) + lower
    }
}
public extension Float {
    /**
    Create a random num Float
    :param: lower number Float
    :param: upper number Float
    :return: random number Float
    By DaRkDOG
    */
    public static func random(lower: Float, upper: Float) -> Float {
        let r = Float(arc4random(UInt32)) / Float(UInt32.max)
        return (r * (upper - lower)) + lower
    }
}

Generating random numbers with Swift

You could try as well:

let diceRoll = Int(arc4random_uniform(UInt32(6)))

I had to add "UInt32" to make it work.

Add to integers in a list

If you try appending the number like, say listName.append(4) , this will append 4 at last. But if you are trying to take <int> and then append it as, num = 4 followed by listName.append(num), this will give you an error as 'num' is of <int> type and listName is of type <list>. So do type cast int(num) before appending it.

What REST PUT/POST/DELETE calls should return by a convention?

Overall, the conventions are “think like you're just delivering web pages”.

For a PUT, I'd return the same view that you'd get if you did a GET immediately after; that would result in a 200 (well, assuming the rendering succeeds of course). For a POST, I'd do a redirect to the resource created (assuming you're doing a creation operation; if not, just return the results); the code for a successful create is a 201, which is really the only HTTP code for a redirect that isn't in the 300 range.

I've never been happy about what a DELETE should return (my code currently produces an HTTP 204 and an empty body in this case).

How to change an image on click using CSS alone?

some people have suggested the "visited", but the visited links remain in the browsers cache, so the next time your user visits the page, the link will have the second image.. i dont know it that's the desired effect you want. Anyway you coul mix JS and CSS:

<style>
.off{
    color:red;
}
.on{
    color:green;
}
</style>
<a href="" class="off" onclick="this.className='on';return false;">Foo</a>

using the onclick event, you can change (or toggle maybe?) the class name of the element. In this example i change the text color but you could also change the background image.

Good Luck

How does C compute sin() and other math functions?

Concerning trigonometric function like sin(), cos(),tan() there has been no mention, after 5 years, of an important aspect of high quality trig functions: Range reduction.

An early step in any of these functions is to reduce the angle, in radians, to a range of a 2*p interval. But p is irrational so simple reductions like x = remainder(x, 2*M_PI) introduce error as M_PI, or machine pi, is an approximation of p. So, how to do x = remainder(x, 2*p)?

Early libraries used extended precision or crafted programming to give quality results but still over a limited range of double. When a large value was requested like sin(pow(2,30)), the results were meaningless or 0.0 and maybe with an error flag set to something like TLOSS total loss of precision or PLOSS partial loss of precision.

Good range reduction of large values to an interval like -p to p is a challenging problem that rivals the challenges of the basic trig function, like sin(), itself.

A good report is Argument reduction for huge arguments: Good to the last bit (1992). It covers the issue well: discusses the need and how things were on various platforms (SPARC, PC, HP, 30+ other) and provides a solution algorithm the gives quality results for all double from -DBL_MAX to DBL_MAX.


If the original arguments are in degrees, yet may be of a large value, use fmod() first for improved precision. A good fmod() will introduce no error and so provide excellent range reduction.

// sin(degrees2radians(x))
sin(degrees2radians(fmod(x, 360.0))); // -360.0 < fmod(x,360) < +360.0

Various trig identities and remquo() offer even more improvement. Sample: sind()

Batch file include external file for variables

While trying to use the method with excutable configuration I noticed that it may work or may NOT work depending on where in the script is located the call:

call config.cmd

I know it doesn't make any sens, but for me it's a fact. When "call config.cmd" is located at the top of the script, it works, but if further in the script it doesn't.

By doesn't work, I mean the variable are not set un the calling script.

Very very strange !!!!

Can we pass an array as parameter in any function in PHP?

I composed this code as an example. Hope the idea works!

<?php
$friends = array('Robert', 'Louis', 'Ferdinand');
  function greetings($friends){
    echo "Greetings, $friends <br>";
  }
  foreach ($friends as $friend) {
  greetings($friend);
  }
?>

Easiest way to ignore blank lines when reading a file in Python

I guess there is a simple solution which I recently used after going through so many answers here.

with open(file_name) as f_in:   
    for line in f_in:
        if len(line.split()) == 0:
            continue

This just does the same work, ignoring all empty line.

Python script to copy text to clipboard

Use Tkinter:

https://stackoverflow.com/a/4203897/2804197

try:
    from Tkinter import Tk
except ImportError:
    from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()

(Original author: https://stackoverflow.com/users/449571/atomizer)

Read user input inside a loop

It looks like you read twice, the read inside the while loop is not needed. Also, you don't need to invoke the cat command:

while read input
do
    echo $input
done < filename

Hide Spinner in Input Number - Firefox 29

/* for chrome */
    input[type=number]::-webkit-inner-spin-button,
    input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;}             


/* for mozilla */  
   input[type=number] {-moz-appearance: textfield;}

Creating a Plot Window of a Particular Size

This will depend on the device you're using. If you're using a pdf device, you can do this:

pdf( "mygraph.pdf", width = 11, height = 8 )
plot( x, y )

You can then divide up the space in the pdf using the mfrow parameter like this:

par( mfrow = c(2,2) )

That makes a pdf with four panels available for plotting. Unfortunately, some of the devices take different units than others. For example, I think that X11 uses pixels, while I'm certain that pdf uses inches. If you'd just like to create several devices and plot different things to them, you can use dev.new(), dev.list(), and dev.next().

Other devices that might be useful include:

There's a list of all of the devices here.

Pick a random value from an enum?

This is probably the most concise way of achieving your goal.All you need to do is to call Letter.getRandom() and you will get a random enum letter.

public enum Letter {
    A,
    B,
    C,
    //...

    public static Letter getRandom() {
        return values()[(int) (Math.random() * values().length)];
    }
}

If my interface must return Task what is the best way to have a no-operation implementation?

When you must return specified type:

Task.FromResult<MyClass>(null);

Is it not possible to define multiple constructors in Python?

For the example you gave, use default values:

class City:
    def __init__(self, name="Default City Name"):
        ...
    ...

In general, you have two options:

1) Do if-elif blocks based on the type:

def __init__(self, name):
    if isinstance(name, str):
        ...
    elif isinstance(name, City):
        ...
    ...

2) Use duck typing --- that is, assume the user of your class is intelligent enough to use it correctly. This is typically the preferred option.

Eclipse won't compile/run java file

This worked for me:

  1. Create a new project
  2. Create a class in it
  3. Add erroneous code, let error come
  4. Now go to your project
  5. Go to Problems window
  6. Double click on a error

It starts showing compilation errors in the code.

C# Reflection: How to get class reference from string?

A simple use:

Type typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName");

Sample:

Type dogClass = Type.GetType("Animals.Dog, Animals");

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

Just use this command and it will handle this error npm install --unsafe-perm --allow-root

Why is vertical-align:text-top; not working in CSS

The vertical-align attribute is for inline elements only. It will have no effect on block level elements, like a div. Also text-top only moves the text to the top of the current font size. If you would like to vertically align an inline element to the top just use this.

vertical-align: top;

The paragraph tag is not outdated. Also, the vertical-align attribute applied to a span element may not display as intended in some mozilla browsers.

How to print from Flask @app.route to python console

It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:

from __future__ import print_function # In python 2.7
import sys

@app.route('/button/')
def button_clicked():
    print('Hello world!', file=sys.stderr)
    return redirect('/')

Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post

how to parse json using groovy

That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }

If you know it's a single-element Map then you can directly access the link:

def data = userJson.values().iterator().next()
String link = data.link

And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

String id = '212315952136472'
...
String link = userJson[id].link

What's the fastest way to convert String to Number in JavaScript?

This is probably not that fast, but has the added benefit of making sure your number is at least a certain value (e.g. 0), or at most a certain value:

Math.max(input, 0);

If you need to ensure a minimum value, usually you'd do

var number = Number(input);
if (number < 0) number = 0;

Math.max(..., 0) saves you from writing two statements.

Link to "pin it" on pinterest without generating a button

For such cases, I found very useful the Share Link Generator, it helps creating Facebook, Google+, Twitter, Pinterest, LinkedIn share buttons.

Keeping it simple and how to do multiple CTE in a query

You can have multiple CTEs in one query, as well as reuse a CTE:

WITH    cte1 AS
        (
        SELECT  1 AS id
        ),
        cte2 AS
        (
        SELECT  2 AS id
        )
SELECT  *
FROM    cte1
UNION ALL
SELECT  *
FROM    cte2
UNION ALL
SELECT  *
FROM    cte1

Note, however, that SQL Server may reevaluate the CTE each time it is accessed, so if you are using values like RAND(), NEWID() etc., they may change between the CTE calls.

getting the table row values with jquery

Here is a working example. I changed the code to output to a div instead of an alert box. Your issue was item.innerHTML I believe. I use the jQuery html function instead and that seemed to resolve the issue.

<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;'  >
    <tr>

   <th>Fund</th>
   <th>Organization</th>
   <th>Access</th>
   <th>Delete</th>
   </tr>
    <tr>
   <td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a  class='delbtn'ref='#'>X</a></td></tr>
   <tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
   <tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
   <tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a  class='delbtn' href='#'>X</a></td></tr>
   <tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
   </td>
  </tr>
</table>
<div id="output"></div>?

the javascript:

$('#thisTable tr').on('click', function(event) {    
    var tds = $(this).addClass('row-highlight').find('td');
    var values = '';
    tds.each(function(index, item) {           
        values = values + 'td' + (index + 1) + ':' + $(item).html() + '<br/>';
    });
    $("#output").html(values);
});

Lodash - difference between .extend() / .assign() and .merge()

Here's how extend/assign works: For each property in source, copy its value as-is to destination. if property values themselves are objects, there is no recursive traversal of their properties. Entire object would be taken from source and set in to destination.

Here's how merge works: For each property in source, check if that property is object itself. If it is then go down recursively and try to map child object properties from source to destination. So essentially we merge object hierarchy from source to destination. While for extend/assign, it's simple one level copy of properties from source to destination.

Here's simple JSBin that would make this crystal clear: http://jsbin.com/uXaqIMa/2/edit?js,console

Here's more elaborate version that includes array in the example as well: http://jsbin.com/uXaqIMa/1/edit?js,console

installing requests module in python 2.7 windows

  1. Download the source code(zip or rar package).
  2. Run the setup.py inside.

How to make program go back to the top of the code instead of closing

You can easily do it with loops, there are two types of loops

For Loops:

for i in range(0,5):
    print 'Hello World'

While Loops:

count = 1
while count <= 5:
    print 'Hello World'
    count += 1

Each of these loops print "Hello World" five times

How to match, but not capture, part of a regex?

Update: Thanks to Germán Rodríguez Herrera!

In javascript try: /123-(apple(?=-)|banana(?=-)|(?!-))-?456/

Remember that the result is in group 1

Debuggex Demo

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

Running eclipse in Administrator Mode fixed it for me. You can do this by [Right Click] -> Run as Administrator on the eclipse.exe from your install dir.

I was on a working environment with win7 machine having restrictive permission. I also did remove the .lock and .log files but that did not help. It can be a combination of all as well that made it work.

Migration: Cannot add foreign key constraint

Add it in two steps, and it's good to make it unsigned too:

public function up()
{
    Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id')->unsigned();
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });

   Schema::table('priorities', function($table) {
       $table->foreign('user_id')->references('id')->on('users');
   });

}

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

pip3: command not found but python3-pip is already installed

Probably pip3 is installed in /usr/local/bin/ which is not in the PATH of the sudo (root) user. Use this instead

sudo /usr/local/bin/pip3 install virtualenv

Sort collection by multiple fields in Kotlin

Use sortedWith to sort a list with Comparator.

You can then construct a comparator using several ways:

  • compareBy, thenBy construct the comparator in a chain of calls:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
    
  • compareBy has an overload which takes multiple functions:

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    

How to sum the values of a JavaScript object?

I am a bit tardy to the party, however, if you require a more robust and flexible solution then here is my contribution. If you want to sum only a specific property in a nested object/array combo, as well as perform other aggregate methods, then here is a little function I have been using on a React project:

var aggregateProperty = function(obj, property, aggregate, shallow, depth) {
    //return aggregated value of a specific property within an object (or array of objects..)

    if ((typeof obj !== 'object' && typeof obj !== 'array') || !property) {
        return;
    }

    obj = JSON.parse(JSON.stringify(obj)); //an ugly way of copying the data object instead of pointing to its reference (so the original data remains unaffected)
    const validAggregates = [ 'sum', 'min', 'max', 'count' ];
    aggregate = (validAggregates.indexOf(aggregate.toLowerCase()) !== -1 ? aggregate.toLowerCase() : 'sum'); //default to sum

    //default to false (if true, only searches (n) levels deep ignoring deeply nested data)
    if (shallow === true) {
        shallow = 2;
    } else if (isNaN(shallow) || shallow < 2) {
        shallow = false;
    }

    if (isNaN(depth)) {
        depth = 1; //how far down the rabbit hole have we travelled?
    }

    var value = ((aggregate == 'min' || aggregate == 'max') ? null : 0);
    for (var prop in obj) {
        if (!obj.hasOwnProperty(prop)) {
            continue;
        }

        var propValue = obj[prop];
        var nested = (typeof propValue === 'object' || typeof propValue === 'array');
        if (nested) {
            //the property is an object or an array

            if (prop == property && aggregate == 'count') {
                value++;
            }

            if (shallow === false || depth < shallow) {
                propValue = aggregateProperty(propValue, property, aggregate, shallow, depth+1); //recursively aggregate nested objects and arrays
            } else {
                continue; //skip this property
            }
        }

        //aggregate the properties value based on the selected aggregation method
        if ((prop == property || nested) && propValue) {
            switch(aggregate) {
                case 'sum':
                    if (!isNaN(propValue)) {
                        value += propValue;
                    }
                    break;
                case 'min':
                    if ((propValue < value) || !value) {
                        value = propValue;
                    }
                    break;
                case 'max':
                    if ((propValue > value) || !value) {
                        value = propValue;
                    }
                    break;
                case 'count':
                    if (propValue) {
                        if (nested) {
                            value += propValue;
                        } else {
                            value++;
                        }
                    }
                    break;
            }
        }
    }

    return value;
}

It is recursive, non ES6, and it should work in most semi-modern browsers. You use it like this:

const onlineCount = aggregateProperty(this.props.contacts, 'online', 'count');

Parameter breakdown:

obj = either an object or an array
property = the property within the nested objects/arrays you wish to perform the aggregate method on
aggregate = the aggregate method (sum, min, max, or count)
shallow = can either be set to true/false or a numeric value
depth = should be left null or undefined (it is used to track the subsequent recursive callbacks)

Shallow can be used to enhance performance if you know that you will not need to search deeply nested data. For instance if you had the following array:

[
    {
        id: 1,
        otherData: { ... },
        valueToBeTotaled: ?
    },
    {
        id: 2,
        otherData: { ... },
        valueToBeTotaled: ?
    },
    {
        id: 3,
        otherData: { ... },
        valueToBeTotaled: ?
    },
    ...
]

If you wanted to avoid looping through the otherData property since the value you are going to be aggregating is not nested that deeply, you could set shallow to true.

Adding item to Dictionary within loop

As per my understanding you want data in dictionary as shown below:

key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3

for this you can use list for each dictionary keys:

case_list = {}
for entry in entries_list:
    if key in case_list:
        case_list[key1].append(value)
    else:
        case_list[key1] = [value]

Callback when DOM is loaded in react.js

The below is what I came up with to wait for when the DOM is ready before trying to get a class using document.getElementsByClassName. I called this function from the componentDidMount() lifecycle method.

     changeIcon() {
            if (
                document.getElementsByClassName('YOURCLASSNAME')
                    .length > 0 &&
                document.getElementsByClassName('YOURCLASSNAME').length > 0
            ) {
                document.getElementsByClassName(
                    'YOURCLASSNAME'
                )[0].className = 'YOUR-NEW-CLASSNAME';
                document.getElementsByClassName(
                    'YOUR-OTHER-EXISTING-CLASSNAME'
                )[0].style.display = 'block';
            } else {
                setTimeout(this.changeIcon, 500);
            }
     }

Access PHP variable in JavaScript

You can't, you'll have to do something like

<script type="text/javascript">
   var php_var = "<?php echo $php_var; ?>";
</script>

You can also load it with AJAX

rhino is right, the snippet lacks of a type for the sake of brevity.

Also, note that if $php_var has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.

How can I get the content of CKEditor using JQuery?


i add ckEditor by adding DLL in toolBox.
html code:

<CKEditor:CKEditorControl ID="editor1" runat="server" 
            BasePath="ckeditor" ContentsCss="ckeditor/contents.css" 
            Height="250px" 
            TemplatesFiles="ckeditor/themes/default/theme.js" FilebrowserBrowseUrl="ckeditor/plugins/FileManager/index.html" 
            FilebrowserFlashBrowseUrl="ckeditor/plugins/FileManager/index.html" FilebrowserFlashUploadUrl="ckeditor/plugins/FileManager/index.html" 
            FilebrowserImageBrowseLinkUrl="ckeditor/plugins/FileManager/index.html" FilebrowserImageBrowseUrl="ckeditor/plugins/FileManager/index.html" 
            FilebrowserImageUploadUrl="ckeditor/plugins/FileManager/index.html" 
            FilebrowserUploadUrl="ckeditor/plugins/FileManager/index.html" BackColor="#FF0066" 
                    DialogButtonsOrder="Rtl" 
                    FontNames="B Yekan;B Yekan,tahoma;Arial/Arial, Helvetica, sans-serif; Comic Sans MS/Comic Sans MS, cursive; Courier New/Courier New, Courier, monospace; Georgia/Georgia, serif; Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif; Tahoma/Tahoma, Geneva, sans-serif; Times New Roman/Times New Roman, Times, serif; Trebuchet MS/Trebuchet MS, Helvetica, sans-serif; Verdana/Verdana, Geneva, sans-serif" 
                    ResizeDir="Vertical" ResizeMinHeight="350" UIColor="#CACACA">dhd fdh</CKEditor:CKEditorControl>

for get data of it.
jquery:

var editor  = $('textarea iframe html body').html();
    alert(editor); 

Invoke native date picker from web-app on iOS/Android

My answer is over-simplistic. If you like to write simple code that works cross-platform, then use the window.prompt method to ask the user for a date. Obviously you need to validate with a regex and then create the date object.

function onInputClick(e){
var r = window.prompt("Give me a date (YYYY-MM-DD)", "2014-01-01");
if(/[\d]{4}-[\d]{1,2}-[\d]{1,2}/.test(r)){
    //date ok
    e.value=r;
    var split=e.value.split("-");
    var date=new Date(parseInt(split[0]),parseInt(split[1])-1,parseInt(split[2]));
}else{
    alert("Invalid date. Try again.");
}
}

In you HTML:

<input type="text" onclick="onInputClick(this)" value="2014-01-01">

How to split a string with angularJS

You could try this:

$scope.testdata = [{ 'name': 'name,id' }, {'name':'someName,someId'}]
$scope.array= [];
angular.forEach($scope.testdata, function (value, key) {
    $scope.array.push({ 'name': value.name.split(',')[0], 'id': value.name.split(',')[1] });
});
console.log($scope.array)

This way you can save the data for later use and acces it by using an ng-repeat like this:

<div ng-repeat="item in array">{{item.name}}{{item.id}}</div>


I hope this helped someone,
Plunker link: here
All credits go to @jwpfox and @Mohideen ibn Mohammed from the answer above.

Git and nasty "error: cannot lock existing info/refs fatal"

for me, removing .git/info/ref kick things going.There shouldn't be a ref file when git is not running. But in my case there were one for whatever reason and caused the problem.

Removing the file will not remove any of your local commits or branches.

How to uninstall / completely remove Oracle 11g (client)?

Do everything suggested by ziesemer.

You may also want to remove from the registry:

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\<any Ora* drivers> keys     

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers<any Ora* driver> values

So they no longer appear in the "ODBC Drivers that are installed on your system" in ODBC Data Source Administrator

Setting up enviromental variables in Windows 10 to use java and javac

Adding Environment Variable simplified with screenshot. Check the below URL and you should be able to do without any trouble.

https://itsforlavanya.blogspot.com/2020/08/environment-variable-simple-7-steps-to.html

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'] will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _, is that a typo?

What's "P=NP?", and why is it such a famous question?

P stands for polynomial time. NP stands for non-deterministic polynomial time.

Definitions:

  • Polynomial time means that the complexity of the algorithm is O(n^k), where n is the size of your data (e. g. number of elements in a list to be sorted), and k is a constant.

  • Complexity is time measured in the number of operations it would take, as a function of the number of data items.

  • Operation is whatever makes sense as a basic operation for a particular task. For sorting, the basic operation is a comparison. For matrix multiplication, the basic operation is multiplication of two numbers.

Now the question is, what does deterministic vs. non-deterministic mean? There is an abstract computational model, an imaginary computer called a Turing machine (TM). This machine has a finite number of states, and an infinite tape, which has discrete cells into which a finite set of symbols can be written and read. At any given time, the TM is in one of its states, and it is looking at a particular cell on the tape. Depending on what it reads from that cell, it can write a new symbol into that cell, move the tape one cell forward or backward, and go into a different state. This is called a state transition. Amazingly enough, by carefully constructing states and transitions, you can design a TM, which is equivalent to any computer program that can be written. This is why it is used as a theoretical model for proving things about what computers can and cannot do.

There are two kinds of TM's that concern us here: deterministic and non-deterministic. A deterministic TM only has one transition from each state for each symbol that it is reading off the tape. A non-deterministic TM may have several such transition, i. e. it is able to check several possibilities simultaneously. This is sort of like spawning multiple threads. The difference is that a non-deterministic TM can spawn as many such "threads" as it wants, while on a real computer only a specific number of threads can be executed at a time (equal to the number of CPUs). In reality, computers are basically deterministic TMs with finite tapes. On the other hand, a non-deterministic TM cannot be physically realized, except maybe with a quantum computer.

It has been proven that any problem that can be solved by a non-deterministic TM can be solved by a deterministic TM. However, it is not clear how much time it will take. The statement P=NP means that if a problem takes polynomial time on a non-deterministic TM, then one can build a deterministic TM which would solve the same problem also in polynomial time. So far nobody has been able to show that it can be done, but nobody has been able to prove that it cannot be done, either.

NP-complete problem means an NP problem X, such that any NP problem Y can be reduced to X by a polynomial reduction. That implies that if anyone ever comes up with a polynomial-time solution to an NP-complete problem, that will also give a polynomial-time solution to any NP problem. Thus that would prove that P=NP. Conversely, if anyone were to prove that P!=NP, then we would be certain that there is no way to solve an NP problem in polynomial time on a conventional computer.

An example of an NP-complete problem is the problem of finding a truth assignment that would make a boolean expression containing n variables true.
For the moment in practice any problem that takes polynomial time on the non-deterministic TM can only be done in exponential time on a deterministic TM or on a conventional computer.
For example, the only way to solve the truth assignment problem is to try 2^n possibilities.

Adding IN clause List to a JPA Query

When using IN with a collection-valued parameter you don't need (...):

@NamedQuery(name = "EventLog.viewDatesInclude", 
    query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND " 
    + "el.timeMark <= :dateTo AND " 
    + "el.name IN :inclList") 

How to force div to appear below not next to another?

use clear:left; or clear:both in your css.

#map { float:left; width:700px; height:500px; }
 #list { float:left; width:200px; background:#eee; list-style:none; padding:0; }
 #similar { float:left; width:200px; background:#000; clear:both; } 


<div id="map"></div>        
<ul id="list"></ul>
<div id ="similar">
 this text should be below, not next to ul.
</div>

How do I use Docker environment variable in ENTRYPOINT array?

After much pain, and great assistance from @vitr et al above, i decided to try

  • standard bash substitution
  • shell form of ENTRYPOINT (great tip from above)

and that worked.

ENV LISTEN_PORT=""

ENTRYPOINT java -cp "app:app/lib/*" hello.Application --server.port=${LISTEN_PORT:-80}

e.g.

docker run --rm -p 8080:8080 -d --env LISTEN_PORT=8080 my-image

and

docker run --rm -p 8080:80 -d my-image

both set the port correctly in my container

Refs

see https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html

Twitter Bootstrap Responsive Background-Image inside Div

Try this (apply to a class you image is in (not img itself), e.g.

.myimage {
  background: transparent url("yourimage.png") no-repeat top center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: 100%;
  height: 500px;
}

Fatal error: Call to undefined function mysql_connect()

PHP.INI

Check if you forgot to enable the options below(loads the modules for mysql among others):

; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
extension_dir = "ext"

Determine file creation date in Java

The API of java.io.File only supports getting the last modified time. And the Internet is very quiet on this topic as well.

Unless I missed something significant, the Java library as is (up to but not yet including Java 7) does not include this capability. So if you were desperate for this, one solution would be to write some C(++) code to call system routines and call it using JNI. Most of this work seems to be already done for you in a library called JNA, though.

You may still need to do a little OS specific coding in Java for this, though, as you'll probably not find the same system calls available in Windows and Unix/Linux/BSD/OS X.

Bootstrap 3 jquery event for active tab change

Thanks to @Gerben's post came to know there are two events show.bs.tab (before the tab is shown) and shown.bs.tab (after the tab is shown) as explained in the docs - Bootstrap Tab usage

An additional solution if we're only interested in a specific tab, and maybe add separate functions without having to add an if - else block in one function, is to use the a href selector (maybe along with additional selectors if required)

 $("a[href='#tab_target_id']").on('shown.bs.tab', function(e) {
      console.log('shown - after the tab has been shown');
 });

 // or even this one if we want the earlier event
 $("a[href='#tab_target_id']").on('show.bs.tab', function(e) {
      console.log('show - before the new tab has been shown');
 });

demo

How can I use Guzzle to send a POST request in JSON?

Simply use this it will work

   $auth = base64_encode('user:'.config('mailchimp.api_key'));
    //API URL
    $urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
    //API authentication Header
    $headers = array(
        'Accept'     => 'application/json',
        'Authorization' => 'Basic '.$auth
    );
    $client = new Client();
    $req_Memeber = new Request('POST', $urll, $headers, $userlist);
    // promise
    $promise = $client->sendAsync($req_Memeber)->then(function ($res){
            echo "Synched";
        });
      $promise->wait();

Send string to stdin

You were close

/my/bash/script <<< 'This string will be sent to stdin.'

For multiline input, here-docs are suited:

/my/bash/script <<STDIN -o other --options
line 1
line 2
STDIN

Edit To the comments:

To achieve binary input, say

xxd -r -p <<BINARY | iconv -f UCS-4BE -t UTF-8 | /my/bash/script
0000 79c1 0000 306f 0000 3061 0000 3093 0000 3077 0000 3093 0000 304b 0000 3093 0000 3077 0000 3093 0000 306a 0000 8a71 0000 306b 0000 30ca 0000 30f3 0000 30bb
0000 30f3 0000 30b9 0000 3092 0000 7ffb 0000 8a33 0000 3059 0000 308b 0000 3053 0000 3068 0000 304c 0000 3067 0000 304d 0000 000a
BINARY

If you substitute cat for /my/bash/script (or indeed drop the last pipe), this prints:

????????????????????????????

Or, if you wanted something a little more geeky:

0000000: 0000 0000 bef9 0e3c 59f8 8e3c 0a71 d63c  .......<Y..<.q.<
0000010: c6f2 0e3d 3eaa 323d 3a5e 563d 090e 7a3d  ...=>.2=:^V=..z=
0000020: 7bdc 8e3d 2aaf a03d b67e b23d c74a c43d  {..=*..=.~.=.J.=
0000030: 0513 d63d 16d7 e73d a296 f93d a8a8 053e  ...=...=...=...>
0000040: 6583 0e3e 5a5b 173e 5b30 203e 3d02 293e  e..>Z[.>[0 >=.)>
0000050: d4d0 313e f39b 3a3e 6f63 433e 1c27 4c3e  ..1>..:>ocC>.'L>
0000060: cde6 543e 59a2 5d3e 9259 663e 4d0c 6f3e  ..T>Y.]>.Yf>M.o>
0000070: 60ba 773e cf31 803e ee83 843e 78d3 883e  `.w>.1.>...>x..>
0000080: 5720 8d3e 766a 913e beb1 953e 1cf6 993e  W .>vj.>...>...>
0000090: 7a37 9e3e c275 a23e dfb0 a63e bce8 aa3e  z7.>.u.>...>...>
00000a0: 441d af3e 624e b33e 017c b73e 0ca6 bb3e  D..>bN.>.|.>...>
00000b0: 6fcc bf3e 15ef c33e e90d c83e d728 cc3e  o..>...>...>.(.>
00000c0: c93f d03e ac52 d43e 6c61 d83e f36b dc3e  .?.>.R.>la.>.k.>
00000d0: 2f72 e03e 0a74 e43e 7171 e83e 506a ec3e  /r.>.t.>qq.>Pj.>
00000e0: 945e f03e 274e f43e f738 f83e f11e fc3e  .^.>'N.>.8.>...>
00000f0: 0000 003f 09ee 013f 89d9 033f 77c2 053f  ...?...?...?w..?
0000100: caa8 073f 788c 093f 776d 0b3f be4b 0d3f  ...?x..?wm.?.K.?
0000110: 4427 0f3f 0000 113f e8d5 123f f3a8 143f  D'.?...?...?...?
0000120: 1879 163f 4e46 183f 8d10 1a3f cad7 1b3f  .y.?NF.?...?...?
0000130: fe9b 1d3f 1f5d 1f3f 241b 213f 06d6 223f  ...?.].?$.!?.."?
0000140: bb8d 243f 3a42 263f 7cf3 273f 78a1 293f  ..$?:B&?|.'?x.)?
0000150: 254c 2b3f 7bf3 2c3f 7297 2e3f 0138 303f  %L+?{.,?r..?.80?
0000160: 22d5 313f ca6e 333f                      ".1?.n3?

Which is the sines of the first 90 degrees in 4byte binary floats

How to prevent a jQuery Ajax request from caching in Internet Explorer?

you can define it like this :

let table = $('.datatable-sales').DataTable({
        processing: true,
        responsive: true,
        serverSide: true,
        ajax: {
            url: "<?php echo site_url("your url"); ?>",
            cache: false,
            type: "POST",
            data: {
                <?php echo your api; ?>,
            }
        }

or like this :

$.get({url: <?php echo json_encode(site_url('your api'))?>, cache: false})

hope it helps

Removing display of row names from data frame

If you want to format your table via kable, you can use row.names = F

kable(df, row.names = F)

Problems with local variable scope. How to solve it?

not Error:

JSONObject json1 = getJsonX();

Error:

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

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

But you can write:

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

How to conditional format based on multiple specific text in Excel

You can use MATCH for instance.

  1. Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.

  2. In the entry box, put:

    =MATCH(A2, 'Sheet2'!A:A, 0)
    
  3. Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.

MATCH takes the value A2 from your data table, looks into 'Sheet2'!A:A and if there's an exact match (that's why there's a 0 at the end), then it'll return the row number.

Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.

EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:

=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))

How to add Certificate Authority file in CentOS 7

Your CA file must have been in a binary X.509 format instead of Base64 encoding; it needs to be a regular DER or PEM in order for it to be added successfully to the list of trusted CAs on your server.

To proceed, do place your CA file inside your /usr/share/pki/ca-trust-source/anchors/ directory, then run the command line below (you might need sudo privileges based on your settings);

# CentOS 7, Red Hat 7, Oracle Linux 7
update-ca-trust

Please note that all trust settings available in the /usr/share/pki/ca-trust-source/anchors/ directory are interpreted with a lower priority compared to the ones placed under the /etc/pki/ca-trust/source/anchors/ directory which may be in the extended BEGIN TRUSTED file format.

For Ubuntu and Debian systems, /usr/local/share/ca-certificates/ is the preferred directory for that purpose.

As such, you need to place your CA file within the /usr/local/share/ca-certificates/ directory, then update the of trusted CAs by running, with sudo privileges where required, the command line below;

update-ca-certificates

Difference between the Apache HTTP Server and Apache Tomcat?

  1. Apache is a general-purpose http server, which supports a number of advanced options that Tomcat doesn't.
  2. Although Tomcat can be used as a general purpose http server, you can also set up Apache and Tomcat to work together with Apache serving static content and forwarding the requests for dynamic content to Tomcat.

How to align footer (div) to the bottom of the page?

Use <div style="position:fixed;bottom:0;height:auto;margin-top:40px;width:100%;text-align:center">I am footer</div>. Footer will not go upwards

In a bootstrap responsive page how to center a div

CSS:

html,
body {
    height: 100%;
}

.container {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

HTML:

<div class="container">
  <div>
    example
  </div>
</div>

Example fiddle

How to increase the Java stack size?

It is hard to give a sensible solution since you are keen to avoid all sane approaches. Refactoring one line of code is the senible solution.

Note: Using -Xss sets the stack size of every thread and is a very bad idea.

Another approach is byte code manipulation to change the code as follows;

public static long fact(int n) { 
    return n < 2 ? n : n > 127 ? 0 : n * fact(n - 1); 
}

given every answer for n > 127 is 0. This avoid changing the source code.

How to add buttons at top of map fragment API v2 layout

extending de Almeida's answer I am editing code little bit here. since previous code was hiding gps location icon I did following way which worked better.

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"

>

<RadioGroup 
    android:id="@+id/radio_group_list_selector"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:orientation="horizontal" 
    android:background="#80000000"
    android:padding="4dp" >

    <RadioButton
        android:id="@+id/radioPopular"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="@string/Popular"
        android:gravity="center_horizontal|center_vertical"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioAZ"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/AZ"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />

    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioCategory"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/Category"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioNearBy"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/NearBy"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton3"
        android:textColor="@drawable/textcolor_radiobutton" />
</RadioGroup>

<fragment
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:scrollbars="vertical" />

Proper way to restrict text input values (e.g. only numbers)

To catch all the event surrounding model changes, can consider using

<input (ngModelChange)="inputFilter($event)"/>

It will detect copy / paste, keyup, any condition that changes the value of the model.

And then:

inputFilter(event: any) {
    const pattern = /[0-9\+\-\ ]/;
    let inputChar = String.fromCharCode(event.charCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
    }
}

Find files and tar them (with spaces)

Big warning on several of the solutions (and your own test) :

When you do : anything | xargs something

xargs will try to fit "as many arguments as possible" after "something", but then you may end up with multiple invocations of "something".

So your attempt: find ... | xargs tar czvf file.tgz may end up overwriting "file.tgz" at each invocation of "tar" by xargs, and you end up with only the last invocation! (the chosen solution uses a GNU -T special parameter to avoid the problem, but not everyone has that GNU tar available)

You could do instead:

find . -type f -print0 | xargs -0 tar -rvf backup.tar
gzip backup.tar

Proof of the problem on cygwin:

$ mkdir test
$ cd test
$ seq 1 10000 | sed -e "s/^/long_filename_/" | xargs touch 
    # create the files
$ seq 1 10000 | sed -e "s/^/long_filename_/" | xargs tar czvf archive.tgz
    # will invoke tar several time as it can'f fit 10000 long filenames into 1
$ tar tzvf archive.tgz | wc -l
60
    # in my own machine, I end up with only the 60 last filenames, 
    # as the last invocation of tar by xargs overwrote the previous one(s)

# proper way to invoke tar: with -r  (which append to an existing tar file, whereas c would overwrite it)
# caveat: you can't have it compressed (you can't add to a compressed archive)
$ seq 1 10000 | sed -e "s/^/long_filename_/" | xargs tar rvf archive.tar #-r, and without z
$ gzip archive.tar
$ tar tzvf archive.tar.gz | wc -l
10000 
  # we have all our files, despite xargs making several invocations of the tar command

 

Note: that behavior of xargs is a well know diccifulty, and it is also why, when someone wants to do :

find .... | xargs grep "regex"

they intead have to write it:

find ..... | xargs grep "regex" /dev/null

That way, even if the last invocation of grep by xargs appends only 1 filename, grep sees at least 2 filenames (as each time it has: /dev/null, where it won't find anything, and the filename(s) appended by xargs after it) and thus will always display the file names when something maches "regex". Otherwise you may end up with the last results showing matches without a filename in front.

Datatable select with multiple conditions

Yes, the DataTable.Select method supports boolean operators in the same way that you would use them in a "real" SQL statement:

DataRow[] results = table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'");

See DataColumn.Expression in MSDN for the syntax supported by DataTable's Select method.

How do I use su to execute the rest of the bash script as that user?

Much simpler: use sudo to run a shell and use a heredoc to feed it commands.

#!/usr/bin/env bash
whoami
sudo -i -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami

(answer originally on SuperUser)

Find what 2 numbers add to something and multiply to something

Here is how I would do that:

$sum = 5;
$product = 6;

$found = FALSE;
for ($a = 1; $a < $sum; $a++) {
  $b = $sum - $a;
  if ($a * $b == $product) {
    $found = TRUE;
    break;
  }
}

if ($found) {
  echo "The answer is a = $a, b = $b.";
} else {
  echo "There is no answer where a and b are both integers.";
}

Basically, start at $a = 1 and $b = $sum - $a, step through it one at a time since we know then that $a + $b == $sum is always true, and multiply $a and $b to see if they equal $product. If they do, that's the answer.

See it working

Whether that is the most efficient method is very much debatable.

Creating and appending text to txt file in VB.NET

Don't check File.Exists() like that. In fact, the whole thing is over-complicated. This should do what you need:

Dim strFile As String = $@"C:\ErrorLog_{DateTime.Today:dd-MMM-yyyy}.txt"
File.AppendAllText(strFile, $"Error Message in  Occured at-- {DateTime.Now}{Environment.NewLine}")

Got it all down to two lines of code :)

Shell Script — Get all files modified after <date>

This script will find files having a modification date of two minutes before and after the given date (and you can change the values in the conditions as per your requirement)

PATH_SRC="/home/celvas/Documents/Imp_Task/"
PATH_DST="/home/celvas/Downloads/zeeshan/"

cd $PATH_SRC
TODAY=$(date  -d "$(date +%F)" +%s)
TODAY_TIME=$(date -d "$(date +%T)" +%s)


for f in `ls`;
do
#       echo "File -> $f"
        MOD_DATE=$(stat -c %y "$f")
        MOD_DATE=${MOD_DATE% *}
#       echo MOD_DATE: $MOD_DATE
        MOD_DATE1=$(date -d "$MOD_DATE" +%s)
#       echo MOD_DATE: $MOD_DATE

DIFF_IN_DATE=$[ $MOD_DATE1 - $TODAY ]
DIFF_IN_DATE1=$[ $MOD_DATE1 - $TODAY_TIME ]
#echo DIFF: $DIFF_IN_DATE
#echo DIFF1: $DIFF_IN_DATE1
if [[ ($DIFF_IN_DATE -ge -120) && ($DIFF_IN_DATE1 -le 120) && (DIFF_IN_DATE1 -ge -120) ]]
then
echo File lies in Next Hour = $f
echo MOD_DATE: $MOD_DATE

#mv $PATH_SRC/$f  $PATH_DST/$f
fi
done

For example you want files having modification date before the given date only, you may change 120 to 0 in $DIFF_IN_DATE parameter discarding the conditions of $DIFF_IN_DATE1 parameter.

Similarly if you want files having modification date 1 hour before and after given date, just replace 120 by 3600 in if CONDITION.

elasticsearch bool query combine must with OR

If you were using Solr's default or Lucene query parser, you can pretty much always put it into a query string query:

POST test/_search
{
  "query": {
    "query_string": {
      "query": "(( name:(+foo +bar) OR info:(+foo +bar)  )) AND state:(1) AND (has_image:(0) OR has_image:(1)^100)"
    }
  }
}

That said, you may want to use a boolean query, like the one you already posted, or even a combination of the two.

When is a timestamp (auto) updated?

Adding where to find UPDATE CURRENT_TIMESTAMP because for new people this is a confusion.

Most people will use phpmyadmin or something like it.

Default value you select CURRENT_TIMESTAMP

Attributes (a different drop down) you select UPDATE CURRENT_TIMESTAMP

Can I send a ctrl-C (SIGINT) to an application on Windows?

Edit:

For a GUI App, the "normal" way to handle this in Windows development would be to send a WM_CLOSE message to the process's main window.

For a console app, you need to use SetConsoleCtrlHandler to add a CTRL_C_EVENT.

If the application doesn't honor that, you could call TerminateProcess.

How to exclude a directory from ant fileset, based on directories contents

You need to add a '/' after the dir name

<exclude name="WEB-INF/" />

Groovy Shell warning "Could not open/create prefs root node ..."

I was getting the following message:

Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002

and it was gone after creating one of these registry keys, mine is 64 bit so I tried only that.

32 bit Windows
HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

64 bit Windows
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

Caching a jquery ajax response in javascript/browser

Old question, but my solution is a bit different.

I was writing a single page web app that was constantly making ajax calls triggered by the user, and to make it even more difficult it required libraries that used methods other than jquery (like dojo, native xhr, etc). I wrote a plugin for one of my own libraries to cache ajax requests as efficiently as possible in a way that would work in all major browsers, regardless of which libraries were being used to make the ajax call.

The solution uses jSQL (written by me - a client-side persistent SQL implementation written in javascript which uses indexeddb and other dom storage methods), and is bundled with another library called XHRCreep (written by me) which is a complete re-write of the native XHR object.

To implement all you need to do is include the plugin in your page, which is here.

There are two options:

jSQL.xhrCache.max_time = 60;

Set the maximum age in minutes. any cached responses that are older than this are re-requested. Default is 1 hour.

jSQL.xhrCache.logging = true;

When set to true, mock XHR calls will be shown in the console for debugging.

You can clear the cache on any given page via

jSQL.tables = {}; jSQL.persist();

C# Error "The type initializer for ... threw an exception

This problem can occur if a class tries to get value of a non-existent key in web.config.

For example, the class has a static variable ClientID

private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();

but the web.config doesn't contain the 'GoogleCalendarApplicationClientID' key, then the error will be thrown on any static function call or any class instance creation

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

How do I call an Angular 2 pipe with multiple arguments?

I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.

Here is the Pipe being called in an *ngFor directive,

<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
  Hello {{item.first}} !
</div>

Here is the Pipe,

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
  transform(myobjects: Array<object>, args?: Array<object>): any {
    if (args && Array.isArray(myobjects)) {
      // copy all objects of original array into new array of objects
      var returnobjects = myobjects;
      // args are the compare oprators provided in the *ngFor directive
      args.forEach(function (filterobj) {
        let filterkey = Object.keys(filterobj)[0];
        let filtervalue = filterobj[filterkey];
        myobjects.forEach(function (objectToFilter) {
          if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
            // object didn't match a filter value so remove it from array via filter
            returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
          }
        })
      });
      // return new array of objects to *ngFor directive
      return returnobjects;
    }
  }
}

And here is the Component containing the object to filter,

import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  items = [{ title: "mr", first: "john", last: "jones" }
   ,{ title: "mr", first: "adrian", last: "jacobs" }
   ,{ title: "mr", first: "lou", last: "jones" }
   ,{ title: "ms", first: "linda", last: "hamilton" }
  ];
}

StackBlitz Example

GitHub Example: Fork a working copy of this example here

*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.

Happy Coding :-)

How to execute a program or call a system command from Python

Use:

import os

cmd = 'ls -al'

os.system(cmd)

os - This module provides a portable way of using operating system-dependent functionality.

For the more os functions, here is the documentation.

Getting the actual usedrange

I use the following vba code to determine the entire used rows range for the worksheet to then shorten the selected range of a column:

    Set rUsedRowRange = Selection.Worksheet.UsedRange.Columns( _
    Selection.Column - Selection.Worksheet.UsedRange.Column + 1)

Also works the other way around:

    Set rUsedColumnRange = Selection.Worksheet.UsedRange.Rows( _
    Selection.Row - Selection.Worksheet.UsedRange.Row + 1)

How can I import data into mysql database via mysql workbench?

  • Under Server Administration on the Home window select the server instance you want to restore database to (Create New Server Instance if doing it first time).
  • Click on Manage Import/Export
  • Click on Data Import/Restore on the left side of the screen.
  • Select Import from Self-Contained File radio button (right side of screen)
  • Select the path of .sql
  • Click Start Import button at the right bottom corner of window.

Hope it helps.

---Edited answer---

Regarding selection of the schema. MySQL Workbench (5.2.47 CE Rev1039) does not yet support exporting to the user defined schema. It will create only the schema for which you exported the .sql... In 5.2.47 we see "New" target schema. But it does not work. I use MySQL Administrator (the old pre-Oracle MySQL Admin beauty) for my work for backup/restore. You can still download it from Googled trustable sources (search MySQL Administrator 1.2.17).

Check if a variable is of function type

For those who's interested in functional style, or looks for more expressive approach to utilize in meta programming (such as type checking), it could be interesting to see Ramda library to accomplish such task.

Next code contains only pure and pointfree functions:

const R = require('ramda');

const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);

const equalsSyncFunction = isPrototypeEquals(() => {});

const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);

As of ES2017, async functions are available, so we can check against them as well:

const equalsAsyncFunction = isPrototypeEquals(async () => {});

const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);

And then combine them together:

const isFunction = R.either(isSyncFunction, isAsyncFunction);

Of course, function should be protected against null and undefined values, so to make it "safe":

const safeIsFunction = R.unless(R.isNil, isFunction);

And, complete snippet to sum up:

const R = require('ramda');

const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);

const equalsSyncFunction = isPrototypeEquals(() => {});
const equalsAsyncFunction = isPrototypeEquals(async () => {});

const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);

const isFunction = R.either(isSyncFunction, isAsyncFunction);

const safeIsFunction = R.unless(R.isNil, isFunction);

// ---

console.log(safeIsFunction( function () {} ));
console.log(safeIsFunction( () => {} ));
console.log(safeIsFunction( (async () => {}) ));
console.log(safeIsFunction( new class {} ));
console.log(safeIsFunction( {} ));
console.log(safeIsFunction( [] ));
console.log(safeIsFunction( 'a' ));
console.log(safeIsFunction( 1 ));
console.log(safeIsFunction( null ));
console.log(safeIsFunction( undefined ));

However, note the this solution could show less performance than other available options due to extensive usage of higher-order functions.

What is the shortest function for reading a cookie by name in JavaScript?

To truly remove as much bloat as possible, consider not using a wrapper function at all:

try {
    var myCookie = document.cookie.match('(^|;) *myCookie=([^;]*)')[2]
} catch (_) {
    // handle missing cookie
}

As long as you're familiar with RegEx, that code is reasonably clean and easy to read.

How can I get the current network interface throughput statistics on Linux/UNIX?

I wrote this dumb script a long time ago, it depends on nothing but Perl and Linux≥2.6:

#!/usr/bin/perl

use strict;
use warnings;

use POSIX qw(strftime);
use Time::HiRes qw(gettimeofday usleep);

my $dev = @ARGV ? shift : 'eth0';
my $dir = "/sys/class/net/$dev/statistics";
my %stats = do {
    opendir +(my $dh), $dir;
    local @_ = readdir $dh;
    closedir $dh;
    map +($_, []), grep !/^\.\.?$/, @_;
};

if (-t STDOUT) {
    while (1) {
        print "\033[H\033[J", run();
        my ($time, $us) = gettimeofday();
        my ($sec, $min, $hour) = localtime $time;
        {
            local $| = 1;
            printf '%-31.31s: %02d:%02d:%02d.%06d%8s%8s%8s%8s',
            $dev, $hour, $min, $sec, $us, qw(1s 5s 15s 60s)
        }
        usleep($us ? 1000000 - $us : 1000000);
    }
}
else {print run()}

sub run {
    map {
        chomp (my ($stat) = slurp("$dir/$_"));
        my $line = sprintf '%-31.31s:%16.16s', $_, $stat;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[0]) / 1)
            if @{$stats{$_}} > 0;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[4]) / 5)
            if @{$stats{$_}} > 4;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[14]) / 15)
            if @{$stats{$_}} > 14;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[59]) / 60)
            if @{$stats{$_}} > 59;
        unshift @{$stats{$_}}, $stat;
        pop @{$stats{$_}} if @{$stats{$_}} > 60;
        "$line\n";
    } sort keys %stats;
}

sub slurp {
    local @ARGV = @_;
    local @_ = <>;
    @_;
}

It just reads from /sys/class/net/$dev/statistics every second, and prints out the current numbers and the average rate of change:

$ ./net_stats.pl eth0
rx_bytes                       :  74457040115259 4369093 4797875 4206554 364088
rx_packets                     :     91215713193   23120   23502   23234  17616
...
tx_bytes                       :  90798990376725 8117924 7047762 7472650 319330
tx_packets                     :     93139479736   23401   22953   23216  23171
...
eth0                           : 15:22:09.002216      1s      5s     15s     60s

                                ^ current reading  ^-------- averages ---------^

Regex to split a CSV

In Java this pattern ",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))" almost work for me:

String text = "\",\",\",,\",,\",asdasd a,sd s,ds ds,dasda,sds,ds,\"";
String regex = ",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))";
Pattern p = Pattern.compile(regex);
String[] split = p.split(text);
for(String s:split) {
    System.out.println(s);
}

output:

","
",a,,"

",asdasd a,sd s,ds ds,dasda,sds,ds,"

Disadvantage: not work, when column have an odd number of quotes :(

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

It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.

You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:

http://jsfiddle.net/2w157dyL/1/

However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.

So the fix is very, very simple - add enough right padding to account for the scrollbar:

http://jsfiddle.net/2w157dyL/2/

_x000D_
_x000D_
  main > section {_x000D_
    overflow-y: auto;_x000D_
    padding-right: 2em;_x000D_
  }
_x000D_
_x000D_
_x000D_

It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!

Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help

Input group - two inputs close to each other

working workaround:

<div class="input-group">
    <input type="text" class="form-control input-sm" value="test1" />
    <span class="input-group-btn" style="width:0px;"></span>
    <input type="text" class="form-control input-sm" value="test2" />
</div>

downside: no border-collapse between the two text-fields, but they keep next to each other

http://jsfiddle.net/EfC26/

Update

thanks to Stalinko

This technique allows to glue more than 2 inputs. Border-collapsing is achieved using "margin-left: -1px" (-2px for the 3rd input and so on)

<div class="input-group">
  <input type="text" class="form-control input-sm" value="test1" />
  <span class="input-group-btn" style="width:0px;"></span>
  <input type="text" class="form-control input-sm" value="test2" style="margin-left:-1px" />
  <span class="input-group-btn" style="width:0px;"></span>
  <input type="text" class="form-control input-sm" value="test2" style="margin-left:-2px" />
</div>

http://jsfiddle.net/yLvk5mn1/1/

How to copy directories with spaces in the name

After some trial and error and observing the results (in other words, I hacked it), I got it to work.

Quotes ARE required to use a path name with spaces. The trick is there MUST be a space after the path names before the closing quote...like this...

robocopy "C:\Source Path " "C:\Destination Path " /option1 /option2...

This almost seems like a bug and certainly not very intuitive.

Todd K.

How to insert a row in an HTML table body in JavaScript

I think this script is what exactly you need

var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

-- I like this as the data type and the format remains consistent with a date time data type

;with cte as(
    select 
        cast(utcdate as date) UtcDay, DATEPART(hour, utcdate) UtcHour, count(*) as Counts
    from dbo.mytable cd 
    where utcdate between '2014-01-14' and '2014-01-15'
    group by
        cast(utcdate as date), DATEPART(hour, utcdate)
)
select dateadd(hour, utchour, cast(utcday as datetime)) as UTCDateHour, Counts
from cte

How to transfer some data to another Fragment?

To extend the previous answer even more, like Ankit was saying, for complex objects you need to implement Serializable. For example, for the simple object:

public class MyClass implements Serializable {
    private static final long serialVersionUID = -2163051469151804394L;
    private int id;
    private String created;
}

In you FromFragment:

Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
    .beginTransaction()
    .replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
    .addToBackStack(TAG_TO_FRAGMENT).commit();

in your ToFragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    Bundle args = getArguments();
    MyClass myClass = (MyClass) args
        .getSerializable(TAG_MY_CLASS);

AngularJs: Reload page

It's easy enough to just use $route.reload() (don't forget to inject $route into your controller), but from your example you could just use "href" instead of "ng-href":

<a href=""  class="navbar-brand" title="home"  data-translate>PORTAL_NAME</a>

You only need to use ng-href to protect the user from invalid links caused by them clicking before Angular has replaced the contents of the {{ }} tags.

How to get json key and value in javascript?

//By using jquery json parser    
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(obj['jobtitel']);

//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(t['jobtitel'])

Check this jsfiddle

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.

Source: http://api.jquery.com/jquery.parsejson/

Unique Key constraints for multiple columns in Entity Framework

Recently added a composite key with the uniqueness of 2 columns using the approach that 'chuck' recommended, thank @chuck. Only this approached looked cleaner to me:

public int groupId {get; set;}

[Index("IX_ClientGrouping", 1, IsUnique = true)]
public int ClientId { get; set; }

[Index("IX_ClientGrouping", 2, IsUnique = true)]
public int GroupName { get; set; }

XSLT equivalent for JSON

XSLT equivalents for JSON - a list of candidates (tools and specs)

Tools

1. XSLT

You can use XSLT for JSON with the aim of fn:json-to-xml.

This section describes facilities allowing JSON data to be processed using XSLT.

2. jq

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text. There are install packages for different OS.

3. jj

JJ is a command line utility that provides a fast and simple way to retrieve or update values from JSON documents. It's powered by GJSON and SJSON under the hood.

4. fx

Command-line JSON processing tool - Don't need to learn new syntax - Plain JavaScript - Formatting and highlighting - Standalone binary

5. jl

jl ("JSON lambda") is a tiny functional language for querying and manipulating JSON.

6. JOLT

JSON to JSON transformation library written in Java where the "specification" for the transform is itself a JSON document.

7. gron

Make JSON greppable! gron transforms JSON into discrete assignments to make it easier to grep for what you want and see the absolute 'path' to it. It eases the exploration of APIs that return large blobs of JSON but have terrible documentation.

8. json-e

JSON-e is a data-structure parameterization system for embedding context in JSON objects. The central idea is to treat a data structure as a "template" and transform it, using another data structure as context, to produce an output data structure.

9. JSLT

JSLT is a complete query and transformation language for JSON. The language design is inspired by jq, XPath, and XQuery.

10. JSONata

JSONata is a lightweight query and transformation language for JSON data. Inspired by the 'location path' semantics of XPath 3.1, it allows sophisticated queries to be expressed in a compact and intuitive notation.

11. JSONPath Plus

Analyse, transform, and selectively extract data from JSON documents (and JavaScript objects). jsonpath-plus expands on the original specification to add some additional operators and makes explicit some behaviors the original did not spell out.

12. json-transforms Last Commit Dec 1, 2017

Provides a recursive, pattern-matching approach to transforming JSON data. Transformations are defined as a set of rules which match the structure of a JSON object. When a match occurs, the rule emits the transformed data, optionally recursing to transform child objects.

13. json Last commit Jun 23, 2018

json is a fast CLI tool for working with JSON. It is a single-file node.js script with no external deps (other than node.js itself).

14. jsawk Last commit Mar 4, 2015

Jsawk is like awk, but for JSON. You work with an array of JSON objects read from stdin, filter them using JavaScript to produce a results array that is printed to stdout.

15. yate Last Commit Mar 13, 2017

Tests can be used as docu https://github.com/pasaran/yate/tree/master/tests

16. jsonpath-object-transform Last Commit Jan 18, 2017

Pulls data from an object literal using JSONPath and generate a new objects based on a template.

17. Stapling Last Commit Sep 16, 2013

Stapling is a JavaScript library that enables XSLT formatting for JSON objects. Instead of using a JavaScript templating engine and text/html templates, Stapling gives you the opportunity to use XSLT templates - loaded asynchronously with Ajax and then cached client side - to parse your JSON datasources.

Specs:

JSON Pointer defines a string syntax for identifying a specific value within a JavaScript Object Notation (JSON) document.

JSONPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document

JSPath for JSON is like XPath for XML."

The main source of inspiration behind JSONiq is XQuery, which has been proven so far a successful and productive query language for semi-structured data

How to concatenate items in a list to a single string?

If you want to generate a string of strings separated by commas in final result, you can use something like this:

sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"

I hope this can help someone.

How can I restore the MySQL root user’s full privileges?

If the GRANT ALL doesn't work, try:

  1. Stop mysqld and restart it with the --skip-grant-tables option.
  2. Connect to the mysqld server with just: mysql (i.e. no -p option, and username may not be required).
  3. Issue the following commands in the mysql client:

    UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';

    FLUSH PRIVILEGES;

After that, you should be able to run GRANT ALL ON *.* TO 'root'@'localhost'; and have it work.

Youtube iframe wmode issue

Try adding ?wmode=transparent to the end of the URL. Worked for me.

Invoking a static method using reflection

Fromthe Javadoc of Method.invoke():

If the underlying method is static, then the specified obj argument is ignored. It may be null.

What happens when you

Class klass = ...;
Method m = klass.getDeclaredMethod(methodName, paramtypes);
m.invoke(null, args)

How do I combine 2 javascript variables into a string

warning! this does not work with links.

var variable = 'variable', another = 'another';

['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

How do I get the value of a registry key and ONLY the value using powershell

Well you need to be specific here. As far as I know, the key in a registry is a "folder" of properties. So did you mean get the value of a property? If so, try something like this:

(Get-ItemProperty HKLM:\Software\Microsoft\PowerShell\1\PowerShellEngine -Name PowerShellVersion).PowerShellVersion

First we get an object containing the property we need with Get-ItemProperty and then we get the value of for the property we need from that object. That will return the value of the property as a string. The example above gives you the PS version for "legacy"/compatibility-mdoe powershell (1.0 or 2.0).

How to use ScrollView in Android?

As said above you can put it inside a ScrollView... and if you want the Scroll View to be horizontal put it inside HorizontalScrollView... and if you want your component (or layout) to support both put inside both of them like this:

  <HorizontalScrollView>
        <ScrollView>
            <!-- SOME THING -->
        </ScrollView>
    </HorizontalScrollView>

and with setting the layout_width and layout_height ofcourse.

wget: unable to resolve host address `http'

I figured out what went wrong. In the proxy configuration of my box, an extra http:// got prefixed to "proxy server with http".

Example..

http://http://proxy.mycollege.com

and that has created problems. Corrected that, and it works perfectly.

Thanks @WhiteCoffee and @ChrisBint for your suggestions!

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Find unique rows in numpy.array

np.unique works given a list of tuples:

>>> np.unique([(1, 1), (2, 2), (3, 3), (4, 4), (2, 2)])
Out[9]: 
array([[1, 1],
       [2, 2],
       [3, 3],
       [4, 4]])

With a list of lists it raises a TypeError: unhashable type: 'list'

Copy array items into another array

If you want to modify the original array, you can spread and push:

var source = [1, 2, 3];
var range = [5, 6, 7];
var length = source.push(...range);

console.log(source); // [ 1, 2, 3, 5, 6, 7 ]
console.log(length); // 6

If you want to make sure only items of the same type go in the source array (not mixing numbers and strings for example), then use TypeScript.

/**
 * Adds the items of the specified range array to the end of the source array.
 * Use this function to make sure only items of the same type go in the source array.
 */
function addRange<T>(source: T[], range: T[]) {
    source.push(...range);
}

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

public static void main(String arg[])
{
    HashMap<String, ArrayList<String>> hashmap = 
        new HashMap<String, ArrayList<String>>();
    ArrayList<String> arraylist = new ArrayList<String>();
    arraylist.add("Hello");
    arraylist.add("World.");
    hashmap.put("my key", arraylist);
    arraylist = hashmap.get("not inserted");
    System.out.println(arraylist);
    arraylist = hashmap.get("my key");
    System.out.println(arraylist);
}

null
[Hello, World.]

Works fine... maybe you find your mistake in my code.

Centering controls within a form in .NET (Winforms)?

You could achieve this with the use of anchors. Or more precisely the non use of them.

Controls are anchored by default to the top left of the form which means when the form size will be changed, their distance from the top left side of the form will remain constant. If you change the control anchor to bottom left, then the control will keep the same distance from the bottom and left sides of the form when the form if resized.

Turning off the anchor in a direction will keep the control centered in that direction when resizing.

NOTE: Turning off anchoring via the properties window in VS2015 may require entering None, None (instead of default Top,Left)

How can I do DNS lookups in Python, including referring to /etc/hosts?

The normal name resolution in Python works fine. Why do you need DNSpython for that. Just use socket's getaddrinfo which follows the rules configured for your operating system (on Debian, it follows /etc/nsswitch.conf:

>>> print socket.getaddrinfo('google.com', 80)
[(10, 1, 6, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 1, 6, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 1, 6, '', ('2a00:1450:8006::93', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::93', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::93', 80, 0, 0)), (2, 1, 6, '', ('209.85.229.104', 80)), (2, 2, 17, '', ('209.85.229.104', 80)), (2, 3, 0, '', ('209.85.229.104', 80)), (2, 1, 6, '', ('209.85.229.99', 80)), (2, 2, 17, '', ('209.85.229.99', 80)), (2, 3, 0, '', ('209.85.229.99', 80)), (2, 1, 6, '', ('209.85.229.147', 80)), (2, 2, 17, '', ('209.85.229.147', 80)), (2, 3, 0, '', ('209.85.229.147', 80))]

How do I count a JavaScript object's attributes?

Although it wouldn't be a "true object", you could always do something like this:

var foo = [
  {Key1: "key1"},
  {Key2: "key2"},
  {Key3: "key3"}
];

alert(foo.length); // === 3

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

How do I execute a program from Python? os.system fails due to spaces in path

subprocess.call will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.

import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])

How can I count text lines inside an DOM element? Can I?

You should be able to split('\n').length and get the line breaks.

update: this works on FF/Chrome but not IE.

<html>
<head>
<script src="jquery-1.3.2.min.js"></script>
<script>
    $(document).ready(function() {
        var arr = $("div").text().split('\n');
        for (var i = 0; i < arr.length; i++)
            $("div").after(i + '=' + arr[i] + '<br/>');
    });
</script>
</head>
<body>
<div>One
Two
Three</div>
</body>
</html>

Command failed due to signal: Segmentation fault: 11

I got this error when I was trying to access a property of a singleton's struct instance from a 'static scope' within that singleton (that contains constants inside an enum that are never instantiated)

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

I got the same error after enabling TLSv1.2 in webmin. Right after I enabled TLSv1.2 by accident thinking it was SSLv2, I was not able to log in from https://myipaddress:10000 like I did before. I found this link http://smallbusiness.chron.com/disable-ssl-webmin-miniserv-60053.html and it helped me because I was able to access webmin config file and I was able TLSv1.2

How to create a checkbox with a clickable label?

<label for="vehicle">Type of Vehicle:</label>
<input type="checkbox" id="vehicle" name="vehicle" value="Bike" />

Looking for simple Java in-memory cache

Ehcache is a pretty good solution for this and has a way to peek (getQuiet() is the method) such that it doesn't update the idle timestamp. Internally, Ehcache is implemented with a set of maps, kind of like ConcurrentHashMap, so it has similar kinds of concurrency benefits.

Auto highlight text in a textbox control

On events "Enter" (for example: press Tab key) or "First Click" all text will be selected. dotNET 4.0

public static class TbHelper
{
    // Method for use
    public static void SelectAllTextOnEnter(TextBox Tb)
    {
        Tb.Enter += new EventHandler(Tb_Enter);
        Tb.Click += new EventHandler(Tb_Click);
    }

    private static TextBox LastTb;

    private static void Tb_Enter(object sender, EventArgs e)
    {
        var Tb = (TextBox)sender;
        Tb.SelectAll();
        LastTb = Tb;
    }

    private static void Tb_Click(object sender, EventArgs e)
    {
        var Tb = (TextBox)sender;
        if (LastTb == Tb)
        {
            Tb.SelectAll();
            LastTb = null;
        }
    }
}

Jenkins: Is there any way to cleanup Jenkins workspace?

You can run the below script in the Manage Jenkins ? Scripts Console for deleting the workspaces of all the jobs at one shot. We did this to clean up space on the file system.

import hudson.model.*
// For each project
for(item in Hudson.instance.items) {
  // check that job is not building
  if(!item.isBuilding()) {
    println("Wiping out workspace of job "+item.name)
    item.doDoWipeOutWorkspace()
  }
  else {
    println("Skipping job "+item.name+", currently building")
  }
}

How to align entire html body to the center?

http://bluerobot.com/web/css/center1.html

body {
    margin:50px 0; 
    padding:0;
    text-align:center;
}

#Content {
    width:500px;
    margin:0 auto;
    text-align:left;
    padding:15px;
    border:1px dashed #333;
    background-color:#eee;
}

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

Another potential cause:

I had this issue when I was accidentally presenting the same view controller twice. (Once with performSegueWithIdentifer:sender: which was called when the button was pressed, and a second time with a segue connected directly to the button).

Effectively, two segues were firing at the same time, and I got the error: Attempt to present X on Y whose view is not in the window hierarchy!

Where are include files stored - Ubuntu Linux, GCC

gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo" and #include <zap> will search on your system, I recommend:

$ touch a.c
$ gcc -v -E a.c
 ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"

This is one way to see the search lists for included files, including (if any) directories into which #include "..." will look but #include <...> won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ... here;-) on any system on which gcc runs properly.

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.

Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.

Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.

To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.

How do I flush the cin buffer?

The following should work:

cin.flush();

On some systems it's not available and then you can use:

cin.ignore(INT_MAX);

How to set recurring schedule for xlsm file using Windows Task Scheduler

Code below copied from -> Here

First off, you must save your work book as a macro enabled work book. So it would need to be xlsm not an xlsx. Otherwise, excel will disable the macro's due to not being macro enabled.

Set your vbscript (C:\excel\tester.vbs). The example sub "test()" must be located in your modules on the excel document.

dim eApp
set eApp = GetObject("C:\excel\tester.xlsm")
eApp.Application.Run "tester.xlsm!test"
set eApp = nothing

Then set your Schedule, give it a name, and a username/password for offline access.

Then you have to set your actions and triggers.

Set your schedule(trigger)

Set your trigger

Action, set your vbscript to open with Cscript.exe so that it will be executed in the background and not get hung up by any error handling that vbcript has enabled.

Action Properties

Stored procedure - return identity as output parameter or scalar

Another option would be as the return value for the stored procedure (I don't suggest this though, as that's usually best for error values).

I've included it as both when it's inserting a single row in cases where the stored procedure was being consumed by both other SQL procedures and a front-end which couldn't work with OUTPUT parameters (IBATIS in .NET I believe):

CREATE PROCEDURE My_Insert
    @col1            VARCHAR(20),
    @new_identity    INT    OUTPUT
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO My_Table (col1)
    VALUES (@col1)

    SELECT @new_identity = SCOPE_IDENTITY()

    SELECT @new_identity AS id

    RETURN
END

The output parameter is easier to work with in T-SQL when calling from other stored procedures IMO, but some programming languages have poor or no support for output parameters and work better with result sets.

Reading Datetime value From Excel sheet

Alternatively, if your cell is already a real date, just use .Value instead of .Value2:

excelApp.Range[namedRange].Value
{21/02/2013 00:00:00}
    Date: {21/02/2013 00:00:00}
    Day: 21
    DayOfWeek: Thursday
    DayOfYear: 52
    Hour: 0
    Kind: Unspecified
    Millisecond: 0
    Minute: 0
    Month: 2
    Second: 0
    Ticks: 634970016000000000
    TimeOfDay: {00:00:00}
    Year: 2013

excelApp.Range[namedRange].Value2
41326.0

Count number of rows within each group

If your trying the aggregate solutions above and you get the error:

invalid type (list) for variable

Because you're using date or datetime stamps, try using as.character on the variables:

aggregate(x ~ as.character(Year) + Month, data = df, FUN = length)

On one or both of the variables.

CSS, Images, JS not loading in IIS

You probably have Windows authentication enabled in your web.config. On a local machine, your Windows credentials are automatically passed and it works. On a live site, you are treated as an anonymous user (IE setting can control this, but don't modify this unless you really know what you are doing).

This causes the following:

  • You are required to explicitly login.
  • Resources like scripts and CSS are not served on the login page because you are not authenticated.

This isn't broken, just working as intended, but to "fix" this:

  • Change the authentication type in the web.config if you don't want any login.
  • And/or add a web.config in the directory(s) containing CSS, images, scripts, etc. which specifies authorization rules.

What is the reason for having '//' in Python?

In Python 3, they made the / operator do a floating-point division, and added the // operator to do integer division (i.e., quotient without remainder); whereas in Python 2, the / operator was simply integer division, unless one of the operands was already a floating point number.

In Python 2.X:

>>> 10/3
3
>>> # To get a floating point number from integer division:
>>> 10.0/3
3.3333333333333335
>>> float(10)/3
3.3333333333333335

In Python 3:

>>> 10/3
3.3333333333333335
>>> 10//3
3

For further reference, see PEP238.

How to print all session variables currently set?

<?php
    session_start();
    echo "<h3> PHP List All Session Variables</h3>";
    foreach ($_SESSION as $key=>$val)
    echo $key." ".$val."<br/>";
?>

Passing parameters to a JQuery function

If you want to do an ajax call or a simple javascript function, don't forget to close your function with the return false

like this:

function DoAction(id, name) 
{ 
    // your code
    return false;
}

Determining complexity for recursive functions (Big O notation)

One of the best ways I find for approximating the complexity of the recursive algorithm is drawing the recursion tree. Once you have the recursive tree:

Complexity = length of tree from root node to leaf node * number of leaf nodes
  1. The first function will have length of n and number of leaf node 1 so complexity will be n*1 = n
  2. The second function will have the length of n/5 and number of leaf nodes again 1 so complexity will be n/5 * 1 = n/5. It should be approximated to n

  3. For the third function, since n is being divided by 5 on every recursive call, length of recursive tree will be log(n)(base 5), and number of leaf nodes again 1 so complexity will be log(n)(base 5) * 1 = log(n)(base 5)

  4. For the fourth function since every node will have two child nodes, the number of leaf nodes will be equal to (2^n) and length of the recursive tree will be n so complexity will be (2^n) * n. But since n is insignificant in front of (2^n), it can be ignored and complexity can be only said to be (2^n).

  5. For the fifth function, there are two elements introducing the complexity. Complexity introduced by recursive nature of function and complexity introduced by for loop in each function. Doing the above calculation, the complexity introduced by recursive nature of function will be ~ n and complexity due to for loop n. Total complexity will be n*n.

Note: This is a quick and dirty way of calculating complexity(nothing official!). Would love to hear feedback on this. Thanks.

Eclipse - java.lang.ClassNotFoundException

Run project as Maven test, then Run as JUnit Test.

Apache: The requested URL / was not found on this server. Apache

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

How do you setLayoutParams() for an ImageView?

You need to set the LayoutParams of the ViewGroup the ImageView is sitting in. For example if your ImageView is inside a LinearLayout, then you create a

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

This is because it's the parent of the View that needs to know what size to allocate to the View.

Eclipse count lines of code

Another tool is Google Analytix, which will also allow you to run metrics even if you can`t build the project in case of errors

Showing which files have changed between two revisions

There is also a GUI based method.

You can use gitk.

  1. Run:

    $ gitk --all
    
  2. Right click on a commit of a branch and select Mark this commit in the pop-up menu.

  3. Right click on a commit of another branch and select Diff this -> marked commit or Diff marked commit -> this.

Then there will be a changed files list in the right bottom panel and diff details in the left bottom panel.

How do I disable right click on my web page?

Put this code into your <head> tag of your page.

<script type="text/javascript"> 
function disableselect(e){  
return false  
}  

function reEnable(){  
return true  
}  

//if IE4+  
document.onselectstart=new Function ("return false")  
document.oncontextmenu=new Function ("return false")  
//if NS6  
if (window.sidebar){  
document.onmousedown=disableselect  
document.onclick=reEnable  
}
</script>

This will disable right click on your whole web page, but only when JavaScript is enabled.

canvas.toDataURL() SecurityError

Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:

Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error.

This protects users from having private data exposed by using images to pull information from remote web sites without permission.

I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!

EDIT:

As this answer is still the accepted answer, you should check out @shadyshrif's answer, which is to use:

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

This will only work if you have the correct permissions, but will at least allow you to do what you want.

How to install popper.js with Bootstrap 4?

Bootstrap 4 has two dependencies: jQuery 1.9.1 and popper.js 1.12.3. When you install Bootstrap 4, you need to install these two dependencies.

For Bootstrap 4.1

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

Simplest of all solutions:

filtered_df = df[df['EPS'].notnull()]

The above solution is way better than using np.isfinite()

How to use the CSV MIME-type?

You are not specifying a language or framework, but the following header is used for file downloads:

"Content-Disposition: attachment; filename=abc.csv"

Remove all unused resources from an android project

When we define shrink resources true that time we can also define which resources we wanna keep and which don't I have added xml file in res/raw folder named keep.xml

before going further generate a single signed build and check in apk analyser tool which will show drawable-xhdpi-v4 has messenger_button_send_round_shadow.png which i want to remove for this test

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
       tools:shrinkMode="strict"
       tools:discard="@drawable/com_facebook_button_icon_blue.png,
       @drawable/com_facebook_button_icon_white.png,
       @drawable/com_facebook_button_like_icon_selected.png,
       @drawable/messenger_button_send_round_shadow.png,
       @drawable/messenger_*"  />

by doing messenger_* all files starting from name messenger in drawable folder will be removed or other way around is i have defines specific file to be removed

so that way you can remove files from library it self you can also remove layouts by @layout/layout name if that drawable has been used by layout and so....

PHP form - on submit stay on same page

You have to use code similar to this:

echo "<div id='divwithform'>";

if(isset($_POST['submit']))  // if form was submitted (if you came here with form data)
{
    echo "Success";
}
else                // if form was not submitted (if you came here without form data)
{
    echo "<form> ... </form>";
} 

echo "</div>";

Code with if like this is typical for many pages, however this is very simplified.

Normally, you have to validate some data in first "if" (check if form fields were not empty etc).

Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.

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

This is how I did a similar thing. I have tiles that are thumbnails to YouTube videos. When I click the tile, it redirects me to a 'player' page that uses the 'video_id' to render the correct video to the page.

<GridTile
  key={video_id}
  title={video_title}
  containerElement={<Link to={`/player/${video_id}`}/>}
 >

ETA: Sorry, just noticed that you didn't want to use the LINK or REDIRECT components for some reason. Maybe my answer will still help in some way. ; )

Error: Module not specified (IntelliJ IDEA)

This is because the className value which you are passing as argument for
forName(String className) method is not found or doesn't exists, or you a re passing the wrong value as the class name. Here is also a link which could help you.

1. https://docs.oracle.com/javase/7/docs/api/java/lang/ClassNotFoundException.html
2. https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)

Update

Module not specified

According to the snapshot you have provided this problem is because you have not determined the app module of your project, so I suggest you to choose the app module from configuration. For example:

enter image description here

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

Initialization of an ArrayList in one line

The simple answer

In Java 9 or later, after List.of() was added:

List<String> strings = List.of("foo", "bar", "baz");

With Java 10 or later, this can be shortened with the var keyword.

var strings = List.of("foo", "bar", "baz");

This will give you an immutable List, so it cannot be changed.
Which is what you want in most cases where you're prepopulating it.


Java 8 or earlier:

List<String> strings = Arrays.asList("foo", "bar", "baz");

This will give you a List backed by an array, so it cannot change length.
But you can call List.set, so it's still mutable.


You can make Arrays.asList even shorter with a static import:

List<String> strings = asList("foo", "bar", "baz");

The static import:

import static java.util.Arrays.asList;  

Which any modern IDE will suggest and automatically do for you.
For example in IntelliJ IDEA you press Alt+Enter and select Static import method....


However, i don't recommend shortening the List.of method to of, because that becomes confusing.
List.of is already short enough and reads well.


Using Streams

Why does it have to be a List?
With Java 8 or later you can use a Stream which is more flexible:

Stream<String> strings = Stream.of("foo", "bar", "baz");

You can concatenate Streams:

Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),
                                       Stream.of("baz", "qux"));

Or you can go from a Stream to a List:

import static java.util.stream.Collectors.toList;

List<String> strings = Stream.of("foo", "bar", "baz").collect(toList());

But preferably, just use the Stream without collecting it to a List.


If you really specifically need a java.util.ArrayList

(You probably don't.)
To quote JEP 269 (emphasis mine):

There is a small set of use cases for initializing a mutable collection instance with a predefined set of values. It's usually preferable to have those predefined values be in an immutable collection, and then to initialize the mutable collection via a copy constructor.


If you want to both prepopulate an ArrayList and add to it afterwards (why?), use

ArrayList<String> strings = new ArrayList<>(List.of("foo", "bar"));
strings.add("baz");

or in Java 8 or earlier:

ArrayList<String> strings = new ArrayList<>(asList("foo", "bar"));
strings.add("baz");

or using Stream:

import static java.util.stream.Collectors.toCollection;

ArrayList<String> strings = Stream.of("foo", "bar")
                             .collect(toCollection(ArrayList::new));
strings.add("baz");

But again, it's better to just use the Stream directly instead of collecting it to a List.


Program to interfaces, not to implementations

You said you've declared the list as an ArrayList in your code, but you should only do that if you're using some member of ArrayList that's not in List.

Which you are most likely not doing.

Usually you should just declare variables by the most general interface that you are going to use (e.g. Iterable, Collection, or List), and initialize them with the specific implementation (e.g. ArrayList, LinkedList or Arrays.asList()).

Otherwise you're limiting your code to that specific type, and it'll be harder to change when you want to.

For example, if you're passing an ArrayList to a void method(...):

// Iterable if you just need iteration, for (String s : strings):
void method(Iterable<String> strings) { 
    for (String s : strings) { ... } 
}

// Collection if you also need .size(), .isEmpty(), or .stream():
void method(Collection<String> strings) {
    if (!strings.isEmpty()) { strings.stream()... }
}

// List if you also need .get(index):
void method(List<String> strings) {
    strings.get(...)
}

// Don't declare a specific list implementation
// unless you're sure you need it:
void method(ArrayList<String> strings) {
    ??? // You don't want to limit yourself to just ArrayList
}

Another example would be always declaring variable an InputStream even though it is usually a FileInputStream or a BufferedInputStream, because one day soon you or somebody else will want to use some other kind of InputStream.

REST URI convention - Singular or plural name of resource while creating it

To me plurals manipulate the collection, whereas singulars manipulate the item inside that collection.

Collection allows the methods GET / POST / DELETE

Item allows the methods GET / PUT / DELETE

For example

POST on /students will add a new student in the school.

DELETE on /students will remove all the students in the school.

DELETE on /student/123 will remove student 123 from the school.

It might feel like unimportant but some engineers sometimes forget the id. If the route was always plural and performed a DELETE, you might accidentally wipe your data. Whereas missing the id on the singular will return a 404 route not found.

To further expand the example if the API was supposed to expose multiple schools, then something like

DELETE on /school/abc/students will remove all the students in the school abc.

Choosing the right word sometimes is a challenge on its own, but I like to maintain plurality for the collection. E.g. cart_items or cart/items feels right. In contrast deleting cart, deletes the cart object it self and not the items within the cart ;).

What does -XX:MaxPermSize do?

The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).

This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :

The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.

Note that this other Oracle documentation lists the other HotSpot arguments.

Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.

How do I find out my python path using python?

Python tells me where it lives when it gives me an error message :)

>>> import os
>>> os.environ['PYTHONPATH'].split(os.pathsep)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\martin\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'PYTHONPATH'
>>>

HTML5 required attribute seems not working

Yes, you missed the form encapsulation:

JSFiddle

<form>
   <input id="tbQuestion" type="text" placeholder="Post a question?" required/>
   <input id="btnSubmit" type="submit" />
</form>

How to check if JSON return is empty with jquery

$.getJSON(url,function(json){
if ( json.length == 0 ) 
{
console.log("NO !")
}
});

Android map v2 zoom to show all the markers

this would help.. from google apis demos

private List<Marker> markerList = new ArrayList<>();
Marker marker = mGoogleMap.addMarker(new MarkerOptions().position(geoLatLng)
                .title(title));
markerList.add(marker);
    // Pan to see all markers in view.
    // Cannot zoom to bounds until the map has a size.
    final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
    if (mapView!=null) {
        if (mapView.getViewTreeObserver().isAlive()) {
            mapView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @SuppressWarnings("deprecation") // We use the new method when supported
                @SuppressLint("NewApi") // We check which build version we are using.
                @Override
                public void onGlobalLayout() {
                    //Calculate the markers to get their position
                    LatLngBounds.Builder b = new LatLngBounds.Builder();
                    for (Marker m : markerList) {
                        b.include(m.getPosition());
                    }
                    // also include current location to include in the view
                    b.include(new LatLng(mLocation.getLatitude(),mLocation.getLongitude()));

                    LatLngBounds bounds = b.build();
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                        mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    } else {
                        mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
                }
            });
        }
    }

for clear info look at this url. https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MarkerDemoActivity.java

Media Queries: How to target desktop, tablet, and mobile?

The behavior does not change on desktop. But on tablets and mobiles, I expand the navbar to cover the big logo image. Note: Use the margin (top and bottom) as much as you need for your logo height.

For my case, 60px top and bottom worked perfectly!

@media (max-width:768px) { 
  .navbar-toggle {
      margin: 60px 0;
  }
}

Check the navbar here.

ld cannot find an existing library

Unless I'm badly mistaken libmagic or -lmagic is not the same library as ImageMagick. You state that you want ImageMagick.

ImageMagick comes with a utility to supply all appropriate options to the compiler.

Ex:

g++ program.cpp `Magick++-config --cppflags --cxxflags --ldflags --libs` -o "prog"

Excel VBA Open a Folder

If you want to open a windows file explorer, you should call explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

Equivalent syxntax

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

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

In addition to the accepted answer, I would like to add one info, that NuGet packages in Visual Studio 2017 are located in the project file itself. I.e., right click on the project -> edit, to find all package reference entries.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

I installed System.Configuration.ConfigurationManager from Nuget into my .net core 2.2 application.

I then reference using System.Configuration;

Next, I changed

WebConfigurationManager.AppSettings

to ..

ConfigurationManager.AppSettings

So far I believe this is correct. 4.5.0 is typical with .net core 2.2

I have not had any issues with this.

str_replace with array

Easy and better than str_replace:

<?php
$arr = array(
    "http://" => "http://www.",
    "w" => "W",
    "d" => "D");

    $word = "http://desiweb.ir";
    echo strtr($word,$arr);
?>

strtr PHP doc here

What is the difference between 'git pull' and 'git fetch'?

Bonus:

In speaking of pull & fetch in the above answers, I would like to share an interesting trick,

git pull --rebase

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

Before pushing your new commits to server, try this command and it will automatically sync latest server changes (with a fetch + merge) and will place your commit at the top in git log. No need to worry about manual pull/merge.

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

Read XML Attribute using XmlDocument

If your XML contains namespaces, then you can do the following in order to obtain the value of an attribute:

var xmlDoc = new XmlDocument();

// content is your XML as string
xmlDoc.LoadXml(content);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

// make sure the namespace identifier, URN in this case, matches what you have in your XML 
nsmgr.AddNamespace("ns", "urn:oasis:names:tc:SAML:2.0:protocol");

// get the value of Destination attribute from within the Response node with a prefix who's identifier is "urn:oasis:names:tc:SAML:2.0:protocol" using XPath
var str = xmlDoc.SelectSingleNode("/ns:Response/@Destination", nsmgr);
if (str != null)
{
    Console.WriteLine(str.Value);
}

More on XML namespaces here and here.

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

How to create an array from a CSV file using PHP and the fgetcsv function

I think the str_getcsv() syntax is much cleaner, it also doesn't require the CSV to be stored in the file system.

$csv = str_getcsv(file_get_contents('myCSVFile.csv'));

echo '<pre>';
print_r($csv);
echo '</pre>';

Or for a line by line solution:

$csv = array();
$lines = file('myCSVFile.csv', FILE_IGNORE_NEW_LINES);

foreach ($lines as $key => $value)
{
    $csv[$key] = str_getcsv($value);
}

echo '<pre>';
print_r($csv);
echo '</pre>';

Or for a line by line solution with no str_getcsv():

$csv = array();
$file = fopen('myCSVFile.csv', 'r');

while (($result = fgetcsv($file)) !== false)
{
    $csv[] = $result;
}

fclose($file);

echo '<pre>';
print_r($csv);
echo '</pre>';

Replace one character with another in Bash

In bash, you can do pattern replacement in a string with the ${VARIABLE//PATTERN/REPLACEMENT} construct. Use just / and not // to replace only the first occurrence. The pattern is a wildcard pattern, like file globs.

string='foo bar qux'
one="${string/ /.}"     # sets one to 'foo.bar qux'
all="${string// /.}"    # sets all to 'foo.bar.qux'

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Setting focus on an HTML input box on page load

This is one of the common issues with IE and fix for this is simple. Add .focus() twice to the input.

Fix :-

function FocusOnInput() {
    var element = document.getElementById('txtContactMobileNo');
    element.focus();
    setTimeout(function () { element.focus(); }, 1);
}

And call FocusOnInput() on $(document).ready(function () {.....};

Get unicode value of a character

If you have Java 5, use char c = ...; String s = String.format ("\\u%04x", (int)c);

If your source isn't a Unicode character (char) but a String, you must use charAt(index) to get the Unicode character at position index.

Don't use codePointAt(index) because that will return 24bit values (full Unicode) which can't be represented with just 4 hex digits (it needs 6). See the docs for an explanation.

[EDIT] To make it clear: This answer doesn't use Unicode but the method which Java uses to represent Unicode characters (i.e. surrogate pairs) since char is 16bit and Unicode is 24bit. The question should be: "How can I convert char to a 4-digit hex number", since it's not (really) about Unicode.

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

Make sure you've set your target API (different from the target SDK) in the Project Properties (not the manifest) to be at least 4.0/API 14.

How to access ssis package variables inside script component

Strongly typed var don't seem to be available, I have to do the following in order to get access to them:

String MyVar = Dts.Variables["MyVarName"].Value.ToString();

Using Gulp to Concatenate and Uglify files

Jun 10 2015: Note from the author of gulp-uglifyjs:

DEPRECATED: This plugin has been blacklisted as it relies on Uglify to concat the files instead of using gulp-concat, which breaks the "It should do one thing" paradigm. When I created this plugin, there was no way to get source maps to work with gulp, however now there is a gulp-sourcemaps plugin that achieves the same goal. gulp-uglifyjs still works great and gives very granular control over the Uglify execution, I'm just giving you a heads up that other options now exist.


Feb 18 2015: gulp-uglify and gulp-concat both work nicely with gulp-sourcemaps now. Just make sure to set the newLine option correctly for gulp-concat; I recommend \n;.


Original Answer (Dec 2014): Use gulp-uglifyjs instead. gulp-concat isn't necessarily safe; it needs to handle trailing semi-colons correctly. gulp-uglify also doesn't support source maps. Here's a snippet from a project I'm working on:

gulp.task('scripts', function () {
    gulp.src(scripts)
        .pipe(plumber())
        .pipe(uglify('all_the_things.js',{
            output: {
                beautify: false
            },
            outSourceMap: true,
            basePath: 'www',
            sourceRoot: '/'
        }))
        .pipe(plumber.stop())
        .pipe(gulp.dest('www/js'))
});

CASE statement in SQLite query

Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END

Setting the Vim background colors

As vim's own help on set background says, "Setting this option does not change the background color, it tells Vim what the background color looks like. For changing the background color, see |:hi-normal|."

For example

:highlight Normal ctermfg=grey ctermbg=darkblue

will write in white on blue on your color terminal.

Why can't I find SQL Server Management Studio after installation?

Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.

It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\

Set value of textarea in jQuery

In my condition i had this input in iframe, any of the above resolve my problem but this :

I just solve it like in this way :

$('#myId')[0].value="MY VALUE";

My input field :

<textarea name="cmyInput" rows="2" cols="20" id="myId" class="nd" ignoreautotab="1"></textarea>

WPF What is the correct way of using SVG files as icons in WPF

Your technique will depend on what XAML object your SVG to XAML converter produces. Does it produce a Drawing? An Image? A Grid? A Canvas? A Path? A Geometry? In each case your technique will be different.

In the examples below I will assume you are using your icon on a button, which is the most common scenario, but note that the same techniques will work for any ContentControl.

Using a Drawing as an icon

To use a Drawing, paint an approriately-sized rectangle with a DrawingBrush:

<Button>
  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <DrawingBrush>
        <DrawingBrush.Drawing>

          <Drawing ... /> <!-- Converted from SVG -->

        </DrawingBrush.Drawing>
      </DrawingBrush>
    </Rectangle.Fill>
  </Rectangle>
</Button>

Using an Image as an icon

An image can be used directly:

<Button>
  <Image ... />  <!-- Converted from SVG -->
</Button>

Using a Grid as an icon

A grid can be used directly:

<Button>
  <Grid ... />  <!-- Converted from SVG -->
</Button>

Or you can include it in a Viewbox if you need to control the size:

<Button>
  <Viewbox ...>
    <Grid ... />  <!-- Converted from SVG -->
  </Viewbox>
</Button>

Using a Canvas as an icon

This is like using an image or grid, but since a canvas has no fixed size you need to specify the height and width (unless these are already set by the SVG converter):

<Button>
  <Canvas Height="100" Width="100">  <!-- Converted from SVG, with additions -->
  </Canvas>
</Button>

Using a Path as an icon

You can use a Path, but you must set the stroke or fill explicitly:

<Button>
  <Path Stroke="Red" Data="..." /> <!-- Converted from SVG, with additions -->
</Button>

or

<Button>
  <Path Fill="Blue" Data="..." /> <!-- Converted from SVG, with additions -->
</Button>

Using a Geometry as an icon

You can use a Path to draw your geometry. If it should be stroked, set the Stroke:

<Button>
  <Path Stroke="Red" Width="100" Height="100">
    <Path.Data>
      <Geometry ... /> <!-- Converted from SVG -->
    </Path.Data>
  </Path>
</Button>

or if it should be filled, set the Fill:

<Button>
  <Path Fill="Blue" Width="100" Height="100">
    <Path.Data>
      <Geometry ... /> <!-- Converted from SVG -->
    </Path.Data>
  </Path>
</Button>

How to data bind

If you're doing the SVG -> XAML conversion in code and want the resulting XAML to appear using data binding, use one of the following:

Binding a Drawing:

<Button>
  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <DrawingBrush Drawing="{Binding Drawing, Source={StaticResource ...}}" />
    </Rectangle.Fill>
  </Rectangle>
</Button>

Binding an Image:

<Button Content="{Binding Image}" />

Binding a Grid:

<Button Content="{Binding Grid}" />

Binding a Grid in a Viewbox:

<Button>
  <Viewbox ...>
    <ContentPresenter Content="{Binding Grid}" />
  </Viewbox>
</Button>

Binding a Canvas:

<Button>
  <ContentPresenter Height="100" Width="100" Content="{Binding Canvas}" />
</Button>

Binding a Path:

<Button Content="{Binding Path}" />  <!-- Fill or stroke must be set in code unless set by the SVG converter -->

Binding a Geometry:

<Button>
  <Path Width="100" Height="100" Data="{Binding Geometry}" />
</Button>

Node.js: socket.io close client connection

socket.disconnect() is a synonym to socket.close() which disconnect the socket manually.

When you type in client side :

const socket = io('http://localhost');

this will open a connection with autoConnect: true , so the lib will try to reconnect again when you disconnect the socket from server, to disable the autoConnection:

const socket = io('http://localhost', {autoConnect: false});
socket.open();// synonym to socket.connect()

And if you want you can manually reconnect:

socket.on('disconnect', () => {
  socket.open();
});

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

Finding sum of elements in Swift array

For me, it was like this using property

    let blueKills = match.blueTeam.participants.reduce(0, { (result, participant) -> Int in
        result + participant.kills
    })

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

MySQL LEFT JOIN 3 tables

SELECT p.*, f.Fear
FROM Persons p
LEFT JOIN Person_Fear pf ON pf.PersonID = p.PersonID
LEFT JOIN Fears f ON f.FearID = pf.FearID
ORDER BY p.PersonID

  1. You need to select from the Persons table to ensure you generate a row for every person, whether they have fears or not.
  2. Then you can left join Person_Fear to every person, which will just be NULL if they don't have any entries (as you want).
  3. Finally, you left join Fears on Person_Fear so that you can select the name of the fear.
  4. Optionally, add an order so that each person has all their fears listed together, even if they were added to the Person_Fear table at different times.

PHP 5 disable strict standards error

For no errors.

error_reporting(0);

or for just not strict

error_reporting(E_ALL ^ E_STRICT);

and if you ever want to display all errors again, use

error_reporting(-1);

How to make a Java Generic method static?

You need to move type parameter to the method level to indicate that you have a generic method rather than generic class:

public class ArrayUtils {
    public static <T> E[] appendToArray(E[] array, E item) {
        E[] result = (E[])new Object[array.length+1];
        result[array.length] = item;
        return result;
    }
}

Replace non ASCII character from string

[Updated solution]

can be used with "Normalize" (Canonical decomposition) and "replaceAll", to replace it with the appropriate characters.

import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Pattern;

public final class NormalizeUtils {

    public static String normalizeASCII(final String string) {
        final String normalize = Normalizer.normalize(string, Form.NFD);

        return Pattern.compile("\\p{InCombiningDiacriticalMarks}+")
                      .matcher(normalize)
                      .replaceAll("");
    } ...

Is there any way to call a function periodically in JavaScript?

function test() {
 alert('called!');
}
var id = setInterval('test();', 10000); //call test every 10 seconds.
function stop() { // call this to stop your interval.
   clearInterval(id);
}

Bootstrap 3.0: How to have text and input on same line?

Or you can do this:

<table>
  <tr>
    <td><b>Return:</b></td>
    <td><input id="return1" name='return1' 
              class=" input input-sm" style="width:150px"
              type="text" value='8/28/2013'></td>
  </tr>
</table>

I tried every one of the suggestions above and none of them worked. I don't want to pick a fixed number of columns in the 12 column grid. I want the prompt, and the input right after it, and I want the columns to stretch as needed.

Yes, I know, that is against what bootstrap is all about. And you should NEVER use a table. Because DIV is so much better than tables. But the problem is that tables, rows, and cells actually WORK.

YES - I REALLY DO know that there are CSS zealots, and the knee-jerk reaction is never never never use TABLE, TR, and TD. Yes, I do know that DIV class="table" with DIV class="row" and DIV class="cell" is much much better. Except when it doesn't work, and there are many cases. I don't believe that people should blindly ignore those situations. There are times that the TABLE/TR/TD will work just fine, and there is not reason to use a more complicated and more fragile approach just because it is considered more elegant. A developer should understand what the benefits of the various approaches are, and the tradeoffs, and there is no absolute rule that DIVs are better.

"Case in point - based on this discussion I converted a few existing tds and trs to divs. 45 minutes messing about with it trying to get everything to line up next to each other and I gave up. TDs back in 10 seconds later - works - straight away - on all browsers, nothing more to do. Please try to make me understand - what possible justification do you have for wanting me to do it any other way!" See [https://stackoverflow.com/a/4278073/1758051]

And this: "

Layout should be easy. The fact that there are articles written on how to achieve a dynamic three column layout with header and footer in CSS shows that it is a poor layout system. Of course you can get it to work, but there are literally hundreds of articles online about how to do it. There are pretty much no such articles for a similar layout with tables because it's patently obvious. No matter what you say against tables and in favor of CSS, this one fact undoes it all: a basic three column layout in CSS is often called "The Holy Grail"." [https://stackoverflow.com/a/4964107/1758051]

I have yet to see a way to force DIVs to always line up in a column in all situations. I keep getting shown trivial examples that don't really run into the problems. "Responsive" is about providing a way that they will not always line up in a column. However, if you really want a column, you can waste hours trying to get DIV to work. Sometimes, you need to use appropriate technology no matter what the zealots say.

Commenting out code blocks in Atom

According to this, cmd + / should do it.

And for Windows and Linux, it is ctrl + /.

How to get < span > value?

You can use querySelectorAll to get all span elements and then use new ES2015 (ES6) spread operator convert StaticNodeList that querySelectorAll returns to array of spans, and then use map operator to get list of items.

See example bellow

_x000D_
_x000D_
([...document.querySelectorAll('#test span')]).map(x => console.log(x.innerHTML))
_x000D_
<div id="test">_x000D_
    <span>1</span>_x000D_
    <span>2</span>_x000D_
    <span>3</span>_x000D_
    <span>4</span>_x000D_
<div>
_x000D_
_x000D_
_x000D_

Serializing a list to JSON

public static string JSONSerialize<T>(T obj)
        {
            string retVal = String.Empty;
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(ms, obj);
                var byteArray = ms.ToArray();
                retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
            }
            return retVal;
        }

SQL Server: Cannot insert an explicit value into a timestamp column

create table demo ( id int, ts timestamp )

insert into demo(id,ts) values (1, DEFAULT)

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

This exception because of when you call session.getEntityById(), the session will be closed. So you need to re-attach the entity to the session. Or Easy solution is just configure default-lazy="false" to your entity.hbm.xml or if you are using annotations just add @Proxy(lazy=false) to your entity class.

Removing black dots from li and ul

Relatable post

Those pesky black dots you are referencing to are called bullets.

They are pretty simple to remove, just add this line to your css:

ul {
    list-style-type: none;
}

Hope this helps

A general tree implementation?

A tree in Python is quite simple. Make a class that has data and a list of children. Each child is an instance of the same class. This is a general n-nary tree.

class Node(object):
    def __init__(self, data):
        self.data = data
        self.children = []

    def add_child(self, obj):
        self.children.append(obj)

Then interact:

>>> n = Node(5)
>>> p = Node(6)
>>> q = Node(7)
>>> n.add_child(p)
>>> n.add_child(q)
>>> n.children
[<__main__.Node object at 0x02877FF0>, <__main__.Node object at 0x02877F90>]
>>> for c in n.children:
...   print c.data
... 
6
7
>>> 

This is a very basic skeleton, not abstracted or anything. The actual code will depend on your specific needs - I'm just trying to show that this is very simple in Python.

Manually adding a Userscript to Google Chrome

Update 2016: seems to be working again.

Update August 2014: No longer works as of recent Chrome versions.


Yeah, the new state of affairs sucks. Fortunately it's not so hard as the other answers imply.

  1. Browse in Chrome to chrome://extensions
  2. Drag the .user.js file into that page.

Voila. You can also drag files from the downloads footer bar to the extensions tab.

Chrome will automatically create a manifest.json file in the extensions directory that Brock documented.

<3 Freedom.

How do I set up cron to run a file just once at a specific time?

For those who is not able to access/install at in environment, can use custom script:

#!/bin/bash
if [ $# -lt 2 ]; then
echo ""
echo "Syntax Error!"
echo "Usage: $0 <shell script> <datetime>"
echo "<datetime> format: %Y%m%d%H%M"
echo "Example: $0 /home/user/scripts/server_backup.sh 202008142350"
echo ""
exit 1
fi

while true; do
  t=$(date +%Y%m%d%H%M);      
  if [ $t -eq $2 ]; then
    /bin/bash $1
    echo DONE $(date);
    break;
  fi;
  sleep 1;
done

Let's name the script as run1time.sh Example could be something like:

nohup bash run1time.sh /path/to/your/script.sh 202008150300 &