Programs & Examples On #Prefix operator

A prefix operator immediately precedes its operand, as in −x.

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

The most important rationale for avoiding ++ or -- is that the operators return values and cause side effects at the same time, making it harder to reason about the code.

For efficiency's sake, I prefer:

  • ++i when not using the return value (no temporary)
  • i++ when using the return value (no pipeline stall)

I am a fan of Mr. Crockford, but in this case I have to disagree. ++i is 25% less text to parse than i+=1 and arguably clearer.

What is the difference between prefix and postfix operators?

There is a big difference between postfix and prefix versions of ++.

In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i.

In the postfix version (i.e., i++), the value of i is incremented, but the value of the expression is the original value of i.

Let's analyze the following code line by line:

int i = 10;   // (1)
int j = ++i;  // (2)
int k = i++;  // (3)
  1. i is set to 10 (easy).
  2. Two things on this line:
    • i is incremented to 11.
    • The new value of i is copied into j. So j now equals 11.
  3. Two things on this line as well:
    • i is incremented to 12.
    • The original value of i (which is 11) is copied into k. So k now equals 11.

So after running the code, i will be 12 but both j and k will be 11.

The same stuff holds for postfix and prefix versions of --.

How to pass arguments to entrypoint in docker-compose.yml

You can use docker-compose run instead of docker-compose up and tack the arguments on the end. For example:

docker-compose run dperson/samba arg1 arg2 arg3

If you need to connect to other docker containers, use can use --service-ports option:

docker-compose run --service-ports dperson/samba arg1 arg2 arg3

How to stop default link click behavior with jQuery

You want e.preventDefault() to prevent the default functionality from occurring.

Or have return false from your method.

preventDefault prevents the default functionality and stopPropagation prevents the event from bubbling up to container elements.

Is it possible to open a Windows Explorer window from PowerShell?

This is the only thing that fit my unique constraints of wanting the folder to open as a Quizo Tab in any existing Explorer window.

$objShell = New-Object -ComObject "Shell.Application"
$objShell.Explore("path")

Opacity CSS not working in IE8

Using display: inline-block; works on IE8 to resolve this problem.

FWIW, opacity: 0.75 works on all standards-compliant browsers.

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

You have mentioned "user" twice in your FROM clause. You must provide a table alias to at least one mention so each mention of user. can be pinned to one or the other instance:

FROM article INNER JOIN section
ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user **AS user1** ON article.author\_id = **user1**.id
LEFT JOIN user **AS user2** ON article.modified\_by = **user2**.id
WHERE article.id = '1'

(You may need something different - I guessed which user is which, but the SQL engine won't guess.)

Also, maybe you only needed one "user". Who knows?

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

How to move files from one git repo to another (not a clone), preserving history

If the paths for the files in question are the same in the two repos and you're wanting to bring over just one file or a small set of related files, one easy way to do this is to use git cherry-pick.

The first step is to bring the commits from the other repo into your own local repo using git fetch <remote-url>. This will leave FETCH_HEAD pointing to the head commit from the other repo; if you want to preserve a reference to that commit after you've done other fetches you may want to tag it with git tag other-head FETCH_HEAD.

You will then need to create an initial commit for that file (if it doesn't exist) or a commit to bring the file to a state that can be patched with the first commit from the other repo you want to bring in. You may be able to do this with a git cherry-pick <commit-0> if commit-0 introduced the files you want, or you may need to construct the commit 'by hand'. Add -n to the cherry-pick options if you need to modify the initial commit to, e.g., drop files from that commit you don't want to bring in.

After that, you can continue to git cherry-pick subsequent commits, again using -n where necessary. In the simplest case (all commits are exactly what you want and apply cleanly) you can give the full list of commits on the cherry-pick command line: git cherry-pick <commit-1> <commit-2> <commit-3> ....

Python Iterate Dictionary by Index

I wanted to know (idx, key, value) for a python OrderedDict today (mapping of SKUs to quantities in order of the way they should appear on a receipt). The answers here were all bummers.

In python 3, at least, this way works and and makes sense.

In [1]: from collections import OrderedDict
   ...: od = OrderedDict()
   ...: od['a']='spam'
   ...: od['b']='ham'
   ...: od['c']='eggs'
   ...: 
   ...: for i,(k,v) in enumerate(od.items()):
   ...:    print('%d,%s,%s'%(i,k,v))
   ...: 
0,a,spam
1,b,ham
2,c,eggs

How to make the Facebook Like Box responsive?

The answer you're looking for as of June, 2013 can be found here:

https://gist.github.com/dineshcooper/2111366

It's accomplished using jQuery to rewrite the inner HTML of the parent container that holds the facebook widget.

Hope this helps!

How to Remove Array Element and Then Re-Index Array?

2020 Benchmark in PHP 7.4

For these who are not satisfied with current answers, I did a little benchmark script, anyone can run from CLI.

We are going to compare two solutions:

unset() with array_values() VS array_splice().

<?php

echo 'php v' . phpversion() . "\n";

$itemsOne = [];
$itemsTwo = [];

// populate items array with 100k random strings
for ($i = 0; $i < 100000; $i++) {
    $itemsOne[] = $itemsTwo[] = sha1(uniqid(true));
}

$start = microtime(true);

for ($i = 0; $i < 10000; $i++) {
    unset($itemsOne[$i]);
    $itemsOne = array_values($itemsOne);
}

$end = microtime(true);

echo 'unset & array_values: ' . ($end - $start) . 's' . "\n";

$start = microtime(true);

for ($i = 0; $i < 10000; $i++) {
    array_splice($itemsTwo, $i, 1);
}

$end = microtime(true);

echo 'array_splice: ' . ($end - $start) . 's' . "\n"; 

As you can see the idea is simple:

  • Create two arrays both with the same 100k items (randomly generated strings)
  • Remove 10k first items from first array using unset() and array_values() to reindex
  • Remove 10k first items from second array using array_splice()
  • Measure time for both methods

Output of the script above on my Dell Latitude i7-6600U 2.60GHz x 4 and 15.5GiB RAM:

php v7.4.8
unset & array_values: 29.089932918549s
array_splice: 17.94264793396s

Verdict: array_splice is almost twice more performant than unset and array_values.

So: array_splice is the winner!

Using "Object.create" instead of "new"

Sometimes you cannot create an object with NEW but are still able to invoke the CREATE method.

For example: if you want to define a Custom Element it must derive from HTMLElement.

proto = new HTMLElement  //fail :(
proto = Object.create( HTMLElement.prototype )  //OK :)
document.registerElement( "custom-element", { prototype: proto } )

jQuery OR Selector?

Using a comma may not be sufficient if you have multiple jQuery objects that need to be joined.

The .add() method adds the selected elements to the result set:

// classA OR classB
jQuery('.classA').add('.classB');

It's more verbose than '.classA, .classB', but lets you build more complex selectors like the following:

// (classA which has <p> descendant) OR (<div> ancestors of classB)
jQuery('.classA').has('p').add(jQuery('.classB').parents('div'));

What is console.log?

Beware: leaving calls to console in your production code will cause your site to break in Internet Explorer. Never keep it unwrapped. See: https://web.archive.org/web/20150908041020/blog.patspam.com/2009/the-curse-of-consolelog

Which is the fastest algorithm to find prime numbers?

u can try this code, fastest way to get prime with the less loop posible a number like 1000 will get less than 15 loops

def divisors(integer):
    result = []
    i = 2
    j = integer/2
    while(i <= j):
        if integer % i == 0:
            result.append(i)
            if i != integer//i:
                result.append(integer//i)
        i += 1
        j = integer//i
    if len(result) > 0:
        return sorted(result)
    else:
        return f"{integer} is prime"


print(divisors(1827))
print(divisors(1025))
print(divisors(27))

MySQL SELECT last few days?

You can use this in your MySQL WHERE clause to return records that were created within the last 7 days/week:

created >= DATE_SUB(CURDATE(),INTERVAL 7 day)

Also use NOW() in the subtraction to give hh:mm:ss resolution. So to return records created exactly (to the second) within the last 24hrs, you could do:

created >= DATE_SUB(NOW(),INTERVAL 1 day)

MVVM: Tutorial from start to finish?

Reed Copsey published a nice tutorial that writes a trivial RSS app in WinForms, then makes a straight port to WPF, and finally converts to MVVM. It makes a nice introduction to MVVM before you try and tackle a full description like Josh Smith's article. I'm glad that I read Reed's tutorial before Josh's article, because it gives me a little context to understand the details that Josh is digging into.

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

A method to reverse effect of java String.split()?

There has been an open feature request since at least 2009. The long and short of it is that it will part of the functionality of JDK 8's java.util.StringJoiner class. http://download.java.net/lambda/b81/docs/api/java/util/StringJoiner.html

Here is the Oracle issue if you are interested. http://bugs.sun.com/view_bug.do?bug_id=5015163

Here is an example of the new JDK 8 StringJoiner on an array of String

String[] a = new String[]{"first","second","third"};
StringJoiner sj = new StringJoiner(",");
for(String s:a) sj.add(s);
System.out.println(sj); //first,second,third

A utility method in String makes this even simpler:

String s = String.join(",", stringArray);

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Found this on a different forum

If you're wondering why that leading zero is important, it's because permissions are set as an octal integer, and Python automagically treats any integer with a leading zero as octal. So os.chmod("file", 484) (in decimal) would give the same result.

What you are doing is passing 664 which in octal is 1230

In your case you would need

os.chmod("/tmp/test_file", 436)

[Update] Note, for Python 3 you have prefix with 0o (zero oh). E.G, 0o666

Easily measure elapsed time

They are they same because your doSomething function happens faster than the granularity of the timer. Try:

printf ("**MyProgram::before time= %ld\n", time(NULL));

for(i = 0; i < 1000; ++i) {
    doSomthing();
    doSomthingLong();
}

printf ("**MyProgram::after time= %ld\n", time(NULL));

How to declare a Fixed length Array in TypeScript

The Tuple approach :

This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.

Syntax example :

// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]> 

This is the safest approach, considering it prevents accessing indexes out of the boundaries.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
  Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
  & { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }

Tests :

var myFixedLengthArray: FixedLengthArray< [string, string, string]>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? INVALID INDEX ERROR

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR

(*) This solution requires the noImplicitAny typescript configuration directive to be enabled in order to work (commonly recommended practice)


The Array(ish) approach :

This solution behaves as an augmentation of the Array type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.

Syntax example :

let foo: FixedLengthArray<string, 3> 

Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' |  'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
  Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
  & {
    readonly length: L 
    [ I : number ] : T
    [Symbol.iterator]: () => IterableIterator<T>   
  }

Tests :

var myFixedLengthArray: FixedLengthArray<string,3>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? SHOULD FAIL

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL

Right HTTP status code to wrong input

We had the same problem when making our API as well. We were looking for an HTTP status code equivalent to an InvalidArgumentException. After reading the source article below, we ended up using 422 Unprocessable Entity which states:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

source: https://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm

Vertically align text next to an image?

On a button in jQuery mobile, for instance, you can tweak it a bit by applying this style to the image:

.btn-image {
    vertical-align:middle;
    margin:0 0 3px 0;
}

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

Shortest way to check for null and assign another value if not

My guess is the best you can come up with is

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
                                                      : planRec.approved_by.ToString();

Of course since you're hinting at the fact that approved_by is an object (which cannot equal ""), this would be rewritten as

this.approved_by = (planRec.approved_by ?? string.Empty).ToString();

Switch case with conditions

You should not use switch for this scenario. This is the proper approach:

var cnt = $("#div1 p").length;

alert(cnt);

if (cnt >= 10 && cnt <= 20)
{
   alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
   alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
   alert('31');
}
else 
{
   alert('>41');
}

Text not wrapping in p tag

Adding width: 100%; to the offending p element solved the problem for me. I don't know why it works.

How to center align the cells of a UICollectionView?

Here is my solution with a few assumptions:

  • there is only one section
  • left and right insets are equal
  • cell height is the same

Feel free to adjust to meet your needs.

Centered layout with variable cell width:

protocol HACenteredLayoutDelegate: UICollectionViewDataSource {
    func getCollectionView() -> UICollectionView
    func sizeOfCell(at index: IndexPath) -> CGSize
    func contentInsets() -> UIEdgeInsets
}

class HACenteredLayout: UICollectionViewFlowLayout {
    weak var delegate: HACenteredLayoutDelegate?
    private var cache = [UICollectionViewLayoutAttributes]()
    private var contentSize = CGSize.zero
    override var collectionViewContentSize: CGSize { return self.contentSize }

    required init(delegate: HACenteredLayoutDelegate) {
        self.delegate = delegate
        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func invalidateLayout() {
        cache.removeAll()
        super.invalidateLayout()
    }

    override func prepare() {
        if cache.isEmpty && self.delegate != nil && self.delegate!.collectionView(self.delegate!.getCollectionView(), numberOfItemsInSection: 0) > 0 {
            let insets = self.delegate?.contentInsets() ?? UIEdgeInsets.zero
            var rows: [(width: CGFloat, count: Int)] = [(0, 0)]
            let viewWidth: CGFloat = UIScreen.main.bounds.width
            var y = insets.top
            var unmodifiedIndexes = [IndexPath]()
            for itemNumber in 0 ..< self.delegate!.collectionView(self.delegate!.getCollectionView(), numberOfItemsInSection: 0) {
                let indexPath = IndexPath(item: itemNumber, section: 0)
                let cellSize = self.delegate!.sizeOfCell(at: indexPath)
                let potentialRowWidth = rows.last!.width + (rows.last!.count > 0 ? self.minimumInteritemSpacing : 0) + cellSize.width + insets.right + insets.left
                if potentialRowWidth > viewWidth {
                    let leftOverSpace = max((viewWidth - rows[rows.count - 1].width)/2, insets.left)
                    for i in unmodifiedIndexes {
                        self.cache[i.item].frame.origin.x += leftOverSpace
                    }
                    unmodifiedIndexes = []
                    rows.append((0, 0))
                    y += cellSize.height + self.minimumLineSpacing
                }
                unmodifiedIndexes.append(indexPath)
                let attribute = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                rows[rows.count - 1].count += 1
                rows[rows.count - 1].width += rows[rows.count - 1].count > 1 ? self.minimumInteritemSpacing : 0
                attribute.frame = CGRect(x: rows[rows.count - 1].width, y: y, width: cellSize.width, height: cellSize.height)
                rows[rows.count - 1].width += cellSize.width
                cache.append(attribute)
            }
            let leftOverSpace = max((viewWidth - rows[rows.count - 1].width)/2, insets.left)
            for i in unmodifiedIndexes {
                self.cache[i.item].frame.origin.x += leftOverSpace
            }
            self.contentSize = CGSize(width: viewWidth, height: y + self.delegate!.sizeOfCell(at: IndexPath(item: 0, section: 0)).height + insets.bottom)
        }
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var layoutAttributes = [UICollectionViewLayoutAttributes]()

        for attributes in cache {
            if attributes.frame.intersects(rect) {
                layoutAttributes.append(attributes)
            }
        }
        return layoutAttributes
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        if indexPath.item < self.cache.count {
            return self.cache[indexPath.item]
        }
        return nil
    }
}

Result:

enter image description here

Is it better to return null or empty collection?

Empty collection. Always.

This sucks:

if(myInstance.CollectionProperty != null)
{
  foreach(var item in myInstance.CollectionProperty)
    /* arrgh */
}

It is considered a best practice to NEVER return null when returning a collection or enumerable. ALWAYS return an empty enumerable/collection. It prevents the aforementioned nonsense, and prevents your car getting egged by co-workers and users of your classes.

When talking about properties, always set your property once and forget it

public List<Foo> Foos {public get; private set;}

public Bar() { Foos = new List<Foo>(); }

In .NET 4.6.1, you can condense this quite a lot:

public List<Foo> Foos { get; } = new List<Foo>();

When talking about methods that return enumerables, you can easily return an empty enumerable instead of null...

public IEnumerable<Foo> GetMyFoos()
{
  return InnerGetFoos() ?? Enumerable.Empty<Foo>();
}

Using Enumerable.Empty<T>() can be seen as more efficient than returning, for example, a new empty collection or array.

Dynamically access object property using variable

You should use JSON.parse, take a look at https://www.w3schools.com/js/js_json_parse.asp

const obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}')
console.log(obj.name)
console.log(obj.age)

Time complexity of accessing a Python dict

See Time Complexity. The python dict is a hashmap, its worst case is therefore O(n) if the hash function is bad and results in a lot of collisions. However that is a very rare case where every item added has the same hash and so is added to the same chain which for a major Python implementation would be extremely unlikely. The average time complexity is of course O(1).

The best method would be to check and take a look at the hashs of the objects you are using. The CPython Dict uses int PyObject_Hash (PyObject *o) which is the equivalent of hash(o).

After a quick check, I have not yet managed to find two tuples that hash to the same value, which would indicate that the lookup is O(1)

l = []
for x in range(0, 50):
    for y in range(0, 50):
        if hash((x,y)) in l:
            print "Fail: ", (x,y)
        l.append(hash((x,y)))
print "Test Finished"

CodePad (Available for 24 hours)

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

IE works with iframe like all the other browsers (at least for main functions). You just have to keep a set of rules:

  • before you load any javascript in the iframe (that part of js which needs to know about the iframe parent), ensure that the parent has document.domain changed.
  • when all iframe resources are loaded, change document.domain to be the same as the one defined in parent. (You need to do this later because setting domain will cause the iframe resource's request to fail)

  • now you can make a reference for parent window: var winn = window.parent

  • now you can make a reference to parent HTML, in order to manipulate it: var parentContent = $('html', winn.document)
  • at this point you should have access to IE parent window/document and you can change it as you wont

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

ng-repeat :filter by single field

You can filter by an object with a property matching the objects you have to filter on it:

app.controller('FooCtrl', function($scope) {
   $scope.products = [
       { id: 1, name: 'test', color: 'red' },
       { id: 2, name: 'bob', color: 'blue' }
       /*... etc... */
   ];
});
<div ng-repeat="product in products | filter: { color: 'red' }"> 

This can of course be passed in by variable, as Mark Rajcok suggested.

Data binding in React

To be short, in React, there's no two-way data-binding.

So when you want to implement that feature, try define a state, and write like this, listening events, update the state, and React renders for you:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  render() {
    return (
      <input type="text" value={this.state.value} onChange={this.handleChange} />
    );
  }
}

Details here https://facebook.github.io/react/docs/forms.html

UPDATE 2020

Note:

LinkedStateMixin is deprecated as of React v15. The recommendation is to explicitly set the value and change handler, instead of using LinkedStateMixin.

above update from React official site . Use below code if you are running under v15 of React else don't.

There are actually people wanting to write with two-way binding, but React does not work in that way. If you do want to write like that, you have to use an addon for React, like this:

var WithLink = React.createClass({
  mixins: [LinkedStateMixin],
  getInitialState: function() {
    return {message: 'Hello!'};
  },
  render: function() {
    return <input type="text" valueLink={this.linkState('message')} />;
  }
});

Details here https://facebook.github.io/react/docs/two-way-binding-helpers.html

For refs, it's just a solution that allow developers to reach the DOM in methods of a component, see here https://facebook.github.io/react/docs/refs-and-the-dom.html

Remove trailing zeros

I use this code to avoid "G29" scientific notation:

public static string DecimalToString(this decimal dec)
{
    string strdec = dec.ToString(CultureInfo.InvariantCulture);
    return strdec.Contains(".") ? strdec.TrimEnd('0').TrimEnd('.') : strdec;
}

EDIT: using system CultureInfo.NumberFormat.NumberDecimalSeparator :

public static string DecimalToString(this decimal dec)
{
    string sep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
    string strdec = dec.ToString(CultureInfo.CurrentCulture);
    return strdec.Contains(sep) ? strdec.TrimEnd('0').TrimEnd(sep.ToCharArray()) : strdec;
}

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Removing empty rows of a data file in R

If you have empty rows, not NAs, you can do:

data[!apply(data == "", 1, all),]

To remove both (NAs and empty):

data <- data[!apply(is.na(data) | data == "", 1, all),]

Firing events on CSS class changes in jQuery

using latest jquery mutation

var $target = jQuery(".required-entry");
            var observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.attributeName === "class") {
                        var attributeValue = jQuery(mutation.target).prop(mutation.attributeName);
                        if (attributeValue.indexOf("search-class") >= 0){
                            // do what you want
                        }
                    }
                });
            });
            observer.observe($target[0],  {
                attributes: true
            });

// any code which update div having class required-entry which is in $target like $target.addClass('search-class');

HTTP Status 404 - The requested resource (/) is not available

What are you expecting? The default Tomcat homepage? If so, you'll need to configure Eclipse to take control over from Tomcat.

Doubleclick the Tomcat server entry in the Servers tab, you'll get the server configuration. At the left column, under Server Locations, select Use Tomcat installation (note, when it is grayed out, read the section leading text! ;) ). This way Eclipse will take full control over Tomcat, this way you'll also be able to access the default Tomcat homepage with the Tomcat Manager when running from inside Eclipse. I only don't see how that's useful while developing using Eclipse.

enter image description here

The port number is not the problem. You would otherwise have gotten an exception in Tomcat's startup log and the browser would show a browser-specific "Connection timed out" error page (and thus not a Tomcat-specific error page which would impossibly be served when Tomcat was not up and running!)

A regex for version number parsing

Specifying XSD elements:

<xs:simpleType>
    <xs:restriction base="xs:string">
        <xs:pattern value="[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(\..*)?"/>
    </xs:restriction>
</xs:simpleType>

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

XML Error: Extra content at the end of the document

I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.

Cannot catch toolbar home button click event

This is how I implemented it pre-material design and it seems to still work now I've switched to the new Toolbar. In my case I want to log the user in if they attempt to open the side nav while logged out, (and catch the event so the side nav won't open). In your case you could not return true;.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (!isLoggedIn() && item.getItemId() == android.R.id.home) {
        login();
        return true;
    }
    return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}

SQL Current month/ year question

This should work in MySql

SELECT * FROM 'my_table' WHERE 'month' = MONTH(CURRENT_TIMESTAMP) AND 'year' = YEAR(CURRENT_TIMESTAMP);

How does collections.defaultdict work?

Well, defaultdict can also raise keyerror in the following case:

    from collections import defaultdict
    d = defaultdict()
    print(d[3]) #raises keyerror

Always remember to give argument to the defaultdict like defaultdict(int).

Shift elements in a numpy array

One way to do it without spilt the code into cases

with array:

def shift(arr, dx, default_value):
    result = np.empty_like(arr)
    get_neg_or_none = lambda s: s if s < 0 else None
    get_pos_or_none = lambda s: s if s > 0 else None
    result[get_neg_or_none(dx): get_pos_or_none(dx)] = default_value
    result[get_pos_or_none(dx): get_neg_or_none(dx)] = arr[get_pos_or_none(-dx): get_neg_or_none(-dx)]     
    return result

with matrix it can be done like this:

def shift(image, dx, dy, default_value):
    res = np.full_like(image, default_value)

    get_neg_or_none = lambda s: s if s < 0 else None
    get_pos_or_none = lambda s : s if s > 0 else None

    res[get_pos_or_none(-dy): get_neg_or_none(-dy), get_pos_or_none(-dx): get_neg_or_none(-dx)] = \
        image[get_pos_or_none(dy): get_neg_or_none(dy), get_pos_or_none(dx): get_neg_or_none(dx)]
    return res

How to send POST request?

Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:

import requests

url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)

print(response.text)

More about Request object: https://requests.readthedocs.io/en/master/api/

How to determine if a string is a number with C++?

Try this:

isNumber(const std::string &str) {    
  return !str.empty() && str.find_first_not_of("0123456789") == string::npos;
}

Codeigniter LIKE with wildcard(%)

If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'.

$this->db->like('title', 'match', 'none'); 
// Produces: WHERE title LIKE 'match'

Difference between document.addEventListener and window.addEventListener?

You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window and document both fit the bill (with just a few differences).

From mozilla dev network:

addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.

So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.

Is there an addHeaderView equivalent for RecyclerView?

Native API doesn't have such "addHeader" feature, but has the concept of "addItem".

I was able to include this specific feature of headers and extends for footers as well in my FlexibleAdapter project. I called it Scrollable Headers and Footers.

Here how they work:

Scrollable Headers and Footers are special items that scroll along with all others, but they don't belongs to main items (business items) and they are always handled by the adapter beside the main items. Those items are persistently located at the first and last positions.

enter image description here

There's a lot to say about them, better to read the detailed wiki page.

Moreover the FlexibleAdapter allows you to create headers/sections, also you can have them sticky and tens of others features like expandable items, endless scroll, UI extensions etc... all in one library!

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

Gory details

A DLL uses the PE executable format, and it's not too tricky to read that information out of the file.

See this MSDN article on the PE File Format for an overview. You need to read the MS-DOS header, then read the IMAGE_NT_HEADERS structure. This contains the IMAGE_FILE_HEADER structure which contains the info you need in the Machine member which contains one of the following values

  • IMAGE_FILE_MACHINE_I386 (0x014c)
  • IMAGE_FILE_MACHINE_IA64 (0x0200)
  • IMAGE_FILE_MACHINE_AMD64 (0x8664)

This information should be at a fixed offset in the file, but I'd still recommend traversing the file and checking the signature of the MS-DOS header and the IMAGE_NT_HEADERS to be sure you cope with any future changes.

Use ImageHelp to read the headers...

You can also use the ImageHelp API to do this - load the DLL with LoadImage and you'll get a LOADED_IMAGE structure which will contain a pointer to an IMAGE_NT_HEADERS structure. Deallocate the LOADED_IMAGE with ImageUnload.

...or adapt this rough Perl script

Here's rough Perl script which gets the job done. It checks the file has a DOS header, then reads the PE offset from the IMAGE_DOS_HEADER 60 bytes into the file.

It then seeks to the start of the PE part, reads the signature and checks it, and then extracts the value we're interested in.

#!/usr/bin/perl
#
# usage: petype <exefile>
#
$exe = $ARGV[0];

open(EXE, $exe) or die "can't open $exe: $!";
binmode(EXE);
if (read(EXE, $doshdr, 64)) {

   ($magic,$skip,$offset)=unpack('a2a58l', $doshdr);
   die("Not an executable") if ($magic ne 'MZ');

   seek(EXE,$offset,SEEK_SET);
   if (read(EXE, $pehdr, 6)){
       ($sig,$skip,$machine)=unpack('a2a2v', $pehdr);
       die("No a PE Executable") if ($sig ne 'PE');

       if ($machine == 0x014c){
            print "i386\n";
       }
       elsif ($machine == 0x0200){
            print "IA64\n";
       }
       elsif ($machine == 0x8664){
            print "AMD64\n";
       }
       else{
            printf("Unknown machine type 0x%lx\n", $machine);
       }
   }
}

close(EXE);

Simple int to char[] conversion

#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;

itoa(a,arr,10) ;   // itoa() is a function of stdlib.h file that convert integer 
                   // int to array itoa( integer, targated array, base u want to             
                   //convert like decimal have 10 

for( int i= 0 ; i < strlen(arr); i++)   //  strlen()   function in string file thar return string length
  printf("%c",arr[i]);

}

How would I find the second largest salary from the employee table?

Most of the other answers seem to be db specific.

General SQL query should be as follows:

select
   sal 
from
   emp a 
where
   N = (
      select
         count(distinct sal) 
      from
         emp b 
      where
         a.sal <= b.sal
   )
where
   N = any value

and this query should be able to work on any database.

TypeScript: casting HTMLElement

Rather than using a type assertion, type guard, or any to work around the issue, a more elegant solution would be to use generics to indicate the type of element you're selecting.

Unfortunately, getElementsByName is not generic, but querySelector and querySelectorAll are. (querySelector and querySelectorAll are also far more flexible, and so might be preferable in most cases.)

If you pass a tag name alone into querySelector or querySelectorAll, it will automatically be typed properly due to the following line in lib.dom.d.ts:

querySelector<K extends keyof HTMLElementTagNameMap>(selectors: K): HTMLElementTagNameMap[K] | null;

For example, to select the first script tag on the page, as in your question, you can do:

const script = document.querySelector('script')!;

And that's it - TypeScript can now infer that script is now an HTMLScriptElement.

Use querySelector when you need to select a single element. If you need to select multiple elements, use querySelectorAll. For example:

document.querySelectorAll('script')

results in a type of NodeListOf<HTMLScriptElement>.

If you need a more complicated selector, you can pass a type parameter to indicate the type of the element you're going to select. For example:

const ageInput = document.querySelector<HTMLInputElement>('form input[name="age"]')!;

results in ageInput being typed as an HTMLInputElement.

When is "java.io.IOException:Connection reset by peer" thrown?

For me useful code witch help me was http://rox-xmlrpc.sourceforge.net/niotut/src/NioServer.java

// The remote forcibly closed the connection, cancel

// the selection key and close the channel.

    private void read(SelectionKey key) throws IOException {
            SocketChannel socketChannel = (SocketChannel) key.channel();

            // Clear out our read buffer so it's ready for new data
            this.readBuffer.clear();

            // Attempt to read off the channel
            int numRead;
            try {
                numRead = socketChannel.read(this.readBuffer);
            } catch (IOException e) {
                // The remote forcibly closed the connection, cancel
                // the selection key and close the channel.
                key.cancel();
                socketChannel.close();
                return;
            }

            if (numRead == -1) {
                // Remote entity shut the socket down cleanly. Do the
                // same from our end and cancel the channel.
                key.channel().close();
                key.cancel();
                return;
            }
...

Remove attribute "checked" of checkbox

try something like this FIDDLE

    try
      {
        navigator.device.capture.captureImage(function(mediaFiles) {
        console.log("works");
         });
      }

    catch(err)
      {
        alert('hi');
        $("#captureImage").prop('checked', false);

      }

Turn a number into star rating display using jQuery and CSS

Here's my take using JSX and font awesome, limited on only .5 accuracy, though:

       <span>
          {Array(Math.floor(rating)).fill(<i className="fa fa-star"></i>)}
          {(rating) - Math.floor(rating)==0 ? ('') : (<i className="fa fa-star-half"></i>)}
       </span>

First row is for whole star and second row is for half star (if any)

Plotting power spectrum in python

if rate is the sampling rate(Hz), then np.linspace(0, rate/2, n) is the frequency array of every point in fft. You can use rfft to calculate the fft in your data is real values:

import numpy as np
import pylab as pl
rate = 30.0
t = np.arange(0, 10, 1/rate)
x = np.sin(2*np.pi*4*t) + np.sin(2*np.pi*7*t) + np.random.randn(len(t))*0.2
p = 20*np.log10(np.abs(np.fft.rfft(x)))
f = np.linspace(0, rate/2, len(p))
plot(f, p)

enter image description here

signal x contains 4Hz & 7Hz sin wave, so there are two peaks at 4Hz & 7Hz.

How to save a git commit message from windows cmd?

Press Shift-zz. Saves changes and Quits. Escape didn't work for me.

I am using Git Bash in windows. And couldn't get past this either. My commit messages are simple so I dont want to add another editor atm.

How to echo (or print) to the js console with php

You can also try this way:

<?php
   echo "<script>console.log('$variableName')</script>";
?>

Any way to write a Windows .bat file to kill processes?

Download PSKill. Write a batch file that calls it for each process you want dead, passing in the name of the process for each.

How to convert a Java object (bean) to key-value pairs (and vice versa)?

With Java 8 you may try this :

public Map<String, Object> toKeyValuePairs(Object instance) {
    return Arrays.stream(Bean.class.getDeclaredMethods())
            .collect(Collectors.toMap(
                    Method::getName,
                    m -> {
                        try {
                            Object result = m.invoke(instance);
                            return result != null ? result : "";
                        } catch (Exception e) {
                            return "";
                        }
                    }));
}

How to display an error message in an ASP.NET Web Application

Roughly you can do it like that :

try
{
    //do something
}
catch (Exception ex)
{
    string script = "<script>alert('" + ex.Message + "');</script>";
    if (!Page.IsStartupScriptRegistered("myErrorScript"))
    {
         Page.ClientScript.RegisterStartupScript("myErrorScript", script);
    }
}

But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.

Get Element value with minidom with Python

I had a similar case, what worked for me was:

name.firstChild.childNodes[0].data

XML is supposed to be simple and it really is and I don't know why python's minidom did it so complicated... but it's how it's made

Why is Tkinter Entry's get function returning nothing?

It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.

Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:

import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        print(self.entry.get())

app = SampleApp()
app.mainloop()

Run the program, type into the entry widget, then click on the button.

HTML: How to center align a form

Being form a block element, you can center-align it by setting its side margins to auto:

form { margin: 0 auto; }

EDIT:
As @moomoochoo correctly pointed out, this rule will only work if the block element (your form, in this case) has been assigned a specific width.
Also, this 'trick' will not work for floating elements.

jQuery append() vs appendChild()

I know this is an old and answered question and I'm not looking for votes I just want to add an extra little thing that I think might help newcomers.

yes appendChild is a DOM method and append is JQuery method but practically the key difference is that appendChild takes a node as a parameter by that I mean if you want to add an empty paragraph to the DOM you need to create that p element first

var p = document.createElement('p')

then you can add it to the DOM whereas JQuery append creates that node for you and adds it to the DOM right away whether it's a text element or an html element or a combination!

$('p').append('<span> I have been appended </span>');

Find a string by searching all tables in SQL Server Management Studio 2008

If you are like me and have certain restrictions in a production environment, you may wish to use a table variable instead of temp table, and an ad-hoc query rather than a create procedure.

Of course depending on your sql server instance, it must support table variables.

I also added a USE statement to narrow the search scope

USE DATABASE_NAME
DECLARE @SearchStr nvarchar(100) = 'SEARCH_TEXT'
DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL

BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL

        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END    
END

SELECT ColumnName, ColumnValue FROM @Results

How can I consume a WSDL (SOAP) web service in Python?

There is a relatively new library which is very promising and albeit still poorly documented, seems very clean and pythonic: python zeep.

See also this answer for an example.

How to get diff between all files inside 2 folders that are on the web?

You urls are not in the same repository, so you can't do it with the svn diff command.

svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'

Another way you could do it, is export each repos using svn export, and then use the diff command to compare the 2 directories you exported.

// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2

// Compare exported directories
diff repos1 repos2 > file.diff

Need a query that returns every field that contains a specified letter

select * from your_table where your_field like '%a%b%'

and be prepared to wait a while...

Edit: note that this pattern looks for an 'a' followed by a 'b' (possibly with other "stuff" in between) -- rereading your question, that may not be what you wanted...

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

A bit late, but perhaps someone will find it useful.

Links that fix the problem (you must be logged into google account):

https://security.google.com/settings/security/activity?hl=en&pli=1

https://www.google.com/settings/u/1/security/lesssecureapps

https://accounts.google.com/b/0/DisplayUnlockCaptcha

Some explanation of what happens:

This problem can be caused by either 'less secure' applications trying to use the email account (this is according to google help, not sure how they judge what is secure and what is not) OR if you are trying to login several time in a row OR if you change countries (for example use VPN, move code to different server or actually try to login from different part of the world).

To resolve I had to: (first time)

  • login to my account via web
  • view recent attempts to use the account and accept suspicious access: THIS LINK
  • disable the feature of blocking suspicious apps/technologies: THIS LINK

This worked the first time, but few hours later, probably because I was doing a lot of testing the problem reappeared and was not fixable using the above method. In addition I had to clear the captcha (the funny picture, which asks you to rewrite a word or a sentence when logging into any account nowadays too many times) :

  • after login to my account I went HERE
  • Clicked continue

Hope this helps.

How to clear exisiting dropdownlist items when its content changes?

just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:

Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) //ddl2.Items.Clear()

ddl2.DataSource=New List(Of String)()
ddl2.DataSource = sql2
ddl2.DataBind() End Sub

and it worked just fine

Select mySQL based only on month and year

Suppose you have a database field created_at Where you take value from timestamp. You want to search by Year & Month from created_at date.

YEAR(date(created_at))=2019 AND MONTH(date(created_at))=2

How do I remove a substring from the end of a string in Python?

If you need to strip some end of a string if it exists otherwise do nothing. My best solutions. You probably will want to use one of first 2 implementations however I have included the 3rd for completeness.

For a constant suffix:

def remove_suffix(v, s):
    return v[:-len(s)] if v.endswith(s) else v
remove_suffix("abc.com", ".com") == 'abc'
remove_suffix("abc", ".com") == 'abc'

For a regex:

def remove_suffix_compile(suffix_pattern):
    r = re.compile(f"(.*?)({suffix_pattern})?$")
    return lambda v: r.match(v)[1]
remove_domain = remove_suffix_compile(r"\.[a-zA-Z0-9]{3,}")
remove_domain("abc.com") == "abc"
remove_domain("sub.abc.net") == "sub.abc"
remove_domain("abc.") == "abc."
remove_domain("abc") == "abc"

For a collection of constant suffixes the asymptotically fastest way for a large number of calls:

def remove_suffix_preprocess(*suffixes):
    suffixes = set(suffixes)
    try:
        suffixes.remove('')
    except KeyError:
        pass

    def helper(suffixes, pos):
        if len(suffixes) == 1:
            suf = suffixes[0]
            l = -len(suf)
            ls = slice(0, l)
            return lambda v: v[ls] if v.endswith(suf) else v
        si = iter(suffixes)
        ml = len(next(si))
        exact = False
        for suf in si:
            l = len(suf)
            if -l == pos:
                exact = True
            else:
                ml = min(len(suf), ml)
        ml = -ml
        suffix_dict = {}
        for suf in suffixes:
            sub = suf[ml:pos]
            if sub in suffix_dict:
                suffix_dict[sub].append(suf)
            else:
                suffix_dict[sub] = [suf]
        if exact:
            del suffix_dict['']
            for key in suffix_dict:
                suffix_dict[key] = helper([s[:pos] for s in suffix_dict[key]], None)
            return lambda v: suffix_dict.get(v[ml:pos], lambda v: v)(v[:pos])
        else:
            for key in suffix_dict:
                suffix_dict[key] = helper(suffix_dict[key], ml)
            return lambda v: suffix_dict.get(v[ml:pos], lambda v: v)(v)
    return helper(tuple(suffixes), None)
domain_remove = remove_suffix_preprocess(".com", ".net", ".edu", ".uk", '.tv', '.co.uk', '.org.uk')

the final one is probably significantly faster in pypy then cpython. The regex variant is likely faster than this for virtually all cases that do not involve huge dictionaries of potential suffixes that cannot be easily represented as a regex at least in cPython.

In PyPy the regex variant is almost certainly slower for large number of calls or long strings even if the re module uses a DFA compiling regex engine as the vast majority of the overhead of the lambda's will be optimized out by the JIT.

In cPython however the fact that your running c code for the regex compare almost certainly outweighs the algorithmic advantages of the suffix collection version in almost all cases.

Edit: https://m.xkcd.com/859/

How to skip the OPTIONS preflight request?

The preflight is being triggered by your Content-Type of application/json. The simplest way to prevent this is to set the Content-Type to be text/plain in your case. application/x-www-form-urlencoded & multipart/form-data Content-Types are also acceptable, but you'll of course need to format your request payload appropriately.

If you are still seeing a preflight after making this change, then Angular may be adding an X-header to the request as well.

Or you might have headers (Authorization, Cache-Control...) that will trigger it, see:

What's default HTML/CSS link color?

For me, on Chrome (updated June 2018) the color for an unvisited link is #2779F6. You can always get this by zooming in really close, taking a screenshot, and visiting a website like html-color-codes.info that will convert a screenshot to a color code.

Creating an empty file in C#

Using just File.Create will leave the file open, which probably isn't what you want.

You could use:

using (File.Create(filename)) ;

That looks slightly odd, mind you. You could use braces instead:

using (File.Create(filename)) {}

Or just call Dispose directly:

File.Create(filename).Dispose();

Either way, if you're going to use this in more than one place you should probably consider wrapping it in a helper method, e.g.

public static void CreateEmptyFile(string filename)
{
    File.Create(filename).Dispose();
}

Note that calling Dispose directly instead of using a using statement doesn't really make much difference here as far as I can tell - the only way it could make a difference is if the thread were aborted between the call to File.Create and the call to Dispose. If that race condition exists, I suspect it would also exist in the using version, if the thread were aborted at the very end of the File.Create method, just before the value was returned...

How to get child element by index in Jquery?

var node = document.getElementsByClassName("second")[0].firstElementChild

Disclaimer: Browser compliance on getElementsByClassName and firstElementChild are shaky. DOM-shims fix those problems though.

High-precision clock in Python

Python tries hard to use the most precise time function for your platform to implement time.time():

/* Implement floattime() for various platforms */

static double
floattime(void)
{
    /* There are three ways to get the time:
      (1) gettimeofday() -- resolution in microseconds
      (2) ftime() -- resolution in milliseconds
      (3) time() -- resolution in seconds
      In all cases the return value is a float in seconds.
      Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
      fail, so we fall back on ftime() or time().
      Note: clock resolution does not imply clock accuracy! */
#ifdef HAVE_GETTIMEOFDAY
    {
        struct timeval t;
#ifdef GETTIMEOFDAY_NO_TZ
        if (gettimeofday(&t) == 0)
            return (double)t.tv_sec + t.tv_usec*0.000001;
#else /* !GETTIMEOFDAY_NO_TZ */
        if (gettimeofday(&t, (struct timezone *)NULL) == 0)
            return (double)t.tv_sec + t.tv_usec*0.000001;
#endif /* !GETTIMEOFDAY_NO_TZ */
    }

#endif /* !HAVE_GETTIMEOFDAY */
    {
#if defined(HAVE_FTIME)
        struct timeb t;
        ftime(&t);
        return (double)t.time + (double)t.millitm * (double)0.001;
#else /* !HAVE_FTIME */
        time_t secs;
        time(&secs);
        return (double)secs;
#endif /* !HAVE_FTIME */
    }
}

( from http://svn.python.org/view/python/trunk/Modules/timemodule.c?revision=81756&view=markup )

Pick any kind of file via an Intent in Android

This gives me the best result:

    Intent intent;
    if (android.os.Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
        intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
        intent.putExtra("CONTENT_TYPE", "*/*");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
    } else {

        String[] mimeTypes =
                {"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
                        "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
                        "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
                        "text/plain",
                        "application/pdf",
                        "application/zip", "application/vnd.android.package-archive"};

        intent = new Intent(Intent.ACTION_GET_CONTENT); // or ACTION_OPEN_DOCUMENT
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    }

How to get char from string by index?

Another recommended exersice for understanding lists and indexes:

L = ['a', 'b', 'c']
for index, item in enumerate(L):
    print index + '\n' + item

0
a
1
b
2
c 

Best way to deploy Visual Studio application that can run without installing

First you need to publish the file by:

  1. BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go. Representation

  2. Save your file to a particular folder. Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj). In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files. (You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)

NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

Passing by reference in C

Because you're passing the value of the pointer to the method and then dereferencing it to get the integer that is pointed to.

How to send and receive JSON data from a restful webservice using Jersey API

Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.

@Path("/hello")
public class Hello {

  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {

    String input = (String) inputJsonObj.get("input");
    String output = "The input you sent is :" + input;
    JSONObject outputJsonObj = new JSONObject();
    outputJsonObj.put("output", output);

    return outputJsonObj;
  }
}

And, your client code should look like this:

  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  client.addFilter(new LoggingFilter());
  WebResource service = client.resource(getBaseURI());
  JSONObject inputJsonObj = new JSONObject();
  inputJsonObj.put("input", "Value");
  System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));

selenium - chromedriver executable needs to be in PATH

An answer from 2020. The following code solves this. A lot of people new to selenium seem to have to get past this step. Install the chromedriver and put it inside a folder on your desktop. Also make sure to put the selenium python project in the same folder as where the chrome driver is located.

Change USER_NAME and FOLDER in accordance to your computer.

For Windows

driver = webdriver.Chrome(r"C:\Users\USER_NAME\Desktop\FOLDER\chromedriver")

For Linux/Mac

driver = webdriver.Chrome("/home/USER_NAME/FOLDER/chromedriver")

File opens instead of downloading in internet explorer in a href link

This must be a matter of http headers.

see here: HTTP Headers for File Downloads

The server should tell your browser to download the file by sending

Content-Type: application/octet-stream; 
Content-Disposition: attachment;

in the headers

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

Most answers suggest to just add ServerName localhost to /etc/apache2/apache2.conf.

But quoting Apache documentation :

The presence of this error message also indicates that Apache httpd was unable to obtain a fully-qualified hostname by doing a reverse lookup on your server's IP address. While the above instructions will get rid of the warning in any case, it is also a good idea to fix your name resolution so that this reverse mapping works.

Therefore adding such a line to /etc/hosts is probably a more robust solution :

192.0.2.0  foobar.example.com  foobar

where 192.0.2.0 is the static IP address of the server named foobar within the example.com domain.

One can check the FQDN e.g. with

hostname -A

(shortcut for hostname --all-fqdn).

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

Try adding a reference to the missing dll's from your service/web project directly. Adding the references to a different project didn't work for me.

I only had to do this when publishing my web app because it wasn't copying all the required dll's.

Running a simple shell script as a cronjob

Specify complete path and grant proper permission to scriptfile. I tried following script file to run through cron:

#!/bin/bash
/bin/mkdir /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/crondir

And crontab command is

* * * * * /bin/bash /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/test.sh

It worked for me.

How to check that a JCheckBox is checked?

By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):

myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:

if(myCheckBox.isSelected()){_do_something_if_selected_}

HTML5 tag for horizontal line break

I am answering this old question just because it still shows up in google queries and I think one optimal answer is missing. Try this code: use ::before or ::after

See Align <hr> to the left in an HTML5-compliant way

Get the current user, within an ApiController action, without passing the userID as a parameter

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

Using Jquery Ajax to retrieve data from Mysql

This answer was for @
Neha Gandhi but I modified it for  people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer 

    <html>
<!--Save this as index.php-->
      <script src="//code.jquery.com/jquery-1.9.1.js"></script>
        <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
    
     <script type="text/javascript">
    
     $(document).ready(function() {
    
        $("#display").click(function() {                
    
          $.ajax({    //create an ajax request to display.php
            type: "GET",
            url: "display.php",             
            dataType: "html",   //expect html to be returned                
            success: function(response){                    
                $("#responsecontainer").html(response); 
                //alert(response);
            }
    
        });
    });
    });
    
    </script>
    
    <body>
    <h3 align="center">Manage Student Details</h3>
    <table border="1" align="center">
       <tr>
           <td> <input type="button" id="display" value="Display All Data" /> </td>
       </tr>
    </table>
    <div id="responsecontainer" align="center">
    
    </div>
    </body>
    </html>

<?php
// save this as display.php


    // show errors 
error_reporting(E_ALL);
ini_set('display_errors', 1);
    //errors ends here 
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT 
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials   FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();

echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";

while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName =    $row['lastName'];
$cell =    $row['cell'];

    echo "<tr>";
    echo "<td align=center>$firstName</td>";
    echo "<td align=center>$empid</td>";
    echo "<td align=center>$lastName </td>";
    echo "<td align=center>$cell</td>";
    echo "<td align=center>$cell</td>";
    echo "</tr>";
}
echo "</table>";
?>

<?php
// save this as dbconnector.php
function connected_Db(){

    $dsn  = 'mysql:host=localhost;dbname=mydb;charset=utf8';
    $opt  = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    #echo "Yes we are connected";
    return new PDO($dsn,'username','password', $opt);
    
}
$con = connected_Db();
if($con){
//echo "me  is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>

Drop primary key using script in SQL Server database

The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:

DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '

SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                               FROM     sysobjects
                                               WHERE    xtype = 'PK'
                                                        AND parent_obj =        OBJECT_ID('Student')))

EXEC (@SQL)

What is the difference between a JavaBean and a POJO?

POJO: If the class can be executed with underlying JDK,without any other external third party libraries support then its called POJO

JavaBean: If class only contains attributes with accessors(setters and getters) those are called javabeans.Java beans generally will not contain any bussiness logic rather those are used for holding some data in it.

All Javabeans are POJOs but all POJO are not Javabeans

syntax for creating a dictionary into another dictionary in python

Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?

Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.

To re-reference the values of one dictionary into another, you can use dict.update:

>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}

A change to a value that's present in both dictionaries will be visible in both:

>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}

This is the same as copying the value over or making a new dictionary with it, i.e.

>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

How to compare two vectors for equality element by element in C++?

According to the discussion here you can directly compare two vectors using

==

if (vector1 == vector2){
   //true
}
else{
   //false
}

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

Try this.

public class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        var json = config.Formatters.JsonFormatter;
        json.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional , Action =RouteParameter.Optional }

        );
    }
}

How do I set a VB.Net ComboBox default value

Just go to the combo box properties - DropDownStyle and change it to "DropDownList"

This will make visible the first item.

How to fix 'android.os.NetworkOnMainThreadException'?

I had a similar problem, I just used the following in oncreate method of your activity.

//allow strict mode
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

and it worked well.

Caveat is that using this for a network request that takes more than 100 miliseconds will cause noticeable UI freeze and potentially ANRs (Application Not Responding), so keep that in mind.

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

How to choose between Hudson and Jenkins?

Just my take on the matter, three months later:

Jenkins has continued the path well-trodden by the original Hudson with frequent releases including many minor updates.

Oracle seems to have largely delegated work on the future path for Hudson to the Sonatype team, who has performed some significant changes, especially with respect to Maven. They have jointly moved it to the Eclipse foundation.

I would suggest that if you like the sound of:

  • less frequent releases but ones that are more heavily tested for backwards compatibility (more of an "enterprise-style" release cycle)
  • a product focused primarily on strong Maven and/or Nexus integration (i.e., you have no interest in Gradle and Artifactory etc)
  • professional support offerings from Sonatype or maybe Oracle in preference to Cloudbees etc
  • you don't mind having a smaller community of plugin developers etc.

, then I would suggest Hudson.

Conversely, if you prefer:

  • more frequent updates, even if they require a bit more frequent tweaking and are perhaps slightly riskier in terms of compatibility (more of a "latest and greatest" release cycle)
  • a system with more active community support for e.g., other build systems / artifact repositories
  • support offerings from the original creator et al. and/or you have no interest in professional support (e.g., you're happy as long as you can get a fix in next week's "latest and greatest")
  • a classical OSS-style witches' brew of a development ecosystem

then I would suggest Jenkins. (and as a commenter noted, Jenkins now also has "LTS" releases which are maintained on a more "stable" branch)


The conservative course would be to choose Hudson now and migrate to Jenkins if must-have features are unavailable. The dynamic course would be to choose Jenkins now and migrate to Hudson if chasing updates becomes too time-consuming to justify.

Angular 2 Hover event

yes there is on-mouseover in angular2 instead of ng-Mouseover like in angular 1.x so you have to write this :-

<div on-mouseover='over()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>

over(){
    console.log("Mouseover called");
  }

As @Gunter Suggested in comment there is alternate of on-mouseover we can use this too. Some people prefer the on- prefix alternative, known as the canonical form.

Update

HTML Code -

<div (mouseover)='over()' (mouseout)='out()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>

Controller/.TS Code -

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  over(){
    console.log("Mouseover called");
  }

  out(){
    console.log("Mouseout called");
  }
}

Working Example

Some other Mouse events can be used in Angular -

(mouseenter)="myMethod()"
(mousedown)="myMethod()"
(mouseup)="myMethod()"

How can I run another application within a panel of my C# program?

I don't know if this is still the recommended thing to use but the "Object Linking and Embedding" framework allows you to embed certain objects/controls directly into your application. This will probably only work for certain applications, I'm not sure if Notepad is one of them. For really simple things like notepad, you'll probably have an easier time just working with the text box controls provided by whatever medium you're using (e.g. WinForms).

Here's a link to OLE info to get started:

http://en.wikipedia.org/wiki/Object_Linking_and_Embedding

How do I change the language of moment.js?

I had to import also the language:

import moment from 'moment'
import 'moment/locale/es'  // without this line it didn't work
moment.locale('es')

Then use moment like you normally would

alert(moment(date).fromNow())

jQuery: Setting select list 'selected' based on text, failing strangely

Using the filter() function seems to work in your test cases (tested in Firefox). The selector would look like this:

$('#mySelect1 option').filter(function () {
    return $(this).text() === 'Banana';
});

How to read data from java properties file using Spring Boot

We can read properties file in spring boot using 3 way

1. Read value from application.properties Using @Value

map key as

public class EmailService {

 @Value("${email.username}")
 private String username;

}

2. Read value from application.properties Using @ConfigurationProperties

In this we will map prefix of key using ConfigurationProperties and key name is same as field of class

  @Component
   @ConfigurationProperties("email")
    public class EmailConfig {

        private String   username;
    }

3. Read application.properties Using using Environment object

public class EmailController {

@Autowired
private Environment env;

@GetMapping("/sendmail")
public void sendMail(){     
    System.out.println("reading value from application properties file  using Environment ");
    System.out.println("username ="+ env.getProperty("email.username"));
    System.out.println("pwd ="+ env.getProperty("email.pwd"));
}

Reference : how to read value from application.properties in spring boot

What is the difference between task and thread?

Thread

The bare metal thing, you probably don't need to use it, you probably can use a LongRunning task and take the benefits from the TPL - Task Parallel Library, included in .NET Framework 4 (february, 2002) and above (also .NET Core).

Tasks

Abstraction above the Threads. It uses the thread pool (unless you specify the task as a LongRunning operation, if so, a new thread is created under the hood for you).

Thread Pool

As the name suggests: a pool of threads. Is the .NET framework handling a limited number of threads for you. Why? Because opening 100 threads to execute expensive CPU operations on a Processor with just 8 cores definitely is not a good idea. The framework will maintain this pool for you, reusing the threads (not creating/killing them at each operation), and executing some of them in parallel, in a way that your CPU will not burn.

OK, but when to use each one?

In resume: always use tasks.

Task is an abstraction, so it is a lot easier to use. I advise you to always try to use tasks and if you face some problem that makes you need to handle a thread by yourself (probably 1% of the time) then use threads.

BUT be aware that:

  • I/O Bound: For I/O bound operations (database calls, read/write files, APIs calls, etc) avoid using normal tasks, use LongRunning tasks (or threads if you need to). Because using tasks would lead you to a thread pool with a few threads busy and a lot of another tasks waiting for its turn to take the pool.
  • CPU Bound: For CPU bound operations just use the normal tasks (that internally will use the thread pool) and be happy.

Change image source with JavaScript

I know this question is old, but for the one's what are new, here is what you can do:

HTML

<img id="demo" src="myImage.png">

<button onclick="myFunction()">Click Me!</button>

JAVASCRIPT

function myFunction() {
document.getElementById('demo').src = "myImage.png";
}

What is cardinality in Databases?

Cardinality refers to the uniqueness of data contained in a column. If a column has a lot of duplicate data (e.g. a column that stores either "true" or "false"), it has low cardinality, but if the values are highly unique (e.g. Social Security numbers), it has high cardinality.

How do I get the logfile from an Android device?

I hope this code will help someone. It took me 2 days to figure out how to log from device, and then filter it:

public File extractLogToFileAndWeb(){
        //set a file
        Date datum = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ITALY);
        String fullName = df.format(datum)+"appLog.log";
        File file = new File (Environment.getExternalStorageDirectory(), fullName);

        //clears a file
        if(file.exists()){
            file.delete();
        }


        //write log to file
        int pid = android.os.Process.myPid();
        try {
            String command = String.format("logcat -d -v threadtime *:*");        
            Process process = Runtime.getRuntime().exec(command);

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder result = new StringBuilder();
            String currentLine = null;

            while ((currentLine = reader.readLine()) != null) {
                   if (currentLine != null && currentLine.contains(String.valueOf(pid))) {
                       result.append(currentLine);
                       result.append("\n");
                    }
            }

            FileWriter out = new FileWriter(file);
            out.write(result.toString());
            out.close();

            //Runtime.getRuntime().exec("logcat -d -v time -f "+file.getAbsolutePath());
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
        }


        //clear the log
        try {
            Runtime.getRuntime().exec("logcat -c");
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
        }

        return file;
    }

as pointed by @mehdok

add the permission to the manifest for reading logs

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

How to join two sets in one line without using "|"

You could use or_ alias:

>>> from operator import or_
>>> from functools import reduce # python3 required
>>> reduce(or_, [{1, 2, 3, 4}, {3, 4, 5, 6}])
set([1, 2, 3, 4, 5, 6])

How to create a GUID / UUID

For my use-case, I required id generation that was guaranteed to be unique globally; without exception. I struggled with the problem for a while, and came up with a solution called tuid (Truly Unique ID). It generates an id with the first 32 characters being system-generated and the remaining digits representing milliseconds since epoch. In situations where I need to generate id's on client-side javascript, it works well. Have a look:

https://github.com/mongoh/tuid

How to configure Eclipse build path to use Maven dependencies?

For newer Eclipse versions (>=Mars) right click on project > configure > convert to Maven project

Android : Capturing HTTP Requests with non-rooted android device

I just installed Drony, is not shareware and it does no require root on cellphone with Android 3.x or above

https://play.google.com/store/apps/details?id=org.sandroproxy.drony

It intercepts the requests and are shown on a LOG

What does iterator->second mean?

The type of the elements of an std::map (which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K and value is V is std::pair<const K, V> - the key is const to prevent you from interfering with the internal sorting of map values.

std::pair<> has two members named first and second (see here), with quite an intuitive meaning. Thus, given an iterator i to a certain map, the expression:

i->first

Which is equivalent to:

(*i).first

Refers to the first (const) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:

i->second

Which is equivalent to:

(*i).second

Refers to the second element of the pair - i.e. to the corresponding value in the map.

How can I set a website image that will show as preview on Facebook?

Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).

How to unpublish an app in Google Play Developer Console

  1. Go to your "play.google.com" dashboard
  2. Select your app
  3. In left menu item select "Store presence"
  4. Then, select "Pricing & distribution"
  5. Click "Unpublish" in "App Availability" section

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

Try this:

$(".datepicker").on("dp.change", function(e) {
    alert('hey');
});

(413) Request Entity Too Large | uploadReadAheadSize

For me, setting the uploadReadAheadSize to int.MaxValue also fixed the problem, after also increasing the limits on the WCF binding.

It seems that, when using SSL, the entire request entity body is preloaded, for which this metabase property is used.

For more info, see:

The page was not displayed because the request entity is too large. iis7

Reading data from a website using C#

If you're downloading text then I'd recommend using the WebClient and get a streamreader to the text:

        WebClient web = new WebClient();
        System.IO.Stream stream = web.OpenRead("http://www.yoursite.com/resource.txt");
        using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
        {
            String text = reader.ReadToEnd();
        }

If this is taking a long time then it is probably a network issue or a problem on the web server. Try opening the resource in a browser and see how long that takes. If the webpage is very large, you may want to look at streaming it in chunks rather than reading all the way to the end as in that example. Look at http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx to see how to read from a stream.

How can we dynamically allocate and grow an array

public class Arr {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int a[] = {1,2,3};
        //let a[] is your original array
        System.out.println(a[0] + " " + a[1] + " " + a[2]);
        int b[];
        //let b[] is your temporary array with size greater than a[]
        //I have took 5
        b = new int[5];
        //now assign all a[] values to b[]
        for(int i = 0 ; i < a.length ; i ++)
            b[i] = a[i];
        //add next index values to b
        b[3] = 4;
        b[4] = 5;
        //now assign b[] to a[]
        a = b;
        //now you can heck that size of an original array increased
        System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " " 
    + a[4]);
    }

}

Output for the above code is:

1 2 3

1 2 3 4 5

How long is the SHA256 hash?

A sha256 is 256 bits long -- as its name indicates.

Since sha256 returns a hexadecimal representation, 4 bits are enough to encode each character (instead of 8, like for ASCII), so 256 bits would represent 64 hex characters, therefore you need a varchar(64), or even a char(64), as the length is always the same, not varying at all.

And the demo :

$hash = hash('sha256', 'hello, world!');
var_dump($hash);

Will give you :

$ php temp.php
string(64) "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728"

i.e. a string with 64 characters.

CSS3 Transition not working

Transition is more like an animation.

div.sicon a {
    background:-moz-radial-gradient(left, #ffffff 24%, #cba334 88%);
    transition: background 0.5s linear;
    -moz-transition: background 0.5s linear; /* Firefox 4 */
    -webkit-transition: background 0.5s linear; /* Safari and Chrome */
    -o-transition: background 0.5s linear; /* Opera */
    -ms-transition: background 0.5s linear; /* Explorer 10 */
}

So you need to invoke that animation with an action.

div.sicon a:hover {
    background:-moz-radial-gradient(left, #cba334 24%, #ffffff 88%);
}

Also check for browser support and if you still have some problem with whatever you're trying to do! Check css-overrides in your stylesheet and also check out for behavior: ***.htc css hacks.. there may be something overriding your transition!

You should check this out: http://www.w3schools.com/css/css3_transitions.asp

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.

Creating Accordion Table with Bootstrap

For anyone who came here looking for how to get the true accordion effect and only allow one row to be expanded at a time, you can add an event handler for show.bs.collapse like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified this example to do so here: http://jsfiddle.net/QLfMU/116/

How to call a stored procedure from Java and JPA

To call stored procedure we can use Callable Statement in java.sql package.

Passing multiple values for a single parameter in Reporting Services

This works great for me:

WHERE CHARINDEX(CONVERT(nvarchar, CustNum), @CustNum) > 0

Margin while printing html page

I also recommend pt versus cm or mm as it's more precise. Also, I cannot get @page to work in Chrome (version 30.0.1599.69 m) It ignores anything I put for the margins, large or small. But, you can get it to work with body margins on the document, weird.

Scala Doubles, and Precision

Edit: fixed the problem that @ryryguy pointed out. (Thanks!)

If you want it to be fast, Kaito has the right idea. math.pow is slow, though. For any standard use you're better off with a recursive function:

def trunc(x: Double, n: Int) = {
  def p10(n: Int, pow: Long = 10): Long = if (n==0) pow else p10(n-1,pow*10)
  if (n < 0) {
    val m = p10(-n).toDouble
    math.round(x/m) * m
  }
  else {
    val m = p10(n).toDouble
    math.round(x*m) / m
  }
}

This is about 10x faster if you're within the range of Long (i.e 18 digits), so you can round at anywhere between 10^18 and 10^-18.

multiple conditions for filter in spark data frames

In spark/scala, it's pretty easy to filter with varargs.

val d = spark.read...//data contains column named matid
val ids = Seq("BNBEL0608AH", "BNBEL00608H")
val filtered = d.filter($"matid".isin(ids:_*))

Why std::cout instead of simply cout?

It seems possible your class may have been using pre-standard C++. An easy way to tell, is to look at your old programs and check, do you see:

#include <iostream.h>

or

#include <iostream>

The former is pre-standard, and you'll be able to just say cout as opposed to std::cout without anything additional. You can get the same behavior in standard C++ by adding

using std::cout;

or

using namespace std;

Just one idea, anyway.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

I was facing the same problem in IntelliJ. It was working from command line though.

I found the issue was because of an improper Gradle config in the IDE. I wasn't using the "default Gradle wrapper" as recommended:

enter image description here

Angular2 get clicked element id

Finally found the simplest way:

<button (click)="toggle($event)" class="someclass" id="btn1"></button>
<button (click)="toggle($event)" class="someclass" id="btn2"></button>

toggle(event) {
   console.log(event.target.id); 
}

What is the format specifier for unsigned short int?

Try using the "%h" modifier:

scanf("%hu", &length);
        ^

ISO/IEC 9899:201x - 7.21.6.1-7

Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.

Turning off eslint rule for a specific file

It's better to add "overrides" in your .eslintrc.js config file. For example if you wont to disable camelcase rule for all js files ending on Actions add this code after rules scope in .eslintrc.js.

"rules": {    
...........    
},
"overrides": [
 {
  "files": ["*Actions.js"],
     "rules": {
        "camelcase": "off"   
     }
 }
]

Count lines in large files

Your limiting speed factor is the I/O speed of your storage device, so changing between simple newlines/pattern counting programs won't help, because the execution speed difference between those programs are likely to be suppressed by the way slower disk/storage/whatever you have.

But if you have the same file copied across disks/devices, or the file is distributed among those disks, you can certainly perform the operation in parallel. I don't know specifically about this Hadoop, but assuming you can read a 10gb the file from 4 different locations, you can run 4 different line counting processes, each one in one part of the file, and sum their results up:

$ dd bs=4k count=655360 if=/path/to/copy/on/disk/1/file | wc -l &
$ dd bs=4k skip=655360 count=655360 if=/path/to/copy/on/disk/2/file | wc -l &
$ dd bs=4k skip=1310720 count=655360 if=/path/to/copy/on/disk/3/file | wc -l &
$ dd bs=4k skip=1966080 if=/path/to/copy/on/disk/4/file | wc -l &

Notice the & at each command line, so all will run in parallel; dd works like cat here, but allow us to specify how many bytes to read (count * bs bytes) and how many to skip at the beginning of the input (skip * bs bytes). It works in blocks, hence, the need to specify bs as the block size. In this example, I've partitioned the 10Gb file in 4 equal chunks of 4Kb * 655360 = 2684354560 bytes = 2.5GB, one given to each job, you may want to setup a script to do it for you based on the size of the file and the number of parallel jobs you will run. You need also to sum the result of the executions, what I haven't done for my lack of shell script ability.

If your filesystem is smart enough to split big file among many devices, like a RAID or a distributed filesystem or something, and automatically parallelize I/O requests that can be paralellized, you can do such a split, running many parallel jobs, but using the same file path, and you still may have some speed gain.

EDIT: Another idea that occurred to me is, if the lines inside the file have the same size, you can get the exact number of lines by dividing the size of the file by the size of the line, both in bytes. You can do it almost instantaneously in a single job. If you have the mean size and don't care exactly for the the line count, but want an estimation, you can do this same operation and get a satisfactory result much faster than the exact operation.

How to solve error message: "Failed to map the path '/'."

I Think this is because of IIS is unable to find the root folder. i.e wwwroot. Restarting the IIS wont be helpful in some scenarios. if the root path has changed, you should bring it back to %SystemDrive%\inetpub\wwwroot

by right clicking sites node in IIS and changing physical path to the above one.

and make sure that your application pool is asp.net v4.0 and running in integrated mode

Dealing with HTTP content in HTTPS pages

I don't know if this would fit what you are doing, but as a quick fix I would "wrap" the http content into an https script. For instance, on your page that is served through https i would introduce an iframe that would replace your rss feed and in the src attr of the iframe put a url of a script on your server that captures the feed and outputs the html. the script is reading the feed through http and outputs it through https (thus "wrapping")

Just a thought

How do I count unique items in field in Access query?

Access-Engine does not support

SELECT count(DISTINCT....) FROM ...

You have to do it like this:

SELECT count(*) 
FROM
(SELECT DISTINCT Name FROM table1)

Its a little workaround... you're counting a DISTINCT selection.

Angular - Can't make ng-repeat orderBy work

The orderBy only works with Arrays -- See http://docs.angularjs.org/api/ng.filter:orderBy

Also a great filter to use for Objects instead of Arrays @ Angularjs OrderBy on ng-repeat doesn't work

How to group an array of objects by key

_x000D_
_x000D_
var cars = [{
  make: 'audi',
  model: 'r8',
  year: '2012'
}, {
  make: 'audi',
  model: 'rs5',
  year: '2013'
}, {
  make: 'ford',
  model: 'mustang',
  year: '2012'
}, {
  make: 'ford',
  model: 'fusion',
  year: '2015'
}, {
  make: 'kia',
  model: 'optima',
  year: '2012'
}].reduce((r, car) => {

  const {
    model,
    year,
    make
  } = car;

  r[make] = [...r[make] || [], {
    model,
    year
  }];

  return r;
}, {});

console.log(cars);
_x000D_
_x000D_
_x000D_

Maven: mvn command not found

Maven setup:

a. install maven from https://maven.apache.org/download.cgi

b. unzip maven and keep in C drive.

c. Set MAVEN_HOME in system variable. enter image description here

d. Set path for maven enter image description here

How to secure phpMyAdmin

You can use the following command :

$ grep "phpmyadmin" $path_to_access.log | grep -Po "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" | sort | uniq | xargs -I% sudo iptables -A INPUT -s % -j DROP 

Explanation:

Make sure your IP isn't listed before piping through iptables drop!!

This will first find all lines in $path_to_access.log that have phpmyadmin in them,

then grep out the ip address from the start of the line,

then sort and unique them,

then add a rule to drop them in iptables

Again, just edit in echo % at the end instead of the iptables command to make sure your IP isn't in there. Don't inadvertently ban your access to the server!

Limitations

You may need to change the grep part of the command if you're on mac or any system that doesn't have grep -P. I'm not sure if all systems start with xargs, so that might need to be installed too. It's super useful anyway if you do a lot of bash.

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

I found if you have issues with including or mixing your page with something like http://www.example.com, you can fix that by putting //www.example.com instead

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

In other words...

IDE Even your notepad is an IDE. Every software you write/compile code with is an IDE.

Library A bunch of code which simplifies functions/methods for quick use.

API A programming interface for functions/configuration which you work with, its usage is often documented.

SDK Extras and/or for development/testing purposes.

ToolKit Tiny apps for quick use, often GUIs.

GUI Apps with a graphical interface, requires no knowledge of programming unlike APIs.

Framework Bunch of APIs/huge Library/Snippets wrapped in a namespace/or encapsulated from outer scope for compact handling without conflicts with other code.

MVC A design pattern separated in Models, Views and Controllers for huge applications. They are not dependent on each other and can be changed/improved/replaced without to take care of other code.

Example:

Car (Model)
The object that is being presented.
Example in IT: A HTML form.


Camera (View)
Something that is able to see the object(car).
Example in IT: Browser that renders a website with the form.


Driver (Controller)
Someone who drives that car.
Example in IT: Functions which handle form data that's being submitted.

Snippets Small codes of only a few lines, may not be even complete but worth for a quick share.

Plug-ins Exclusive functions for specified frameworks/APIs/libraries only.

Add-ons Additional modules or services for specific GUIs.

IIS Request Timeout on long ASP.NET operation

Remove ~ character in location so

path="~/Admin/SomePage.aspx"

becomes

path="Admin/SomePage.aspx"

Rails migration for change column

Another way to change data type using migration

step1: You need to remove the faulted data type field name using migration

ex:

rails g migration RemoveFieldNameFromTableName field_name:data_type

Here don't forget to specify data type for your field

Step 2: Now you can add field with correct data type

ex:

rails g migration AddFieldNameToTableName field_name:data_type

That's it, now your table will added with correct data type field, Happy ruby coding!!

How to style the UL list to a single line

Try experimenting with something like this also:

HTML

 <ul class="inlineList">
   <li>She</li>
   <li>Needs</li>
   <li>More Padding, Captain!</li>
 </ul>

CSS

 .inlineList {
   display: flex;
   flex-direction: row;
   /* Below sets up your display method: flex-start|flex-end|space-between|space-around */
   justify-content: flex-start; 
   /* Below removes bullets and cleans white-space */
   list-style: none;
   padding: 0;
   /* Bonus: forces no word-wrap */
   white-space: nowrap;
 }
 /* Here, I got you started.
 li {
   padding-top: 50px;
   padding-bottom: 50px;
   padding-left: 50px;
   padding-right: 50px;
 }
 */

I made a codepen to illustrate: http://codepen.io/agm1984/pen/mOxaEM

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

List(of String) or Array or ArrayList

Neither collection will let you add items that way.

You can make an extension to make for examle List(Of String) have an Add method that can do that:

Imports System.Runtime.CompilerServices
Module StringExtensions

  <Extension()>
  Public Sub Add(ByVal list As List(Of String), ParamArray values As String())
    For Each s As String In values
      list.Add(s)
    Next
  End Sub

End Module

Now you can add multiple value in one call:

Dim lstOfStrings as New List(Of String)
lstOfStrings.Add(String1, String2, String3, String4)

How does the class_weight parameter in scikit-learn work?

The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.

SUMMARY

  • for moderately imbalanced data WITHOUT noise, there is not much of a difference in applying class weights
  • for moderately imbalanced data WITH noise and strongly imbalanced, it is better to apply class weights
  • param class_weight="balanced" works decent in the absence of you wanting to optimize manually
  • with class_weight="balanced" you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
    • as a result, the total % TRUE might be higher than actual because of all the false positives
    • AUC might misguide you here if the false alarms are an issue
  • no need to change decision threshold to the imbalance %, even for strong imbalance, ok to keep 0.5 (or somewhere around that depending on what you need)

NB

The result might differ when using RF or GBM. sklearn does not have class_weight="balanced" for GBM but lightgbm has LGBMClassifier(is_unbalance=False)

CODE

# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd

# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same

# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last

print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%

print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE

"Port 4200 is already in use" when running the ng serve command

To stop all the local port running in windows, use this simple comment alone instead searching for pid separatly using netstat,

It find all the pid and stop the local port which is currently running,

taskkill /im node.exe /f

How to check if an element is off-screen

You could check the position of the div using $(div).position() and check if the left and top margin properties are less than 0 :

if($(div).position().left < 0 && $(div).position().top < 0){
    alert("off screen");
}

Appending an element to the end of a list in Scala

That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:

(4 :: List(1,2,3).reverse).reverse

or that:

List(1,2,3) ::: List(4)

How to set headers in http get request?

Go's net/http package has many functions that deal with headers. Among them are Add, Del, Get and Set methods. The way to use Set is:

func yourHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("header_name", "header_value")
}

What is sr-only in Bootstrap 3?

According to bootstrap's documentation, the class is used to hide information intended only for screen readers from the layout of the rendered page.

Screen readers will have trouble with your forms if you don't include a label for every input. For these inline forms, you can hide the labels using the .sr-only class.

Here is an example styling used:

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0,0,0,0);
  border: 0;
}

Is it important or can I remove it? Works fine without.

It's important, don't remove it.

You should always consider screen readers for accessibility purposes. Usage of the class will hide the element anyways, therefore you shouldn't see a visual difference.

If you're interested in reading about accessibility:

Adding integers to an int array

you have an array of int which is a primitive type, primitive type doesn't have the method add. You should look for Collections.

Pass variables to AngularJS controller, best practice?

You could create a basket service. And generally in JS you use objects instead of lots of parameters.

Here's an example: http://jsfiddle.net/2MbZY/

var app = angular.module('myApp', []);

app.factory('basket', function() {
    var items = [];
    var myBasketService = {};

    myBasketService.addItem = function(item) {
        items.push(item);
    };
    myBasketService.removeItem = function(item) {
        var index = items.indexOf(item);
        items.splice(index, 1);
    };
    myBasketService.items = function() {
        return items;
    };

    return myBasketService;
});

function MyCtrl($scope, basket) {
    $scope.newItem = {};
    $scope.basket = basket;    
}

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

What is the Maximum Size that an Array can hold?

I think if you don't consider the VM, it is Integer.MaxValue

How to check if one of the following items is in a list?

Simple.

_new_list = []
for item in a:
    if item in b:
        _new_list.append(item)
    else:
        pass

Left align and right align within div in Bootstrap

bootstrap 5.0

_x000D_
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

<div class="row">
  <div class="col-sm-6"><p class="float-start">left</p></div>  
  <div class="col-sm-6"><p class="float-end">right</p></div>  
</div>
_x000D_
_x000D_
_x000D_

A whole column can accommodate 12, 6 (col-sm-6) is exactly half, and in this half, one to the left(float-start) and one to the right(float-end).

more example

  • fontawesome-button

    _x000D_
    _x000D_
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />
    
    <div class="row">
      <div class=col-sm-6>
        <p class="float-start text-center">  <!-- text-center can help you put the icon at the center -->
          <a class="text-decoration-none" href="https://www.google.com/"
          ><i class="fas fa-arrow-circle-left fa-3x"></i><br>Left
          </a>
        </p>
      </div>
      <div class=col-sm-6>
        <p class="float-end text-center">
          <a class="text-decoration-none" href="https://www.google.com/"
          ><i class="fas fa-arrow-circle-right fa-3x"></i><br>Right
          </a>
        </p>
      </div>  
    _x000D_
    _x000D_
    _x000D_

C# how to wait for a webpage to finish loading before continuing

If you are using the InternetExplorer.Application COM object, check the ReadyState property for the value of 4.

How to display default text "--Select Team --" in combo box on pageload in WPF?

I would recommend the following:

Define a behavior

public static class ComboBoxBehaviors
{
    public static readonly DependencyProperty DefaultTextProperty =
        DependencyProperty.RegisterAttached("DefaultText", typeof(String), typeof(ComboBox), new PropertyMetadata(null));

    public static String GetDefaultText(DependencyObject obj)
    {
        return (String)obj.GetValue(DefaultTextProperty);
    }

    public static void SetDefaultText(DependencyObject obj, String value)
    {
        var combo = (ComboBox)obj;

        RefreshDefaultText(combo, value);

        combo.SelectionChanged += (sender, _) => RefreshDefaultText((ComboBox)sender, GetDefaultText((ComboBox)sender));

        obj.SetValue(DefaultTextProperty, value);
    }

    static void RefreshDefaultText(ComboBox combo, string text)
    {
        // if item is selected and DefaultText is set
        if (combo.SelectedIndex == -1 && !String.IsNullOrEmpty(text))
        {
            // Show DefaultText
            var visual = new TextBlock()
            {
                FontStyle = FontStyles.Italic,
                Text = text,
                Foreground = Brushes.Gray
            };

            combo.Background = new VisualBrush(visual)
            {
                Stretch = Stretch.None,
                AlignmentX = AlignmentX.Left,
                AlignmentY = AlignmentY.Center,
                Transform = new TranslateTransform(3, 0)
            };
        }
        else
        {
            // Hide DefaultText
            combo.Background = null;
        }
    }
}

User the behavior

<ComboBox Name="cmb" Margin="72,121,0,0" VerticalAlignment="Top"
          local:ComboBoxBehaviors.DefaultText="-- Select Team --"/>

Add custom icons to font awesome

Give Icomoon a try. You can upload your own SVGs, add them to the library, then create a custom font combining FontAwesome with your own icons.

Gradle finds wrong JAVA_HOME even though it's correctly set

Adding below lines in build.gradle solved my issue .

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8

Base64 encoding in SQL Server 2005 T-SQL

DECLARE @source varbinary(max),  
@encoded_base64 varchar(max),  
@decoded varbinary(max) 
SET @source = CONVERT(varbinary(max), 'welcome') 
-- Convert from varbinary to base64 string 
SET @encoded_base64 = CAST(N'' AS xml).value('xs:base64Binary(sql:variable       
("@source"))', 'varchar(max)') 
  -- Convert back from base64 to varbinary 
   SET @decoded = CAST(N'' AS xml).value('xs:base64Binary(sql:variable             
  ("@encoded_base64"))', 'varbinary(max)') 

 SELECT
  CONVERT(varchar(max), @source) AS [Source varchar], 
   @source AS [Source varbinary], 
     @encoded_base64 AS [Encoded base64], 
     @decoded AS [Decoded varbinary], 
     CONVERT(varchar(max), @decoded) AS [Decoded varchar]

This is usefull for encode and decode.

By Bharat J

Comparing two arrays & get the values which are not common

Look at Compare-Object

Compare-Object $a1 $b1 | ForEach-Object { $_.InputObject }

Or if you would like to know where the object belongs to, then look at SideIndicator:

$a1=@(1,2,3,4,5,8)
$b1=@(1,2,3,4,5,6)
Compare-Object $a1 $b1

How can I determine the direction of a jQuery scroll event?

You can do it without having to keep track of the previous scroll top, as all the other examples require:

$(window).bind('mousewheel', function(event) {
    if (event.originalEvent.wheelDelta >= 0) {
        console.log('Scroll up');
    }
    else {
        console.log('Scroll down');
    }
});

I am not an expert on this so feel free to research it further, but it appears that when you use $(element).scroll, the event being listened for is a 'scroll' event.

But if you specifically listen for a mousewheel event by using bind, the originalEvent attribute of the event parameter to your callback contains different information. Part of that information is wheelDelta. If it's positive, you moved the mousewheel up. If it's negative, you moved the mousewheel down.

My guess is that mousewheel events will fire when the mouse wheel turns, even if the page does not scroll; a case in which 'scroll' events probably are not fired. If you want, you can call event.preventDefault() at the bottom of your callback to prevent the page from scrolling, and so that you can use the mousewheel event for something other than a page scroll, like some type of zoom functionality.

Getting the exception value in Python

Use repr() and The difference between using repr and str

Using repr:

>>> try:
...     print(x)
... except Exception as e:
...     print(repr(e))
... 
NameError("name 'x' is not defined")

Using str:

>>> try:
...     print(x)
... except Exception as e:
...     print(str(e))
... 
name 'x' is not defined

How do I configure different environments in Angular.js?

Have you seen this question and its answer?

You can set a globally valid value for you app like this:

app.value('key', 'value');

and then use it in your services. You could move this code to a config.js file and execute it on page load or another convenient moment.

Assigning more than one class for one event

    $('[class*="tag"]').live('click', function() {
      if ($(this).hasClass('clickedTag')){
         // code here
      } else {
         // and here
      }
   });

C: convert double to float, preserving decimal point precision

A float generally has about 7 digits of precision, regardless of the position of the decimal point. So if you want 5 digits of precision after the decimal, you'll need to limit the range of the numbers to less than somewhere around +/-100.

Java Error opening registry key

Make sure you remove any java.exe, javaw.exe and javaws.exe from your Windows\System32 folder and if you have an x64 system (Win 7 64 bits) also do the same under Windows\SysWOW64.

If you can't find them at these locations, try deleting them from C:\ProgramData\Oracle\Java\javapath.

Get the new record primary key ID from MySQL insert query?

BEWARE !! of LAST_INSERT_ID() if trying to return this primary key value within PHP.

I know this thread is not tagged PHP, but for anybody who came across this answer looking to return a MySQL insert id from a PHP scripted insert using standard mysql_query calls - it wont work and is not obvious without capturing SQL errors.

The newer mysqli supports multiple queries - which LAST_INSERT_ID() actually is a second query from the original.

IMO a separate SELECT to identify the last primary key is safer than the optional mysql_insert_id() function returning the AUTO_INCREMENT ID generated from the previous INSERT operation.

Compiling and Running Java Code in Sublime Text 2

As detailed here:

http://sublimetext.userecho.com/topic/90531-default-java-build-system-update/

Steps I took to remedy this

  1. Click Start

  2. Right click on 'Computer'

2.5 Click Properties.

  1. On the left hand side select 'Advanced System Settings'

  2. Near the bottom click on 'Environment Variables'

  3. Scroll down on 'System Variables' until you find 'PATH' - click edit with this selected.

  4. Add the path to your Java bin folder. Mine ends up looking like this:

    CODE: SELECT ALL

    ;C:\Program Files\Java\jdk1.7.0_03\bin\

How to check if any flags of a flag combination are set?

In .NET 4 you can use the Enum.HasFlag method :

using System;

[Flags] public enum Pet {
   None = 0,
   Dog = 1,
   Cat = 2,
   Bird = 4,
   Rabbit = 8,
   Other = 16
}

public class Example
{
   public static void Main()
   {
      // Define three families: one without pets, one with dog + cat and one with a dog only
      Pet[] petsInFamilies = { Pet.None, Pet.Dog | Pet.Cat, Pet.Dog };
      int familiesWithoutPets = 0;
      int familiesWithDog = 0;

      foreach (Pet petsInFamily in petsInFamilies)
      {
         // Count families that have no pets. 
         if (petsInFamily.Equals(Pet.None))
            familiesWithoutPets++;
         // Of families with pets, count families that have a dog. 
         else if (petsInFamily.HasFlag(Pet.Dog))
            familiesWithDog++;
      }
      Console.WriteLine("{0} of {1} families in the sample have no pets.", 
                        familiesWithoutPets, petsInFamilies.Length);   
      Console.WriteLine("{0} of {1} families in the sample have a dog.", 
                        familiesWithDog, petsInFamilies.Length);   
   }
}

The example displays the following output:

//       1 of 3 families in the sample have no pets. 
//       2 of 3 families in the sample have a dog.

Unit Testing C Code

I used RCUNIT to do some unit testing for embedded code on PC before testing on the target. Good hardware interface abstraction is important else endianness and memory mapped registers are going to kill you.

Why rgb and not cmy?

The basic colours are RGB not RYB. Yes most of the softwares use the traditional RGB which can be used to mix together to form any other color i.e. RGB are the fundamental colours (as defined in Physics & Chemistry texts).

The printer user CMYK (cyan, magenta, yellow, and black) coloring as said by @jcomeau_ictx. You can view the following article to know about RGB vs CMYK: RGB Vs CMYK

A bit more information from the extract about them:

Red, Green, and Blue are "additive colors". If we combine red, green and blue light you will get white light. This is the principal behind the T.V. set in your living room and the monitor you are staring at now. Additive color, or RGB mode, is optimized for display on computer monitors and peripherals, most notably scanning devices.

Cyan, Magenta and Yellow are "subtractive colors". If we print cyan, magenta and yellow inks on white paper, they absorb the light shining on the page. Since our eyes receive no reflected light from the paper, we perceive black... in a perfect world! The printing world operates in subtractive color, or CMYK mode.

Transform only one axis to log10 scale with ggplot2

The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:

m + geom_boxplot() + scale_y_continuous(trans='log10')

EDIT: Or if you don't like that, then either of these appears to give different but useful results:

m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot() 
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()

EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):

fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) + 
  geom_boxplot() + 
  scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)

alt text

Note added mid 2017 in comment about package syntax change:

scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)

Oracle: how to add minutes to a timestamp?

SELECT to_char(sysdate + (1/24/60) * 30, 'dd/mm/yy HH24:MI am') from dual;

simply you can use this with various date format....

iOS - UIImageView - how to handle UIImage image orientation

Swift 3.0 version of Tommy's answer

let imageToDisplay = UIImage.init(cgImage: originalImage.cgImage!, scale: originalImage.scale, orientation: UIImageOrientation.up)

Removing Data From ElasticSearch

For mass-delete by query you may use special delete by query API:

$ curl -XDELETE 'http://localhost:9200/twitter/tweet/_query' -d '{
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

In history that API was deleted and then reintroduced again

Who interesting it has long history.

  1. In first version of that answer I refer to documentation of elasticsearch version 1.6. In it that functionality was marked as deprecated but works good.
  2. In elasticsearch version 2.0 it was moved to separate plugin. And even reasons why it became plugin explained.
  3. And it again appeared in core API in version 5.0!

Very Simple, Very Smooth, JavaScript Marquee

My text marquee for more text, and position absolute enabled

http://jsfiddle.net/zrW5q/2075/

(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
  position: 'absolute',
  visibility: 'hidden',
  height: 'auto',
  width: 'auto',
  'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};

$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
    offset = that.width(),
    width = offset,
    css = {
        'text-indent': that.css('text-indent'),
        'overflow': that.css('overflow'),
        'white-space': that.css('white-space')
    },
    marqueeCss = {
        'text-indent': width,
        'overflow': 'hidden',
        'white-space': 'nowrap'
    },
    args = $.extend(true, {
        count: -1,
        speed: 1e1,
        leftToRight: false
    }, args),
    i = 0,
    stop = textWidth * -1,
    dfd = $.Deferred();

function go() {
    if (that.css('overflow') != "hidden") {
        that.css('text-indent', width + 'px');
        return false;
    }
    if (!that.length) return dfd.reject();

    if (width <= stop) {
        i++;
        if (i == args.count) {
            that.css(css);
            return dfd.resolve();
        }
        if (args.leftToRight) {
            width = textWidth * -1;
        } else {
            width = offset;
        }
    }
    that.css('text-indent', width + 'px');
    if (args.leftToRight) {
        width++;
    } else {
        width--;
    }
    setTimeout(go, args.speed);
};

if (args.leftToRight) {
    width = textWidth * -1;
    width++;
    stop = offset;
} else {
    width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {     
    $(this).removeAttr("style");
}).mouseout(function () {
    $(this).marquee();
});
})(jQuery);

bootstrap responsive table content wrapping

EDIT

I think the reason that your table is not responsive to start with was you did not wrap in .container, .row and .col-md-x classes like this one

<div class="container">
   <div class="row">
     <div class="col-md-12">
     <!-- or use any other number .col-md- -->
         <div class="table-responsive">
             <div class="table">
             </div>
         </div>
     </div>
   </div>
</div>

With this, you can still use <p> tags and even make it responsive.

Please see the Bootply example here

SQL left join vs multiple tables on FROM line?

The second is preferred because it is far less likely to result in an accidental cross join by forgetting to put inthe where clause. A join with no on clause will fail the syntax check, an old style join with no where clause will not fail, it will do a cross join.

Additionally when you later have to a left join, it is helpful for maintenance that they all be in the same structure. And the old syntax has been out of date since 1992, it is well past time to stop using it.

Plus I have found that many people who exclusively use the first syntax don't really understand joins and understanding joins is critical to getting correct results when querying.

HTML/Javascript change div content

Assuming you're not using jQuery or some other library that makes this sort of thing easier for you, you can just use the element's innerHTML property.

document.getElementById("content").innerHTML = "whatever";

How to break out of the IF statement

You can return only if !something2 or use else return:

public void Method()
{
    if(something)
    {
        //some code
        if(something2)
        {
            //now I should break from ifs and go to te code outside ifs
        }
        if(!something2) // or else
            return;
    }
    // The code i want to go if the second if is true
}

How to select rows from a DataFrame based on column values

There are several ways to select rows from a Pandas dataframe:

  1. Boolean indexing (df[df['col'] == value] )
  2. Positional indexing (df.iloc[...])
  3. Label indexing (df.xs(...))
  4. df.query(...) API

Below I show you examples of each, with advice when to use certain techniques. Assume our criterion is column 'A' == 'foo'

(Note on performance: For each base type, we can keep things simple by using the Pandas API or we can venture outside the API, usually into NumPy, and speed things up.)


Setup

The first thing we'll need is to identify a condition that will act as our criterion for selecting rows. We'll start with the OP's case column_name == some_value, and include some other common use cases.

Borrowing from @unutbu:

import pandas as pd, numpy as np

df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})

1. Boolean indexing

... Boolean indexing requires finding the true value of each row's 'A' column being equal to 'foo', then using those truth values to identify which rows to keep. Typically, we'd name this series, an array of truth values, mask. We'll do so here as well.

mask = df['A'] == 'foo'

We can then use this mask to slice or index the data frame

df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

This is one of the simplest ways to accomplish this task and if performance or intuitiveness isn't an issue, this should be your chosen method. However, if performance is a concern, then you might want to consider an alternative way of creating the mask.


2. Positional indexing

Positional indexing (df.iloc[...]) has its use cases, but this isn't one of them. In order to identify where to slice, we first need to perform the same boolean analysis we did above. This leaves us performing one extra step to accomplish the same task.

mask = df['A'] == 'foo'
pos = np.flatnonzero(mask)
df.iloc[pos]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

3. Label indexing

Label indexing can be very handy, but in this case, we are again doing more work for no benefit

df.set_index('A', append=True, drop=False).xs('foo', level=1)

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

4. df.query() API

pd.DataFrame.query is a very elegant/intuitive way to perform this task, but is often slower. However, if you pay attention to the timings below, for large data, the query is very efficient. More so than the standard approach and of similar magnitude as my best suggestion.

df.query('A == "foo"')

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

My preference is to use the Boolean mask

Actual improvements can be made by modifying how we create our Boolean mask.

mask alternative 1 Use the underlying NumPy array and forgo the overhead of creating another pd.Series

mask = df['A'].values == 'foo'

I'll show more complete time tests at the end, but just take a look at the performance gains we get using the sample data frame. First, we look at the difference in creating the mask

%timeit mask = df['A'].values == 'foo'
%timeit mask = df['A'] == 'foo'

5.84 µs ± 195 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
166 µs ± 4.45 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Evaluating the mask with the NumPy array is ~ 30 times faster. This is partly due to NumPy evaluation often being faster. It is also partly due to the lack of overhead necessary to build an index and a corresponding pd.Series object.

Next, we'll look at the timing for slicing with one mask versus the other.

mask = df['A'].values == 'foo'
%timeit df[mask]
mask = df['A'] == 'foo'
%timeit df[mask]

219 µs ± 12.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
239 µs ± 7.03 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

The performance gains aren't as pronounced. We'll see if this holds up over more robust testing.


mask alternative 2 We could have reconstructed the data frame as well. There is a big caveat when reconstructing a dataframe—you must take care of the dtypes when doing so!

Instead of df[mask] we will do this

pd.DataFrame(df.values[mask], df.index[mask], df.columns).astype(df.dtypes)

If the data frame is of mixed type, which our example is, then when we get df.values the resulting array is of dtype object and consequently, all columns of the new data frame will be of dtype object. Thus requiring the astype(df.dtypes) and killing any potential performance gains.

%timeit df[m]
%timeit pd.DataFrame(df.values[mask], df.index[mask], df.columns).astype(df.dtypes)

216 µs ± 10.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.43 ms ± 39.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

However, if the data frame is not of mixed type, this is a very useful way to do it.

Given

np.random.seed([3,1415])
d1 = pd.DataFrame(np.random.randint(10, size=(10, 5)), columns=list('ABCDE'))

d1

   A  B  C  D  E
0  0  2  7  3  8
1  7  0  6  8  6
2  0  2  0  4  9
3  7  3  2  4  3
4  3  6  7  7  4
5  5  3  7  5  9
6  8  7  6  4  7
7  6  2  6  6  5
8  2  8  7  5  8
9  4  7  6  1  5

%%timeit
mask = d1['A'].values == 7
d1[mask]

179 µs ± 8.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Versus

%%timeit
mask = d1['A'].values == 7
pd.DataFrame(d1.values[mask], d1.index[mask], d1.columns)

87 µs ± 5.12 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

We cut the time in half.


mask alternative 3

@unutbu also shows us how to use pd.Series.isin to account for each element of df['A'] being in a set of values. This evaluates to the same thing if our set of values is a set of one value, namely 'foo'. But it also generalizes to include larger sets of values if needed. Turns out, this is still pretty fast even though it is a more general solution. The only real loss is in intuitiveness for those not familiar with the concept.

mask = df['A'].isin(['foo'])
df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

However, as before, we can utilize NumPy to improve performance while sacrificing virtually nothing. We'll use np.in1d

mask = np.in1d(df['A'].values, ['foo'])
df[mask]

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

Timing

I'll include other concepts mentioned in other posts as well for reference.

Code Below

Each column in this table represents a different length data frame over which we test each function. Each column shows relative time taken, with the fastest function given a base index of 1.0.

res.div(res.min())

                         10        30        100       300       1000      3000      10000     30000
mask_standard         2.156872  1.850663  2.034149  2.166312  2.164541  3.090372  2.981326  3.131151
mask_standard_loc     1.879035  1.782366  1.988823  2.338112  2.361391  3.036131  2.998112  2.990103
mask_with_values      1.010166  1.000000  1.005113  1.026363  1.028698  1.293741  1.007824  1.016919
mask_with_values_loc  1.196843  1.300228  1.000000  1.000000  1.038989  1.219233  1.037020  1.000000
query                 4.997304  4.765554  5.934096  4.500559  2.997924  2.397013  1.680447  1.398190
xs_label              4.124597  4.272363  5.596152  4.295331  4.676591  5.710680  6.032809  8.950255
mask_with_isin        1.674055  1.679935  1.847972  1.724183  1.345111  1.405231  1.253554  1.264760
mask_with_in1d        1.000000  1.083807  1.220493  1.101929  1.000000  1.000000  1.000000  1.144175

You'll notice that the fastest times seem to be shared between mask_with_values and mask_with_in1d.

res.T.plot(loglog=True)

Enter image description here

Functions

def mask_standard(df):
    mask = df['A'] == 'foo'
    return df[mask]

def mask_standard_loc(df):
    mask = df['A'] == 'foo'
    return df.loc[mask]

def mask_with_values(df):
    mask = df['A'].values == 'foo'
    return df[mask]

def mask_with_values_loc(df):
    mask = df['A'].values == 'foo'
    return df.loc[mask]

def query(df):
    return df.query('A == "foo"')

def xs_label(df):
    return df.set_index('A', append=True, drop=False).xs('foo', level=-1)

def mask_with_isin(df):
    mask = df['A'].isin(['foo'])
    return df[mask]

def mask_with_in1d(df):
    mask = np.in1d(df['A'].values, ['foo'])
    return df[mask]

Testing

res = pd.DataFrame(
    index=[
        'mask_standard', 'mask_standard_loc', 'mask_with_values', 'mask_with_values_loc',
        'query', 'xs_label', 'mask_with_isin', 'mask_with_in1d'
    ],
    columns=[10, 30, 100, 300, 1000, 3000, 10000, 30000],
    dtype=float
)

for j in res.columns:
    d = pd.concat([df] * j, ignore_index=True)
    for i in res.index:a
        stmt = '{}(d)'.format(i)
        setp = 'from __main__ import d, {}'.format(i)
        res.at[i, j] = timeit(stmt, setp, number=50)

Special Timing

Looking at the special case when we have a single non-object dtype for the entire data frame.

Code Below

spec.div(spec.min())

                     10        30        100       300       1000      3000      10000     30000
mask_with_values  1.009030  1.000000  1.194276  1.000000  1.236892  1.095343  1.000000  1.000000
mask_with_in1d    1.104638  1.094524  1.156930  1.072094  1.000000  1.000000  1.040043  1.027100
reconstruct       1.000000  1.142838  1.000000  1.355440  1.650270  2.222181  2.294913  3.406735

Turns out, reconstruction isn't worth it past a few hundred rows.

spec.T.plot(loglog=True)

Enter image description here

Functions

np.random.seed([3,1415])
d1 = pd.DataFrame(np.random.randint(10, size=(10, 5)), columns=list('ABCDE'))

def mask_with_values(df):
    mask = df['A'].values == 'foo'
    return df[mask]

def mask_with_in1d(df):
    mask = np.in1d(df['A'].values, ['foo'])
    return df[mask]

def reconstruct(df):
    v = df.values
    mask = np.in1d(df['A'].values, ['foo'])
    return pd.DataFrame(v[mask], df.index[mask], df.columns)

spec = pd.DataFrame(
    index=['mask_with_values', 'mask_with_in1d', 'reconstruct'],
    columns=[10, 30, 100, 300, 1000, 3000, 10000, 30000],
    dtype=float
)

Testing

for j in spec.columns:
    d = pd.concat([df] * j, ignore_index=True)
    for i in spec.index:
        stmt = '{}(d)'.format(i)
        setp = 'from __main__ import d, {}'.format(i)
        spec.at[i, j] = timeit(stmt, setp, number=50)

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I faced same issue when converting an eclipse project to Android studio.In my case i had the design lirary jar file in eclipse project and I have added dependency of the same in gradle caused the error.I solved it by deleting jar from libs.

How to save an image locally using Python whose URL address I already know?

Something fresh for Python 3 using Requests:

Comments in the code. Ready to use function.


import requests
from os import path

def get_image(image_url):
    """
    Get image based on url.
    :return: Image name if everything OK, False otherwise
    """
    image_name = path.split(image_url)[1]
    try:
        image = requests.get(image_url)
    except OSError:  # Little too wide, but work OK, no additional imports needed. Catch all conection problems
        return False
    if image.status_code == 200:  # we could have retrieved error page
        base_dir = path.join(path.dirname(path.realpath(__file__)), "images") # Use your own path or "" to use current working directory. Folder must exist.
        with open(path.join(base_dir, image_name), "wb") as f:
            f.write(image.content)
        return image_name

get_image("https://apod.nasddfda.gov/apod/image/2003/S106_Mishra_1947.jpg")

Define a global variable in a JavaScript function

Just declare it outside the functions, and assign values inside the functions. Something like:

<script type="text/javascript">
    var offsetfrommouse = [10, -20];
    var displayduration = 0;
    var obj_selected = 0;
    var trailimage = null ;  // Global variable
    function makeObj(address) {
        trailimage = [address, 50, 50];  // Assign value

Or simply removing "var" from your variable name inside function also makes it global, but it is better to declare it outside once for cleaner code. This will also work:

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;

function makeObj(address) {
    trailimage = [address, 50, 50];  // Global variable, assign value

I hope this example explains more: http://jsfiddle.net/qCrGE/

var globalOne = 3;
testOne();

function testOne()
{
    globalOne += 2;
    alert("globalOne is :" + globalOne );
    globalOne += 1;
}

alert("outside globalOne is: " + globalOne);

testTwo();

function testTwo()
{
    globalTwo = 20;
    alert("globalTwo is " + globalTwo);
    globalTwo += 5;
}

alert("outside globalTwo is:" + globalTwo);

Eclipse - "Workspace in use or cannot be created, chose a different one."

Right answer can be found in this (duplicate) question.

I reproduced the answer here (and it works!):

Just delete the .lock file in the .metadata directory in your eclipse workspace directory

ASP.NET MVC ActionLink and post method

This has been a difficult problem for me to solve. How can I build a dynamic link in razor and html that can call an action method and pass a value or values to a specific action method? I considered several options including a custom html helper. I just came up with a simple and elegant solution.

The view

@model IEnumerable<MyMvcApp.Models.Product>

@using (Html.BeginForm()) {

     <table>
         <thead>
             <tr>
                 <td>Name</td>
                 <td>Price</td>
                 <td>Quantity</td>
            </tr>
        </thead>
        @foreach (Product p in Model.Products)
        {
            <tr>
                <td><a href="@Url.Action("Edit", "Product", p)">@p.Name</a></td>
                <td>@p.Price.ToString()</td>
                <td>@p.Quantity.ToString()</td>
            </tr>
         }
    </table>
}

The action method

public ViewResult Edit(Product prod)
{
    ContextDB contextDB = new ContextDB();

    Product product = contextDB.Products.Single(p => p.ProductID == prod.ProductId);

    product = prod;

    contextDB.SaveChanges();

    return View("Edit");
}

The point here is that Url.Action does not care whether the action method is a GET or a POST. It will access either type of method. You can pass your data to the action method using

@Url.Action(string actionName, string controllerName, object routeValues)

the routeValues object. I have tried this and it works. No, you are not technically doing a post or submitting the form but if the routeValues object contains your data, it doesnt matter if its a post or a get. You can use a particular action method signature to select the right method.

HTML entity for the middle dot

There's actually seven variants of this:

    char   description          unicode   html       html entity    utf-8

    ·      Middle Dot           U+00B7    &#183;     &middot;       C2 B7
    ·      Greek Ano Teleia     U+0387    &#903;                    CE 87
    •      Bullet               U+2022    &#8226;    &bull;         E2 80 A2
    ‧      Hyphenation Point    U+2027    &#8321;                   E2 80 A7
    ∙      Bullet Operator      U+2219    &#8729;                   E2 88 99
    ●      Black Circle         U+25CF    &#9679;                   E2 97 8F
    ⬤     Black Large Circle   U+2B24    &#11044;                  E2 AC A4

Depending on your viewing application or font, the Bullet Operator may seem very similar to either the Middle Dot or the Bullet.