Programs & Examples On #Key value

A key-value pair is a set of two linked data items: a key which uniquely identifies some item of data, and the value, which is either the data that is identified or a pointer to the location of that data. Key-value pairs are frequently used in lookup tables, hash tables and configuration files.

Java Class that implements Map and keeps insertion order?

You can use LinkedHashMap to main insertion order in Map

The important points about Java LinkedHashMap class are:

  1. It contains onlyunique elements.
  2. A LinkedHashMap contains values based on the key 3.It may have one null key and multiple null values. 4.It is same as HashMap instead maintains insertion order

    public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> 
    

But if you want sort values in map using User-defined object or any primitive data type key then you should use TreeMap For more information, refer this link

How to update value of a key in dictionary in c#?

Have you tried just

dictionary["cat"] = 5;

:)

Update

dictionary["cat"] = 5+2;
dictionary["cat"] = dictionary["cat"]+2;
dictionary["cat"] += 2;

Beware of non-existing keys :)

How to remove elements from a generic list while iterating over it?

For loops are a bad construct for this.

Using while

var numbers = new List<int>(Enumerable.Range(1, 3));

while (numbers.Count > 0)
{
    numbers.RemoveAt(0);
}

But, if you absolutely must use for

var numbers = new List<int>(Enumerable.Range(1, 3));

for (; numbers.Count > 0;)
{
    numbers.RemoveAt(0);
}

Or, this:

public static class Extensions
{

    public static IList<T> Remove<T>(
        this IList<T> numbers,
        Func<T, bool> predicate)
    {
        numbers.ForEachBackwards(predicate, (n, index) => numbers.RemoveAt(index));
        return numbers;
    }

    public static void ForEachBackwards<T>(
        this IList<T> numbers,
        Func<T, bool> predicate,
        Action<T, int> action)
    {
        for (var i = numbers.Count - 1; i >= 0; i--)
        {
            if (predicate(numbers[i]))
            {
                action(numbers[i], i);
            }
        }
    }
}

Usage:

var numbers = new List<int>(Enumerable.Range(1, 10)).Remove((n) => n > 5);

Get index of a key/value pair in a C# dictionary based on the value

Let's say you have a Dictionary called fooDictionary

fooDictionary.Values.ToList().IndexOf(someValue);

Values.ToList() converts your dictionary values into a List of someValue objects.

IndexOf(someValue) searches your new List looking for the someValue object in question and returns the Index which would match the index of the Key/Value pair in the dictionary.

This method does not care about the dictionary keys, it simply returns the index of the value that you are looking for.

This does not however account for the issue that there may be several matching "someValue" objects.

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny is actually a good name):

def getAny(dic, keys, default=None):
    return (keys or default) and dic.get(keys[0], 
                                         getAny( dic, keys[1:], default=default))

or even better, without recursion and more clear:

def getAny(dic, keys, default=None):
    for k in keys: 
        if k in dic:
           return dic[k]
    return default

Then that could be used in a way similar to the dict.get method, like:

getAny(myDict, keySet)

and even have a default result in case of no keys found at all:

getAny(myDict, keySet, "not found")

How to push both key and value into an Array in Jquery

This code

var title = news.title;
var link = news.link;
arr.push({title : link});

is not doing what you think it does. What gets pushed is a new object with a single member named "title" and with link as the value ... the actual title value is not used. To save an object with two fields you have to do something like

arr.push({title:title, link:link});

or with recent Javascript advances you can use the shortcut

arr.push({title, link}); // Note: comma "," and not colon ":"

If instead you want the key of the object to be the content of the variable title you can use

arr.push({[title]: link}); // Note that title has been wrapped in brackets

Iterate through dictionary values?

Create the opposite dictionary:

PIX1 = {}
for key in PIX0.keys():
    PIX1[PIX0.get(key)] = key

Then run the same code on this dictionary instead (using PIX1 instead of PIX0).

BTW, I'm not sure about Python 3, but in Python 2 you need to use raw_input instead of input.

How can I get key's value from dictionary in Swift?

From Apple Docs

You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

https://developer.apple.com/documentation/swift/dictionary

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."

PHP create key => value pairs within a foreach

Create key-value pairs within a foreach like this:

function createOfferUrlArray($Offer) {
    $offerArray = array();

    foreach ($Offer as $key => $value) {
        $offerArray[$key] = $value[4];
    }

    return $offerArray;
}

How do you create a dictionary in Java?

You'll want a Map<String, String>. Classes that implement the Map interface include (but are not limited to):

Each is designed/optimized for certain situations (go to their respective docs for more info). HashMap is probably the most common; the go-to default.

For example (using a HashMap):

Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.println(map.get("dog"));
type of animal

How to search if dictionary value contains certain string with Python

import re
for i in range(len(myDict.values())):
     for j in range(len(myDict.values()[i])):
             match=re.search(r'Mary', myDict.values()[i][j])
             if match:
                     print match.group() #Mary
                     print myDict.keys()[i] #firstName
                     print myDict.values()[i][j] #Mary-Ann

How to create dictionary and add key–value pairs dynamically?

var dict = []; // create an empty array

dict.push({
    key:   "keyName",
    value: "the value"
});
// repeat this last part as needed to add more key/value pairs

Basically, you're creating an object literal with 2 properties (called key and value) and inserting it (using push()) into the array.


Edit: So almost 5 years later, this answer is getting downvotes because it's not creating an "normal" JS object literal (aka map, aka hash, aka dictionary).
It is however creating the structure that OP asked for (and which is illustrated in the other question linked to), which is an array of object literals, each with key and value properties. Don't ask me why that structure was required, but it's the one that was asked for.

But, but, if what you want in a plain JS object - and not the structure OP asked for - see tcll's answer, though the bracket notation is a bit cumbersome if you just have simple keys that are valid JS names. You can just do this:

// object literal with properties
var dict = {
  key1: "value1",
  key2: "value2"
  // etc.
};

Or use regular dot-notation to set properties after creating an object:

// empty object literal with properties added afterward
var dict = {};
dict.key1 = "value1";
dict.key2 = "value2";
// etc.

You do want the bracket notation if you've got keys that have spaces in them, special characters, or things like that. E.g:

var dict = {};

// this obviously won't work
dict.some invalid key (for multiple reasons) = "value1";

// but this will
dict["some invalid key (for multiple reasons)"] = "value1";

You also want bracket notation if your keys are dynamic:

dict[firstName + " " + lastName] = "some value";

Note that keys (property names) are always strings, and non-string values will be coerced to a string when used as a key. E.g. a Date object gets converted to its string representation:

dict[new Date] = "today's value";

console.log(dict);
// => {
//      "Sat Nov 04 2016 16:15:31 GMT-0700 (PDT)": "today's value"
//    }

Note however that this doesn't necessarily "just work", as many objects will have a string representation like "[object Object]" which doesn't make for a non-unique key. So be wary of something like:

var objA = { a: 23 },
    objB = { b: 42 };

dict[objA] = "value for objA";
dict[objB] = "value for objB";

console.log(dict);
// => { "[object Object]": "value for objB" }

Despite objA and objB being completely different and unique elements, they both have the same basic string representation: "[object Object]".

The reason Date doesn't behave like this is that the Date prototype has a custom toString method which overrides the default string representation. And you can do the same:

// a simple constructor with a toString prototypal method
function Foo() {
  this.myRandomNumber = Math.random() * 1000 | 0;
}

Foo.prototype.toString = function () {
  return "Foo instance #" + this.myRandomNumber;
};

dict[new Foo] = "some value";

console.log(dict);
// => {
//      "Foo instance #712": "some value"
//    }

(Note that since the above uses a random number, name collisions can still occur very easily. It's just to illustrate an implementation of toString.)

So when trying to use objects as keys, JS will use the object's own toString implementation, if any, or use the default string representation.

Java - How to create new Entry (key, value)

Example of AbstractMap.SimpleEntry:

import java.util.Map; 
import java.util.AbstractMap;
import java.util.AbstractMap.SimpleEntry;

Instantiate:

ArrayList<Map.Entry<Integer, Integer>> arr = 
    new ArrayList<Map.Entry<Integer, Integer>>();

Add rows:

arr.add(new AbstractMap.SimpleEntry(2, 3));
arr.add(new AbstractMap.SimpleEntry(20, 30));
arr.add(new AbstractMap.SimpleEntry(2, 4));

Fetch rows:

System.out.println(arr.get(0).getKey());
System.out.println(arr.get(0).getValue());
System.out.println(arr.get(1).getKey());
System.out.println(arr.get(1).getValue());
System.out.println(arr.get(2).getKey());
System.out.println(arr.get(2).getValue());

Should print:

2
3
20
30
2
4

It's good for defining edges of graph structures. Like the ones between neurons in your head.

How to iterate over associative arrays in Bash

You can access the keys with ${!array[@]}:

bash-4.0$ echo "${!array[@]}"
foo bar

Then, iterating over the key/value pairs is easy:

for i in "${!array[@]}"
do
  echo "key :" $i
  echo "value:" ${array[$i]}
done

The default for KeyValuePair

From your original code it looks like what you want is to check if the list was empty:

var getResult= keyValueList.SingleOrDefault();
if (keyValueList.Count == 0)
{
   /* default */
}
else
{
}

How to loop through key/value object in Javascript?

Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty() method. This is generally a good idea when using for...in loops:

var user = {};

function setUsers(data) {
    for (var k in data) {
        if (data.hasOwnProperty(k)) {
           user[k] = data[k];
        }
    }
}

Get selected key/value of a combo box using jQuery

I assume by "key" and "value" you mean:

<select>
    <option value="KEY">VALUE</option>
</select>

If that's the case, this will get you the "VALUE":

$(this).find('option:selected').text();

And you can get the "KEY" like this:

$(this).find('option:selected').val();

How to add a new object (key-value pair) to an array in javascript?

.push() will add elements to the end of an array.

Use .unshift() if need to add some element to the beginning of array i.e:

items.unshift({'id':5});

Demo:

_x000D_
_x000D_
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.unshift({'id': 0});_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

And use .splice() in case you want to add object at a particular index i.e:

items.splice(2, 0, {'id':5});
           // ^ Given object will be placed at index 2...

Demo:

_x000D_
_x000D_
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.splice(2, 0, {'id': 2.5});_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

how to prevent adding duplicate keys to a javascript array

var a = [1,2,3], b = [4,1,5,2];

b.forEach(function(value){
  if (a.indexOf(value)==-1) a.push(value);
});

console.log(a);
// [1, 2, 3, 4, 5]

For more details read up on Array.indexOf.

If you want to rely on jQuery, instead use jQuery.inArray:

$.each(b,function(value){
  if ($.inArray(value,a)==-1) a.push(value);
});

If all your values are simply and uniquely representable as strings, however, you should use an Object instead of an Array, for a potentially massive speed increase (as described in the answer by @JonathanSampson).

A KeyValuePair in Java

The class AbstractMap.SimpleEntry is generic and can be useful.

How to count frequency of characters in a string?

Please try the given code below, hope it will helpful to you,

import java.util.Scanner;

class String55 {
    public static int frequency(String s1,String s2)
    {

        int count=0;
        char ch[]=s1.toCharArray();
        char ch1[]=s2.toCharArray();
        for (int i=0;i<ch.length-1; i++)
        {



                int k=i;

                int j1=i+1;
                int j=0;
                int j11=j;
                int j2=j+1;
                {
                    while(k<ch.length && j11<ch1.length && ch[k]==ch1[j11])
                    {
                    k++;
                    j11++;

                    }


                int l=k+j1;
                int m=j11+j2;
                if( l== m)
                {
                    count=1;
                    count++;
                }





        }
        }
        return count;


    }
    public static void main (String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter the pattern");
        String s1=sc.next();
            System.out.println("enter the String");
            String s2=sc.next();
            int res=frequency(s1, s2);
            System.out.println("FREQUENCY==" +res);

    }
}

SAMPLE OUTPUT: enter the pattern man enter the String dhimanman FREQUENCY==2

Thank-you.Happy coding.

append multiple values for one key in a dictionary

You would be best off using collections.defaultdict (added in Python 2.5). This allows you to specify the default object type of a missing key (such as a list).

So instead of creating a key if it doesn't exist first and then appending to the value of the key, you cut out the middle-man and just directly append to non-existing keys to get the desired result.

A quick example using your data:

>>> from collections import defaultdict
>>> data = [(2010, 2), (2009, 4), (1989, 8), (2009, 7)]
>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> for year, month in data:
...     d[year].append(month)
... 
>>> d
defaultdict(<type 'list'>, {2009: [4, 7], 2010: [2], 1989: [8]})

This way you don't have to worry about whether you've seen a digit associated with a year or not. You just append and forget, knowing that a missing key will always be a list. If a key already exists, then it will just be appended to.

Storing a Key Value Array into a compact JSON string

So why don't you simply use a key-value literal?

var params = {
    'slide0001.html': 'Looking Ahead',
    'slide0002.html': 'Forecase',
    ...
};

return params['slide0001.html']; // returns: Looking Ahead

Where does PostgreSQL store the database?

On Mac: /Library/PostgreSQL/9.0/data/base

The directory can't be entered, but you can look at the content via: sudo du -hc data

No module named 'openpyxl' - Python 3.4 - Ubuntu

I still was not able to import 'openpyxl' after successfully installing it via both conda and pip. I discovered that it was installed in '/usr/lib/python3/dist-packages', so this https://stackoverflow.com/a/59861933/10794682 worked for me:

import sys 
sys.path.append('/usr/lib/python3/dist-packages')

Hope this might be useful for others.

SQL Call Stored Procedure for each Row without using a cursor

This is a variation of n3rds solution above. No sorting by using ORDER BY is needed, as MIN() is used.

Remember that CustomerID (or whatever other numerical column you use for progress) must have a unique constraint. Furthermore, to make it as fast as possible CustomerID must be indexed on.

-- Declare & init
DECLARE @CustomerID INT = (SELECT MIN(CustomerID) FROM Sales.Customer); -- First ID
DECLARE @Data1 VARCHAR(200);
DECLARE @Data2 VARCHAR(200);

-- Iterate over all customers
WHILE @CustomerID IS NOT NULL
BEGIN  

  -- Get data based on ID
  SELECT @Data1 = Data1, @Data2 = Data2
    FROM Sales.Customer
    WHERE [ID] = @CustomerID ;

  -- call your sproc
  EXEC dbo.YOURSPROC @Data1, @Data2

  -- Get next customerId
  SELECT @CustomerID = MIN(CustomerID)
    FROM Sales.Customer
    WHERE CustomerID > @CustomerId 

END

I use this approach on some varchars I need to look over, by putting them in a temporary table first, to give them an ID.

How can I make a button redirect my page to another page?

you could do so:

<button onclick="location.href='page'">

you could change the action attribute of the form on click the button:

<button class="float-left submit-button" onclick='myFun()'>Home</button>

<script>
myFun(){
$('form').attr('action','new path');
}
</script>

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

I have IntelliJ IDEA 12.x on the Mac and I use Maven 3 and I get the red highlighting over my code even though the Maven build is fine. None of the above (re-indexing, force import, etc.) worked for me. I had to do the following:

Intellij -> Preferences -> Maven -> Importing
    [ ] Use Maven3 to import projects

I have to check the Maven3 import option and that fixes the issue.

Delete last commit in bitbucket

In the first place, if you are working with other people on the same code repository, you should not delete a commit since when you force the update on the repository it will leave the local repositories of your coworkers in an illegal state (e.g. if they made commits after the one you deleted, those commits will be invalid since they were based on a now non-existent commit).

Said that, what you can do is revert the commit. This procedure is done differently (different commands) depending on the CVS you're using:

On git:

git revert <commit>

On mercurial:

hg backout <REV>

EDIT: The revert operation creates a new commit that does the opposite than the reverted commit (e.g. if the original commit added a line, the revert commit deletes that line), effectively removing the changes of the undesired commit without rewriting the repository history.

Get all mysql selected rows into an array

$name=array(); 
while($result=mysql_fetch_array($res)) {
    $name[]=array('Id'=>$result['id']); 
    // here you want to fetch all 
    // records from table like this. 
    // then you should get the array 
    // from all rows into one array 
}

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Quickest way to convert XML to JSON in Java

I have uploaded the project you can directly open in eclipse and run that's all https://github.com/pareshmutha/XMLToJsonConverterUsingJAVA

Thank You

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

Update Fragment from ViewPager

You can update the fragment in two different ways,

First way

like @Sajmon

You need to implement getItemPosition(Object obj) method.

This method is called when you call

notifyDataSetChanged()

You can find a example in Github and more information in this post.

enter image description here

Second way

My approach to update fragments within the viewpager is to use the setTag() method for any instantiated view in the instantiateItem() method. So when you want to change the data or invalidate the view that you need, you can call the findViewWithTag() method on the ViewPager to retrieve the previously instantiated view and modify/use it as you want without having to delete/create a new view each time you want to update some value.

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Object object = super.instantiateItem(container, position);
    if (object instanceof Fragment) {
        Fragment fragment = (Fragment) object;
        String tag = fragment.getTag();
        mFragmentTags.put(position, tag);
    }
    return object;
}

public Fragment getFragment(int position) {
    Fragment fragment = null;
    String tag = mFragmentTags.get(position);
    if (tag != null) {
        fragment = mFragmentManager.findFragmentByTag(tag);
    }
    return fragment;
}

You can find a example in Github or more information in this post:

enter image description here

Change label text using JavaScript

Have you tried .innerText or .value instead of .innerHTML?

Recursive mkdir() system call on Unix

There is not a system call to do it for you, unfortunately. I'm guessing that's because there isn't a way to have really well-defined semantics for what should happen in error cases. Should it leave the directories that have already been created? Delete them? What if the deletions fail? And so on...

It is pretty easy to roll your own, however, and a quick google for 'recursive mkdir' turned up a number of solutions. Here's one that was near the top:

http://nion.modprobe.de/blog/archives/357-Recursive-directory-creation.html

static void _mkdir(const char *dir) {
        char tmp[256];
        char *p = NULL;
        size_t len;

        snprintf(tmp, sizeof(tmp),"%s",dir);
        len = strlen(tmp);
        if(tmp[len - 1] == '/')
                tmp[len - 1] = 0;
        for(p = tmp + 1; *p; p++)
                if(*p == '/') {
                        *p = 0;
                        mkdir(tmp, S_IRWXU);
                        *p = '/';
                }
        mkdir(tmp, S_IRWXU);
}

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I faced a similar problem but in my case I was trying to install Visual C++ Redistributable for Visual Studio 2015 Update 1 on Windows Server 2012 R2. However the root cause should be the same.

In short, you need to install the prerequisites of KB2999226.

In more details, the installation log I got stated that the installation for Windows Update KB2999226 failed. According to the Microsoft website here:

Prerequisites To install this update, you must have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) installed in Windows 8.1 or Windows Server 2012 R2. Or, install Service Pack 1 for Windows 7 or Windows Server 2008 R2. Or, install Service Pack 2 for Windows Vista and for Windows Server 2008.

After I have installed April 2014 on my Windows Server 2012 R2, I am able to install the Visual C++ Redistributable correctly.

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

Applying CSS styles to all elements inside a DIV

Alternate solution. Include your external CSS in your HTML file by

<link rel="stylesheet" href="css/applyCSS.css"/> 

inside the applyCSS.css:

   #applyCSS {
      /** Your Style**/
    }

Remove characters from C# string

Its a powerful method I usually use in the same case:

private string Normalize(string text)
{
        return string.Join("",
            from ch in text
            where char.IsLetterOrDigit(ch) || char.IsWhiteSpace(ch)
            select ch);
}

Enjoy...

Converting Integer to Long

((Number) intOrLongOrSomewhat).longValue()

How can I test a change made to Jenkinsfile locally?

As far as i know this Pipeline Plugin is the "Engine" of the new Jenkinsfile mechanics, so im quite positive you could use this to locally test your scripts.

Im not sure if there is any additional steps needed when you copy it into a Jenkinsfile, however the syntax etc should be exactly the same.

Edit: Found the reference on the "engine", check this feature description, last paragraph, first entry.

How to update record using Entity Framework 6?

I know it has been answered good few times already, but I like below way of doing this. I hope it will help someone.

//attach object (search for row)
TableName tn = _context.TableNames.Attach(new TableName { PK_COLUMN = YOUR_VALUE});
// set new value
tn.COLUMN_NAME_TO_UPDATE = NEW_COLUMN_VALUE;
// set column as modified
_context.Entry<TableName>(tn).Property(tnp => tnp.COLUMN_NAME_TO_UPDATE).IsModified = true;
// save change
_context.SaveChanges();

Tracking changes in Windows registry

Regshot deserves a mention here. It scans and takes a snapshot of all registry settings, then you run it again at a later time to compare with the original snapshot, and it shows you all the keys and values that have changed.

What is a good pattern for using a Global Mutex in C#?

Neither Mutex nor WinApi CreateMutex() works for me.

An alternate solution:

static class Program
{
    [STAThread]
    static void Main()
    {
        if (SingleApplicationDetector.IsRunning()) {
            return;
        }

        Application.Run(new MainForm());

        SingleApplicationDetector.Close();
    }
}

And the SingleApplicationDetector:

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Threading;

public static class SingleApplicationDetector
{
    public static bool IsRunning()
    {
        string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
        var semaphoreName = @"Global\" + guid;
        try {
            __semaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize);

            Close();
            return true;
        }
        catch (Exception ex) {
            __semaphore = new Semaphore(0, 1, semaphoreName);
            return false;
        }
    }

    public static void Close()
    {
        if (__semaphore != null) {
            __semaphore.Close();
            __semaphore = null;
        }
    }

    private static Semaphore __semaphore;
}

Reason to use Semaphore instead of Mutex:

The Mutex class enforces thread identity, so a mutex can be released only by the thread that acquired it. By contrast, the Semaphore class does not enforce thread identity.

<< System.Threading.Mutex

Ref: Semaphore.OpenExisting()

API vs. Webservice

Think of Web service as a web api. API is such a general term now so a web service is an interface to functionality, usually business related, that you can get to from the network over a variety of protocols.

How does one parse XML files?

You can use XmlDocument and for manipulating or retrieve data from attributes you can Linq to XML classes.

List all employee's names and their managers by manager name using an inner join

select e.ename as Employee, m.ename as Manager
from emp e, emp m
where e.mgr = m.empno

If you want to get the result for all the records (irrespective of whether they report to anyone or not), append (+) on the second table's name

select e.ename as Employee, m.ename as Manager
from emp e, emp m
where e.mgr = m.empno(+)

How can I install Apache Ant on Mac OS X?

If you have MacPorts installed (https://www.macports.org/), do this:

sudo port install apache-ant

What is the difference between WCF and WPF?

WCF = Windows Communication Foundation is used to build service-oriented applications. WPF = Windows Presentation Foundation is used to write platform-independent applications.

How Can I Truncate A String In jQuery?

with prototype and without space :

 String.prototype.trimToLength = function (trimLenght) {
    return this.length > trimLenght ? this.substring(0, trimLenght - 3) + '...' : this
};

Hidden TextArea

<textarea name="hide" style="display:none;"></textarea>

This sets the css display property to none, which prevents the browser from rendering the textarea.

How do I change a TCP socket to be non-blocking?

If you want to change socket to non blocking , precisely accept() to NON-Blocking state then

    int flags=fcntl(master_socket, F_GETFL);
        fcntl(master_socket, F_SETFL,flags| O_NONBLOCK); /* Change the socket into non-blocking state  F_SETFL is a command saying set flag and flag is 0_NONBLOCK     */                                          

while(1){
    if((newSocket = accept(master_socket, (struct sockaddr *) &address, &addr_size))<0){
                if(errno==EWOULDBLOCK){
                       puts("\n No clients currently available............ \n");
                       continue;
               }
    }else{
          puts("\nClient approched............ \n");
    }

}

Delete rows with blank values in one particular column

It is the same construct - simply test for empty strings rather than NA:

Try this:

df <- df[-which(df$start_pc == ""), ]

In fact, looking at your code, you don't need the which, but use the negation instead, so you can simplify it to:

df <- df[!(df$start_pc == ""), ]
df <- df[!is.na(df$start_pc), ]

And, of course, you can combine these two statements as follows:

df <- df[!(df$start_pc == "" | is.na(df$start_pc)), ]

And simplify it even further with with:

df <- with(df, df[!(start_pc == "" | is.na(start_pc)), ])

You can also test for non-zero string length using nzchar.

df <- with(df, df[!(nzchar(start_pc) | is.na(start_pc)), ])

Disclaimer: I didn't test any of this code. Please let me know if there are syntax errors anywhere

What is a .pid file and what does it contain?

Pidfile contains pid of a process. It is a convention allowing long running processes to be more self-aware. Server process can inspect it to stop itself, or have heuristic that its other instance is already running. Pidfiles can also be used to conventiently kill risk manually, e.g. pkill -F <some.pid>

How to change the docker image installation directory?

Don't use a symbolic Link to move the docker folder to /mnt (for example). This may cause in trouble with the docker rm command.

Better use the -g Option for docker. On Ubuntu you can set it permanently in /etc/default/docker.io. Enhance or replace the DOCKER_OPTS Line.

Here an example: `DOCKER_OPTS="-g /mnt/somewhere/else/docker/"

jQuery disable a link

This works for links that have the onclick attribute set inline. This also allows you to later remove the "return false" in order to enable it.

        //disable all links matching class
        $('.yourLinkClass').each(function(index) {
            var link = $(this);
            var OnClickValue = link.attr("onclick");
            link.attr("onclick", "return false; " + OnClickValue);
        });

        //enable all edit links
        $('.yourLinkClass').each(function (index) {
            var link = $(this);
            var OnClickValue = link.attr("onclick");
            link.attr("onclick", OnClickValue.replace("return false; ", ""));
        });

Get Windows version in a batch file

@echo off
for /f "tokens=2 delims=:" %%a in ('systeminfo ^| find "OS Name"') do set OS_Name=%%a
for /f "tokens=* delims= " %%a in ("%OS_Name%") do set OS_Name=%%a
for /f "tokens=3 delims= " %%a in ("%OS_Name%") do set OS_Name=%%a
if "%os_name%"=="XP" set version=XP
if "%os_name%"=="7" set version=7

This will grab the OS name as "7" or "XP"

Then you can use this in a variable to do certain commands based on the version of windows.

Android: converting String to int

barcode often consist of large number so i think your app crashes because of the size of the string that you are trying to convert to int. you can use BigInteger

BigInteger reallyBig = new BigInteger(myString);

Change <select>'s option and trigger events with JavaScript

Fiddle of my solution is here. But just in case it expires I will paste the code as well.

HTML:

<select id="sel">
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" id="button" value="Change option to 2" />

JS:

var sel = document.getElementById('sel'),
    button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;

    // firing the event properly according to StackOverflow
    // http://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually
    if ("createEvent" in document) {
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent("change", false, true);
        sel.dispatchEvent(evt);
    }
    else {
        sel.fireEvent("onchange");
    }
});

sel.addEventListener('change', function (e) {
    alert('changed');
});

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema

Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from 
USER_CONSTRAINTS;

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

Read specific columns from a csv file with csv module?

Context: For this type of work you should use the amazing python petl library. That will save you a lot of work and potential frustration from doing things 'manually' with the standard csv module. AFAIK, the only people who still use the csv module are those who have not yet discovered better tools for working with tabular data (pandas, petl, etc.), which is fine, but if you plan to work with a lot of data in your career from various strange sources, learning something like petl is one of the best investments you can make. To get started should only take 30 minutes after you've done pip install petl. The documentation is excellent.

Answer: Let's say you have the first table in a csv file (you can also load directly from the database using petl). Then you would simply load it and do the following.

from petl import fromcsv, look, cut, tocsv 

#Load the table
table1 = fromcsv('table1.csv')
# Alter the colums
table2 = cut(table1, 'Song_Name','Artist_ID')
#have a quick look to make sure things are ok. Prints a nicely formatted table to your console
print look(table2)
# Save to new file
tocsv(table2, 'new.csv')

Max or Default?

Sounds like a case for DefaultIfEmpty (untested code follows):

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter).DefaultIfEmpty.Max

How can I autoformat/indent C code in vim?

Maybe you can try the followings $indent -kr -i8 *.c

Hope it's useful for you!

What is DOM Event delegation?

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

See this link --> http://www.akadia.com/services/dotnet_delegates_and_events.html

Where can I find my Facebook application id and secret key?

Dashboard -> [your app] -> [View Details] -> Settings -> Basic

source

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

How to convert an ASCII character into an int in C

Are you searching for this:

int c = some_ascii_character;

Or just converting without assignment:

(int)some_aschii_character;

How to get a reversed list view on a list in Java?

I use this:

public class ReversedView<E> extends AbstractList<E>{

    public static <E> List<E> of(List<E> list) {
        return new ReversedView<>(list);
    }

    private final List<E> backingList;

    private ReversedView(List<E> backingList){
        this.backingList = backingList;
    }

    @Override
    public E get(int i) {
        return backingList.get(backingList.size()-i-1);
    }

    @Override
    public int size() {
        return backingList.size();
    }

}

like this:

ReversedView.of(backingList) // is a fully-fledged generic (but read-only) list

window.open(url, '_blank'); not working on iMac/Safari

You can't rely on window.open because browsers may have different policies. I had the same issue and I used the code below instead.

let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = <your_url>;
a.download = <your_fileName>;
a.click();
document.body.removeChild(a);

Combining C++ and C - how does #ifdef __cplusplus work?

A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code

Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.

The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.

The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.

One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.

Hex-encoded String to Byte Array

I think what the questioner is after is converting the string representation of a hexadecimal value to a byte array representing that hexadecimal value.

The apache commons-codec has a class for that, Hex.

String s = "9B7D2C34A366BF890C730641E6CECF6F";    
byte[] bytes = Hex.decodeHex(s.toCharArray());

Clear terminal in Python

This function works in gnome-terminal because, by default, it recognizes ANSI escape sequences. It gives you a CLEAN PROMPT rows_max distance from the bottom of the terminal, but also precisely from where it was called. Gives you complete control over how much to clear.

def clear(rows=-1, rows_max=None, *, calling_line=True, absolute=None,
          store_max=[]):
    """clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up"""
    from os import linesep
    if rows_max and rows_max != -1:
        store_max[:] = [rows_max, False]
    elif not store_max or store_max[1] or rows_max == -1 or absolute:
        try:
            from shutil import get_terminal_size
            columns_max, rows_max = get_terminal_size()
        except ImportError:
            columns_max, rows_max = 80, 24
        if absolute is None:
            store_max[:] = [rows_max, True]
    if store_max:
        if rows == -1:
            rows = store_max[0]
        elif isinstance(rows, float):
            rows = round(store_max[0] * rows)
        if rows > store_max[0] - 2:
            rows = store_max[0] - 2
    if absolute is None:
        s = ('\033[1A' + ' ' * 30 if calling_line else '') + linesep * rows
    else:
        s = '\033[{}A'.format(absolute + 2) + linesep
        if absolute > rows_max - 2:
            absolute = rows_max - 2
        s += (' ' * columns_max + linesep) * absolute + ' ' * columns_max
        rows = absolute
    print(s + '\033[{}A'.format(rows + 1))

Implementation:

clear() # Clear all, TRIES to automatically get terminal height
clear(800, 24) # Clear all, set 24 as terminal (max) height
clear(12) # Clear half of terminal below if 24 is its height
clear(1000) # Clear to terminal height - 2 (24 - 2)
clear(0.5) # float factor 0.0 - 1.0 of terminal height (0.5 * 24 = 12)
clear() # Clear to rows_max - 2 of user given rows_max (24 - 2)
clear(0, 14) # Clear line, reset rows_max to half of 24 (14-2)
clear(0) # Just clear the line
clear(0, -1) # Clear line, restore auto-determining rows_max
clear(calling_line=False) # Clear all, don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up

Parameters: rows is the number of clear text rows to add between prompt and bottom of terminal, pushing everything up. rows_max is the height of the terminal (or max clearing height) in text rows, and only needs to be set once, but can be reset at any time. *, in the third parameter position means all following parameters are keyword only (e.g., clear(absolute=5)). calling_line=True (default) works better in Interactive mode. calling_line=False works better for text-based, terminal applications. absolute was added to try to fix glitchy gap problems in Interactive mode after reducing size of terminal, but can also be used for terminal applications. store_max is just for secret, "persistent" storage of rows_max value; don't explicitly use this parameter. (When an argument is not passed for store_max, changing the list contents of store_max changes this parameter's default value. Hence, persistent storage.)

Portability: Sorry, this doesn't work in IDLE, but it works >> VERY COOL << in Interactive mode in a terminal (console) that recognizes ANSI escape sequences. I only tested this in Ubuntu 13.10 using Python 3.3 in gnome-terminal. So I can only assume portability is dependant upon Python 3.3 (for the shutil.get_terminal_size() function for BEST results) and ANSI recognition. The print(...) function is Python 3. I also tested this with a simple, text-based, terminal Tic Tac Toe game (application).

For use in Interactive mode: First copy and paste the copy(...) function in Interactive mode and see if it works for you. If so, then put the above function into a file named clear.py . In the terminal start python, with 'python3'. Enter:

>>> import sys
>>> sys.path
['', '/usr/lib/python3.3', ...

Now drop the clear.py file into one of the path directories listed so that Python can find it (don't overwrite any existing files). To easily use from now on:

>>> from clear import clear
>>> clear()
>>> print(clear.__doc__)
clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up

For use in a terminal application: Put the copy(...) function into a file named clear.py in the same folder with your main.py file. Here is a working abstract (skeleton) example from a Tic Tac Toe game application (run from terminal prompt: python3 tictactoe.py):

from os import linesep

class TicTacToe:    
    def __init__(self):
        # Clear screen, but not calling line
        try:
            from clear import clear
            self.clear = clear
            self.clear(calling_line=False)
        except ImportError:
            self.clear = False
        self.rows = 0    # Track printed lines to clear

        # ...
        self.moves = [' '] * 9

    def do_print(self, *text, end=linesep):
        text = list(text)
        for i, v in enumerate(text[:]):
            text[i] = str(v)
        text = ' '.join(text)
        print(text, end=end)
        self.rows += text.count(linesep) + 1

    def show_board(self):
        if self.clear and self.rows:
            self.clear(absolute=self.rows)
        self.rows = 0
        self.do_print('Tic Tac Toe')
        self.do_print('''   |   |
 {6} | {7} | {8}
   |   |
-----------
   |   |
 {3} | {4} | {5}
   |   |
-----------
   |   |
 {0} | {1} | {2}
   |   |'''.format(*self.moves))

    def start(self):
        self.show_board()
        ok = input("Press <Enter> to continue...")
        self.moves = ['O', 'X'] * 4 + ['O']
        self.show_board()
        ok = input("Press <Enter> to close.")

if __name__ == "__main__":
    TicTacToe().start()

Explanation: do_print(...) on line 19 is a version of print(...) needed to keep track of how many new lines have been printed (self.rows). Otherwise, you would have to self.rows += 1 all over the place where print(...) is called throughout the entire program. So each time the board is redrawn by calling show_board() the previous board is cleared out and the new board is printed exactly where it should be. Notice self.clear(calling_line=False) on line 9 basically pushes everything up RELATIVE to the bottom of the terminal, but does not clear the original calling line. In contrast, self.clear(absolute=self.rows) on line 29 absolutely clears out everything self.rows distance upward, rather than just pushing everything upward relative to the bottom of the terminal.

Ubuntu users with Python 3.3: Put #!/usr/bin/env python3 on the very first line of the tictactoe.py file. Right click on the tictactoe.py file => Properties => Permissions tab => Check Execute: Allow executing file as program. Double click on the file => Click Run in Terminal button. If an open terminal's current directory is that of the tictactoe.py file, you can also start the file with ./tictactoe.py.

TypeError: 'str' object cannot be interpreted as an integer

You have to convert input x and y into int like below.

x=int(x)
y=int(y)

MySQL IF ELSEIF in select query

For your question :

SELECT id, 
   IF(qty_1 <= '23', price,
   IF(('23' > qty_1 && qty_2 <= '23'), price_2,
   IF(('23' > qty_2 && qty_3 <= '23'), price_3,
   IF(('23' > qty_2 && qty_3<='23'), price_3,
   IF('23' > qty_3, price_4, 1))))) as total 
FROM product;

You can use the if - else control structure or the IF function in MySQL.

Reference:
http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) */

This one should work:

@supports (-ms-ime-align:auto) {
    .selector {
        property: value;
    }
}

For more see: Browser Strangeness

Google Chrome "window.open" workaround?

menubar must no, or 0, for Google Chrome to open in new window instead of tab.

Import Script from a Parent Directory

From the docs:

from .. import scriptA

You can do this in packages, but not in scripts you run directly. From the link above:

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports.

If you create a script that imports A.B.B, you won't receive the ValueError.

How to parse JSON response from Alamofire API in Swift?

in swift 5 we do like, Use typealias for the completion. Typlealias nothing just use to clean the code.

typealias response = (Bool,Any?)->()


static func postCall(_ url : String, param : [String : Any],completion : @escaping response){
    Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in

        switch response.result {
           case .success(let JSON):
               print("\n\n Success value and JSON: \(JSON)")

           case .failure(let error):
               print("\n\n Request failed with error: \(error)")

           }
    }
}

What is the difference between the operating system and the kernel?

The kernel is part of the operating system and closer to the hardware it provides low level services like:

  • device driver
  • process management
  • memory management
  • system calls

An operating system also includes applications like the user interface (shell, gui, tools, and services).

Angular 2 execute script after template render

I've used this method (reported here )

export class AppComponent {

  constructor() {
    if(document.getElementById("testScript"))
      document.getElementById("testScript").remove();
    var testScript = document.createElement("script");
    testScript.setAttribute("id", "testScript");
    testScript.setAttribute("src", "assets/js/test.js");
    document.body.appendChild(testScript);
  }
}

it worked for me since I wanted to execute a javascript file AFTER THE COMPONENT RENDERED.

Checking Date format from a string in C#

https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                     "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                     "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                     "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                     "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
  string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                          "5/1/2009 6:32:00", "05/01/2009 06:32", 
                          "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
  DateTime dateValue;

  foreach (string dateString in dateStrings)
  {
     if (DateTime.TryParseExact(dateString, formats, 
                                new CultureInfo("en-US"), 
                                DateTimeStyles.None, 
                                out dateValue))
        Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
     else
        Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
  }

Cron and virtualenv

Rather than mucking around with virtualenv-specific shebangs, just prepend PATH onto the crontab.

From an activated virtualenv, run these three commands and python scripts should just work:

$ echo "PATH=$PATH" > myserver.cron
$ crontab -l >> myserver.cron
$ crontab myserver.cron

The crontab's first line should now look like this:

PATH=/home/me/virtualenv/bin:/usr/bin:/bin:  # [etc...]

Programmatically find the number of cores on a machine

you can use WMI in .net too but you're then dependent on the wmi service running etc. Sometimes it works locally, but then fail when the same code is run on servers. I believe that's a namespace issue, related to the "names" whose values you're reading.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

here is the solution that I decided to use.

        ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            string name = certificate.Subject;

            DateTime expirationDate = DateTime.Parse(certificate.GetExpirationDateString());

            if (sslPolicyErrors == SslPolicyErrors.None || (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch && name.EndsWith(".acceptabledomain.com") && expirationDate > DateTime.Now))
            {
                return true;
            }
            return false;
        };

Convert JSON to DataTable

There is an easier method than the other answers here, which require first deserializing into a c# class, and then turning it into a datatable.

It is possible to go directly to a datatable, with JSON.NET and code like this:

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

Parsing JSON from XmlHttpRequest.responseJSON

New ways I: fetch

TL;DR I'd recommend this way as long as you don't have to send synchronous requests or support old browsers.

A long as your request is asynchronous you can use the Fetch API to send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch() to send a request and ResponseBody.json() to parse the response:

fetch(url)
  .then(function(response) {
    return response.json();
  })
  .then(function(jsonResponse) {
    // do something with jsonResponse
  });

Compatibility: The Fetch API is not supported by IE11 as well as Edge 12 & 13. However, there are polyfills.

New ways II: responseType

As Londeren has written in his answer, newer browsers allow you to use the responseType property to define the expected format of the response. The parsed response data can then be accessed via the response property:

var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = req.response;
   // do something with jsonResponse
};
req.send(null);

Compatibility: responseType = 'json' is not supported by IE11.

The classic way

The standard XMLHttpRequest has no responseJSON property, just responseText and responseXML. As long as bitly really responds with some JSON to your request, responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse():

var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = JSON.parse(req.responseText);
   // do something with jsonResponse
};
req.send(null);

Compatibility: This approach should work with any browser that supports XMLHttpRequest and JSON.

JSONHttpRequest

If you prefer to use responseJSON, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSON property. All you have to change in your code would be the first line:

var req = new JSONHttpRequest();

JSONHttpRequest also provides functionality to easily send JavaScript objects as JSON. More details and the code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/.

Full disclosure: I'm the owner of Pixels|Bytes. I thought that my script was a good solution for the original question, but it is rather outdated today. I do not recommend to use it anymore.

Handle Button click inside a row in RecyclerView

this is how I handle multiple onClick events inside a recyclerView:

Edit : Updated to include callbacks (as mentioned in other comments). I have used a WeakReference in the ViewHolder to eliminate a potential memory leak.

Define interface :

public interface ClickListener {

    void onPositionClicked(int position);
    
    void onLongClicked(int position);
}

Then the Adapter :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    
    private final ClickListener listener;
    private final List<MyItems> itemsList;

    public MyAdapter(List<MyItems> itemsList, ClickListener listener) {
        this.listener = listener;
        this.itemsList = itemsList;
    }

    @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row_layout), parent, false), listener);
    }

    @Override public void onBindViewHolder(MyViewHolder holder, int position) {
        // bind layout and data etc..
    }

    @Override public int getItemCount() {
        return itemsList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        private ImageView iconImageView;
        private TextView iconTextView;
        private WeakReference<ClickListener> listenerRef;

        public MyViewHolder(final View itemView, ClickListener listener) {
            super(itemView);

            listenerRef = new WeakReference<>(listener);
            iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
            iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);

            itemView.setOnClickListener(this);
            iconTextView.setOnClickListener(this);
            iconImageView.setOnLongClickListener(this);
        }

        // onClick Listener for view
        @Override
        public void onClick(View v) {

            if (v.getId() == iconTextView.getId()) {
                Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            }
            
            listenerRef.get().onPositionClicked(getAdapterPosition());
        }


        //onLongClickListener for view
        @Override
        public boolean onLongClick(View v) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Hello Dialog")
                    .setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

            builder.create().show();
            listenerRef.get().onLongClicked(getAdapterPosition());
            return true;
        }
    }
}

Then in your activity/fragment - whatever you can implement : Clicklistener - or anonymous class if you wish like so :

MyAdapter adapter = new MyAdapter(myItems, new ClickListener() {
            @Override public void onPositionClicked(int position) {
                // callback performed on click
            }

            @Override public void onLongClicked(int position) {
                // callback performed on click
            }
        });

To get which item was clicked you match the view id i.e. v.getId() == whateverItem.getId()

Hope this approach helps!

How to find the difference in days between two dates?

If the option -d works in your system, here's another way to do it. There is a caveat that it wouldn't account for leap years since I've considered 365 days per year.

date1yrs=`date -d "20100209" +%Y`
date1days=`date -d "20100209" +%j`
date2yrs=`date +%Y`
date2days=`date +%j`
diffyr=`expr $date2yrs - $date1yrs`
diffyr2days=`expr $diffyr \* 365`
diffdays=`expr $date2days - $date1days`
echo `expr $diffyr2days + $diffdays`

Copying and pasting data using VBA code

Use the PasteSpecial method:

sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues

BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).

What is the default Precision and Scale for a Number in Oracle?

I believe the default precision is 38, default scale is zero. However the actual size of an instance of this column, is dynamic. It will take as much space as needed to store the value, or max 21 bytes.

Multiple selector chaining in jQuery?

You should be able to use:

$('#Edit.myClass, #Create.myClass').plugin({options here});

jQuery | Multiple Selectors

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

The server will automatically abort connections over which no message has been received for the duration equal to the receive timeout (default is 10 mins). This is a DoS mitigation to prevent clients from forcing the server to have connections open for an indefinite amount of time.

Since the server aborts the connection because it has gone idle, the client gets this exception.

You can control how long the server allows a connection to go idle before aborting it by configuring the receive timeout on the server's binding. Credit: T.R.Vishwanath - MSFT

Why does the Visual Studio editor show dots in blank spaces?

Press ctrl + E followed by S key to remove the lines in Visual Studio 10

Swap x and y axis without manually swapping values

Microsoft Excel for Mac 2011 v 14.5.9

  • Click on the chart
  • Press the "Switch Plot" button under the "Charts" tab

How do I write dispatch_after GCD in Swift 3, 4, and 5?

call DispatchQueue.main.after(when: DispatchTime, execute: () -> Void)

I'd highly recommend using the Xcode tools to convert to Swift 3 (Edit > Convert > To Current Swift Syntax). It caught this for me

How do I read a resource file from a Java jar file?

It looks as if you are using the URL.toString result as the argument to the FileReader constructor. URL.toString is a bit broken, and instead you should generally use url.toURI().toString(). In any case, the string is not a file path.

Instead, you should either:

  • Pass the URL to ServicesLoader and let it call openStream or similar.
  • Use Class.getResourceAsStream and just pass the stream over, possibly inside an InputSource. (Remember to check for nulls as the API is a bit messy.)

Changing CSS style from ASP.NET code

If your div is an ASP.NET control with runat="server" then AviewAnew's answer should do it. If it's just an HTML div, then you'd probably want to use JavaScript. Can you add the actual div tag to your question?

Boto3 to download all files from a S3 Bucket

for objs in my_bucket.objects.all():
    print(objs.key)
    path='/tmp/'+os.sep.join(objs.key.split(os.sep)[:-1])
    try:
        if not os.path.exists(path):
            os.makedirs(path)
        my_bucket.download_file(objs.key, '/tmp/'+objs.key)
    except FileExistsError as fe:                          
        print(objs.key+' exists')

This code will download the content in /tmp/ directory. If you want you can change the directory.

Loading basic HTML in Node.js

use app.get to get the html file. its simple!!

const express = require('express');
const app = new express();

app.get('/', function(request, response){
    response.sendFile('absolutePathToYour/htmlPage.html');
});

its as simple as that. For this use express module. Install express: npm install express -g

remove kernel on jupyter notebook

Just for completeness, you can get a list of kernels with jupyter kernelspec list, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel. If you do not see everything in this list when you run jupyter kernelspec list, try looking in common Jupyter folders:

ls ~/.local/share/jupyter/kernels  # usually where local kernels go
ls /usr/local/share/jupyter/kernels  # usually where system-wide kernels go
ls /usr/share/jupyter/kernels  # also where system-wide kernels can go

Also, you can delete a kernel with jupyter kernelspec remove or jupyter kernelspec uninstall. The latter is an alias for remove. From the in-line help text for the command:

uninstall
    Alias for remove
remove
    Remove one or more Jupyter kernelspecs by name.

What does -Xmn jvm option stands for

-Xmn : the size of the heap for the young generation Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor" .

Good size is 33%

Source

Simple mediaplayer play mp3 from file path?

String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();   
mediaPlayer.start()

and this play from raw folder.

int resID = myContext.getResources().getIdentifier(playSoundName,"raw",myContext.getPackageName());

            MediaPlayer mediaPlayer = MediaPlayer.create(myContext,resID);
            mediaPlayer.prepare();
            mediaPlayer.start();

mycontext=application.this. use.

Convert iterator to pointer?

A vector is a container with full ownership of it's elements. One vector cannot hold a partial view of another, even a const-view. That's the root cause here.

If you need that, make your own container that has views with weak_ptr's to the data, or look at ranges. Pair of iterators (even pointers work well as iterators into a vector) or, even better, boost::iterator_range that work pretty seamlessly.

It depends on the templatability of your code. Use std::pair if you need to hide the code in a cpp.

How to write loop in a Makefile?

For cross-platform support, make the command separator (for executing multiple commands on the same line) configurable.

If you're using MinGW on a Windows platform for example, the command separator is &:

NUMBERS = 1 2 3 4
CMDSEP = &
doit:
    $(foreach number,$(NUMBERS),./a.out $(number) $(CMDSEP))

This executes the concatenated commands in one line:

./a.out 1 & ./a.out 2 & ./a.out 3 & ./a.out 4 &

As mentioned elsewhere, on a *nix platform use CMDSEP = ;.

React - clearing an input value after form submit

Since you input field is a controlled element, you cannot directly change the input field value without modifying the state.

Also in

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }

this.mainInput doesn't refer the input since mainInput is an id, you need to specify a ref to the input

<input
      ref={(ref) => this.mainInput= ref}
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      value={this.state.city}
      type="text"
    />

In you current state the best way is to clear the state to clear the input value

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({city: ""});
  }

However if you still for some reason want to keep the value in state even if the form is submitted, you would rather make the input uncontrolled

<input
      id="mainInput"
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      type="text"
    />

and update the value in state onChange and onSubmit clear the input using ref

 onHandleChange(e) {
    this.setState({
      city: e.target.value
    });
  }

  onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }

Having Said that, I don't see any point in keeping the state unchanged, so the first option should be the way to go.

How to use the 'og' (Open Graph) meta tag for Facebook share

Use:

<!-- For Google -->
<meta name="description" content="" />
<meta name="keywords" content="" />

<meta name="author" content="" />
<meta name="copyright" content="" />
<meta name="application-name" content="" />

<!-- For Facebook -->
<meta property="og:title" content="" />
<meta property="og:type" content="article" />
<meta property="og:image" content="" />
<meta property="og:url" content="" />
<meta property="og:description" content="" />

<!-- For Twitter -->
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="" />
<meta name="twitter:description" content="" />
<meta name="twitter:image" content="" />

Fill the content =" ... " according to the content of your page.

For more information, visit 18 Meta Tags Every Webpage Should Have in 2013.

How to auto import the necessary classes in Android Studio with shortcut?

File -> Settings -> Keymap Change keymaps settings to your previous IDE to which you are familiar with

enter image description here

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

That's JSON, or JavaScript Object Notation. It's a quick way of describing an object, or a hash map. The thing before the colon is the property name, and the thing after the colon is its value. So in this example, there's a property "r", whose value is whatever's in the variable r. Same for t.

"Integer number too large" error message for 600851475143

You need to use a long literal:

obj.function(600851475143l);  // note the "l" at the end

But I would expect that function to run out of memory (or time) ...

Passing Objects By Reference or Value in C#

When you pass the the System.Drawing.Image type object to a method you are actually passing a copy of reference to that object.

So if inside that method you are loading a new image you are loading using new/copied reference. You are not making change in original.

YourMethod(System.Drawing.Image image)
{
    //now this image is a new reference
    //if you load a new image 
    image = new Image()..
    //you are not changing the original reference you are just changing the copy of original reference
}

How to check "hasRole" in Java Code with Spring Security?

Better late then never, let me put in my 2 cents worth.

In JSF world, within my managed bean, I did the following:


HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
SecurityContextHolderAwareRequestWrapper sc = new SecurityContextHolderAwareRequestWrapper(req, "");

As mentioned above, my understanding is that it can be done the long winded way as followed:


Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetails userDetails = null;
if (principal instanceof UserDetails) {
    userDetails = (UserDetails) principal;
    Collection  authorities = userDetails.getAuthorities();
}

How can I format DateTime to web UTC format?

This code is working for me:

var datetime = new DateTime(2017, 10, 27, 14, 45, 53, 175, DateTimeKind.Local);
var text = datetime.ToString("o");
Console.WriteLine(text);
--  2017-10-27T14:45:53.1750000+03:00

// datetime from string
var newDate = DateTime.ParseExact(text, "o", null);

Access Https Rest Service using Spring RestTemplate

This is a solution with no deprecated class or method : (Java 8 approved)

CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);

RestTemplate restTemplate = new RestTemplate(requestFactory);

Important information : Using NoopHostnameVerifier is a security risk

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

if you tried running java with -version argument, and even though the problem could not be solved by any means, then you might have installed many java versions, like JDK 1.8 and JDK 1.7 at the same time.

So try uninstalling all other versions other than the one you need, then set the JAVA_HOMEpath variable for that JDK remaining, and you're done.

In android how to set navigation drawer header image and name programmatically in class file?

val navigationView: NavigationView =  findViewById(R.id.nv)
val header: View = navigationView.getHeaderView(0)
val tv: TextView = header.findViewById(R.id.profilename)
tv.text = "Your_Text"

This will fix your problem <3

How can I detect window size with jQuery?

You can get the values for the width and height of the browser using the following:

$(window).height();
$(window).width();

To get notified when the browser is resized, use this bind callback:

$(window).resize(function() {
    // Do something
});

DateTime.Now.ToShortDateString(); replace month and day

Use DateTime.ToString with the specified format MM.dd.yyyy:

this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");

Here, MM means the month from 01 to 12, dd means the day from 01 to 31 and yyyy means the year as a four-digit number.

Creating a copy of a database in PostgreSQL

In production environment, where the original database is under traffic, I'm simply using:

pg_dump production-db | psql test-db

How to access global js variable in AngularJS directive

I have tried these methods and find that they dont work for my needs. In my case, I needed to inject json rendered server side into the main template of the page, so when it loads and angular inits, the data is already there and doesnt have to be retrieved (large dataset).

The easiest solution that I have found is to do the following:

In your angular code outside of the app, module and controller definitions add in a global javascript value - this definition MUST come before the angular stuff is defined.

Example:

'use strict';

//my data variable that I need access to.
var data = null;

angular.module('sample', [])

Then in your controller:

.controller('SampleApp', function ($scope, $location) {

$scope.availableList = [];

$scope.init = function () {
    $scope.availableList = data;
}

Finally, you have to init everything (order matters):

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="/path/to/your/angular/js/sample.js"></script>
  <script type="text/javascript">
      data = <?= json_encode($cproducts); ?>
  </script>

Finally initialize your controller and init function.

  <div ng-app="samplerrelations" ng-controller="SamplerApp" ng-init="init();">

By doing this you will now have access to whatever data you stuffed into the global variable.

How to take character input in java

I had the same struggle and I this is what I used:

} public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
System.out.print("Please enter the string: ");
String input = scan.next();
System.out.print("Please enter the required symbol: ");
String symbol = scan.next();        
char symbolChar = symbol.charAt(0);

This works just fine. The idea is to get from the string the only char in it.

catch forEach last iteration

const arr= [1, 2, 3]
arr.forEach(function(element){
 if(arr[arr.length-1] === element){
  console.log("Last Element")
 }
})

How do I create a unique constraint that also allows nulls?

SQL Server 2008 And Up

Just filter a unique index:

CREATE UNIQUE NONCLUSTERED INDEX UQ_Party_SamAccountName
ON dbo.Party(SamAccountName)
WHERE SamAccountName IS NOT NULL;

In Lower Versions, A Materialized View Is Still Not Required

For SQL Server 2005 and earlier, you can do it without a view. I just added a unique constraint like you're asking for to one of my tables. Given that I want uniqueness in column SamAccountName, but I want to allow multiple NULLs, I used a materialized column rather than a materialized view:

ALTER TABLE dbo.Party ADD SamAccountNameUnique
   AS (Coalesce(SamAccountName, Convert(varchar(11), PartyID)))
ALTER TABLE dbo.Party ADD CONSTRAINT UQ_Party_SamAccountName
   UNIQUE (SamAccountNameUnique)

You simply have to put something in the computed column that will be guaranteed unique across the whole table when the actual desired unique column is NULL. In this case, PartyID is an identity column and being numeric will never match any SamAccountName, so it worked for me. You can try your own method—be sure you understand the domain of your data so that there is no possibility of intersection with real data. That could be as simple as prepending a differentiator character like this:

Coalesce('n' + SamAccountName, 'p' + Convert(varchar(11), PartyID))

Even if PartyID became non-numeric someday and could coincide with a SamAccountName, now it won't matter.

Note that the presence of an index including the computed column implicitly causes each expression result to be saved to disk with the other data in the table, which DOES take additional disk space.

Note that if you don't want an index, you can still save CPU by making the expression be precalculated to disk by adding the keyword PERSISTED to the end of the column expression definition.

In SQL Server 2008 and up, definitely use the filtered solution instead if you possibly can!

Controversy

Please note that some database professionals will see this as a case of "surrogate NULLs", which definitely have problems (mostly due to issues around trying to determine when something is a real value or a surrogate value for missing data; there can also be issues with the number of non-NULL surrogate values multiplying like crazy).

However, I believe this case is different. The computed column I'm adding will never be used to determine anything. It has no meaning of itself, and encodes no information that isn't already found separately in other, properly defined columns. It should never be selected or used.

So, my story is that this is not a surrogate NULL, and I'm sticking to it! Since we don't actually want the non-NULL value for any purpose other than to trick the UNIQUE index to ignore NULLs, our use case has none of the problems that arise with normal surrogate NULL creation.

All that said, I have no problem with using an indexed view instead—but it brings some issues with it such as the requirement of using SCHEMABINDING. Have fun adding a new column to your base table (you'll at minimum have to drop the index, and then drop the view or alter the view to not be schema bound). See the full (long) list of requirements for creating an indexed view in SQL Server (2005) (also later versions), (2000).

Update

If your column is numeric, there may be the challenge of ensuring that the unique constraint using Coalesce does not result in collisions. In that case, there are some options. One might be to use a negative number, to put the "surrogate NULLs" only in the negative range, and the "real values" only in the positive range. Alternately, the following pattern could be used. In table Issue (where IssueID is the PRIMARY KEY), there may or may not be a TicketID, but if there is one, it must be unique.

ALTER TABLE dbo.Issue ADD TicketUnique
   AS (CASE WHEN TicketID IS NULL THEN IssueID END);
ALTER TABLE dbo.Issue ADD CONSTRAINT UQ_Issue_Ticket_AllowNull
   UNIQUE (TicketID, TicketUnique);

If IssueID 1 has ticket 123, the UNIQUE constraint will be on values (123, NULL). If IssueID 2 has no ticket, it will be on (NULL, 2). Some thought will show that this constraint cannot be duplicated for any row in the table, and still allows multiple NULLs.

Extract string between two strings in java

Your regex looks correct, but you're splitting with it instead of matching with it. You want something like this:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Multi-line bash commands in makefile

Of course, the proper way to write a Makefile is to actually document which targets depend on which sources. In the trivial case, the proposed solution will make foo depend on itself, but of course, make is smart enough to drop a circular dependency. But if you add a temporary file to your directory, it will "magically" become part of the dependency chain. Better to create an explicit list of dependencies once and for all, perhaps via a script.

GNU make knows how to run gcc to produce an executable out of a set of .c and .h files, so maybe all you really need amounts to

foo: $(wildcard *.h) $(wildcard *.c)

How to convert HTML to PDF using iTextSharp

I use the following code to create PDF

protected void CreatePDF(Stream stream)
        {
            using (var document = new Document(PageSize.A4, 40, 40, 40, 30))
            {
                var writer = PdfWriter.GetInstance(document, stream);
                writer.PageEvent = new ITextEvents();
                document.Open();

                // instantiate custom tag processor and add to `HtmlPipelineContext`.
                var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
                tagProcessorFactory.AddProcessor(
                    new TableProcessor(),
                    new string[] { HTML.Tag.TABLE }
                );

                //Register Fonts.
                XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
                fontProvider.Register(HttpContext.Current.Server.MapPath("~/Content/Fonts/GothamRounded-Medium.ttf"), "Gotham Rounded Medium");
                CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);

                var htmlPipelineContext = new HtmlPipelineContext(cssAppliers);
                htmlPipelineContext.SetTagFactory(tagProcessorFactory);

                var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
                var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);

                // get an ICssResolver and add the custom CSS
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                cssResolver.AddCss(CSSSource, "utf-8", true);
                var cssResolverPipeline = new CssResolverPipeline(
                    cssResolver, htmlPipeline
                );

                var worker = new XMLWorker(cssResolverPipeline, true);
                var parser = new XMLParser(worker);
                using (var stringReader = new StringReader(HTMLSource))
                {
                    parser.Parse(stringReader);
                    document.Close();
                    HttpContext.Current.Response.ContentType = "application /pdf";
                    if (base.View)
                        HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=\"" + OutputFileName + ".pdf\"");
                    else
                        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + OutputFileName + ".pdf\"");
                    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    HttpContext.Current.Response.WriteFile(OutputPath);
                    HttpContext.Current.Response.End();
                }
            }
        }

How do I get a class instance of generic type T?

Many people don't know this trick! Actually, I just found it today! It works like a dream! Just check this example out:

public static void main(String[] args) {
    Date d=new Date();  //Or anything you want!
    printMethods(i);
}

public static <T> void printMethods(T t){
    Class<T> clazz= (Class<T>) t.getClass(); // There you go!
    for ( Method m : clazz.getMethods()){
        System.out.println( m.getName() );
    }
}

How can one create an overlay in css?

I would suggest using css attributes to do this. You can use position:absolute to position an element on top of another.

For example:

<div id="container">
   <div id="on-top">Top!</div>
   <div id="on-bottom">Bottom!</div>
</div>

and css

#container {position:relative;}
#on-top {position:absolute; z-index:5;}
#on-bottom {position:absolute; z-index:4;}

I would take a look at this for advice: http://www.w3schools.com/cssref/pr_class_position.asp

And finally here is a jsfiddle to show you my example

http://jsfiddle.net/Wgfw6/

ARM compilation error, VFP registers used by executable, not object file

In my case CFLAGS = -O0 -g -Wall -I. -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=soft has helped. As you can see, i used it for my stm32f407.

Getting Database connection in pure JPA setup

I ran into this problem today and this was the trick I did, which worked for me:

   EntityManagerFactory emf = Persistence.createEntityManagerFactory("DAOMANAGER");
   EntityManagerem = emf.createEntityManager();

   org.hibernate.Session session = ((EntityManagerImpl) em).getSession();
   java.sql.Connection connectionObj = session.connection();

Though not the best way but does the job.

OAuth 2.0 Authorization Header

You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.

It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1

E.g.:

   GET /resource HTTP/1.1
   Host: server.example.com
   Authorization: Bearer mF_9.B5f-4.1JqM

Where mF_9.B5f-4.1JqM is your OAuth access token.

jQuery jump or scroll to certain position, div or target on the page from button onclick

$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used

ASP.NET MVC - passing parameters to the controller

There is another way to accomplish that (described in more details in Stephen Walther's Pager example

Essentially, you create a link in the view:

Html.ActionLink("Next page", "Index", routeData)

In routeData you can specify name/value pairs (e.g., routeData["page"] = 5), and in the controller Index function corresponding parameters receive the value. That is,

public ViewResult Index(int? page)

will have page passed as 5. I have to admit, it's quite unusual that string ("page") automagically becomes a variable - but that's how MVC works in other languages as well...

CSS/HTML: What is the correct way to make text italic?

Perhaps it has no special meaning and only needs to be rendered in italics to separate it presentationally from the text preceding it.

If it has no special meaning, why does it need to be separated presentationally from the text preceding it? This run of text looks a bit weird, because I’ve italicised it for no reason.

I do take your point though. It’s not uncommon for designers to produce designs that vary visually, without varying meaningfully. I’ve seen this most often with boxes: designers will give us designs including boxes with various combinations of colours, corners, gradients and drop-shadows, with no relation between the styles, and the meaning of the content.

Because these are reasonably complex styles (with associated Internet Explorer issues) re-used in different places, we create classes like box-1, box-2, so that we can re-use the styles.

The specific example of making some text italic is too trivial to worry about though. Best leave minutiae like that for the Semantic Nutters to argue about.

What is the correct JSON content type?

I use the below

contentType: 'application/json',
data: JSON.stringify(SendData),

Vue JS mounted()

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

Git - Ignore node_modules folder everywhere

you can do it with SVN/Tortoise git as well.

just right click on node_modules -> Tortoise git -> add to ignore list.

This will generate .gitIgnore for you and you won't find node_modules folder in staging again.

How do I make a new line in swift

"\n" is not working everywhere!

For example in email, it adds the exact "\n" into the text instead of a new line if you use it in the custom keyboard like: textDocumentProxy.insertText("\n")

There are another newLine characters available but I can't just simply paste them here (Because they make a new lines).

using this extension:

extension CharacterSet {
    var allCharacters: [Character] {
        var result: [Character] = []
        for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
            for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
                if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
                    result.append(Character(uniChar))
                }
            }
        }
        return result
    }
}

you can access all characters in any CharacterSet. There is a character set called newlines. Use one of them to fulfill your requirements:

let newlines = CharacterSet.newlines.allCharacters
for newLine in newlines {
    print("Hello World \(newLine) This is a new line")
}

Then store the one you tested and worked everywhere and use it anywhere. Note that you can't relay on the index of the character set. It may change.

But most of the times "\n" just works as expected.

How does DateTime.Now.Ticks exactly work?

The resolution of DateTime.Now depends on your system timer (~10ms on a current Windows OS)...so it's giving the same ending value there (it doesn't count any more finite than that).

How to retrieve the last autoincremented ID from a SQLite table?

One other option is to look at the system table sqlite_sequence. Your sqlite database will have that table automatically if you created any table with autoincrement primary key. This table is for sqlite to keep track of the autoincrement field so that it won't repeat the primary key even after you delete some rows or after some insert failed (read more about this here http://www.sqlite.org/autoinc.html).

So with this table there is the added benefit that you can find out your newly inserted item's primary key even after you inserted something else (in other tables, of course!). After making sure that your insert is successful (otherwise you will get a false number), you simply need to do:

select seq from sqlite_sequence where name="table_name"

How to fix "containing working copy admin area is missing" in SVN?

Can you try to check out a new copy of the parent directory?

Edit: To be bit more specific, I meant to suggest going up one level and deleting the containing directory. Then do a

svn update --set-depth infinity

to replace the directory.

How to restrict UITextField to take only numbers in Swift?

An approach that solves both decimal and Int:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentText = textField.text
    let futureString = currentText.substring(toIndex: range.location) + string + currentText.substring(fromIndex: range.location + range.length)
    
    if futureString.count == 0 {
        return true
    }
    
    if isDecimal {
        if let numberAsDouble = Double(futureString), numberAsDouble.asPrice.count >= futureString.count {
            return true
        }
    } else if let numberAsInt = Int(futureString), "\(numberAsInt)".count == futureString.count {
        return true
    }
    
    return false
}

Creating multiline strings in JavaScript

This works in IE, Safari, Chrome and Firefox:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class="crazy_idea" thorn_in_my_side='<table  border="0">
                        <tr>
                            <td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
                        </tr>
                    </table>'></div>
<script type="text/javascript">
    alert($(".crazy_idea").attr("thorn_in_my_side"));
</script>

What is function overloading and overriding in php?

There are some differences between Function overloading & overriding though both contains the same function name.In overloading ,between the same name functions contain different type of argument or return type;Such as: "function add (int a,int b)" & "function add(float a,float b); Here the add() function is overloaded. In the case of overriding both the argument and function name are same.It generally found in inheritance or in traits.We have to follow some tactics to introduce, what function will execute now. So In overriding the programmer follows some tactics to execute the desired function where in the overloading the program can automatically identify the desired function...Thanks!

Best way to unselect a <select> in jQuery?

Set a id in your select, like:
<select id="foo" size="2">

Then you can use:
$("#foo").prop("selectedIndex", 0).change();

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

Center icon in a div - horizontally and vertically

Since they are already inline-block child elements, you can set text-align:center on the parent without having to set a width or margin:0px auto on the child. Meaning it will work for dynamically generated content with varying widths.

.img_container, .img_container2 {
    text-align: center;
}

This will center the child within both div containers.

UPDATE:

For vertical centering, you can use the calc() function assuming the height of the icon is known.

.img_container > i, .img_container2 > i {
    position:relative;
    top: calc(50% - 10px); /* 50% - 3/4 of icon height */
}

jsFiddle demo - it works.

For what it's worth - you can also use vertical-align:middle assuming display:table-cell is set on the parent.

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Relational Database Design Patterns?

After many years of database development I can say there are some no goes and some question that you should answer before you begin:

questions:

  • Do you want use in the future another DBMS? If yes then does not use to special SQL stuff of the current DBMS. Remove logic in your application.

Does not use:

  • white spaces in table names and column names
  • Non Ascii characters in table and column names
  • binding to a specific lower case or upper case. And never use 2 tables or columns that differ only with lower case and upper case.
  • does not use SQL keywords for tables or columns names like "FROM", "BETWEEN", "DELETE", etc

recomendations:

  • Use NVARCHAR or equivalents for unicode support then you have no problems with codepages.
  • Give every column a unique name. This make it easer on join to select the column. It is very difficult if every table has a column "ID" or "Name" or "Description". Use XyzID and AbcID.
  • Use a resource bundle or equals for complex SQL expressions. It make it easer to switch to another DBMS.
  • Does not cast hard on any data type. Another DBMS can not have this data type. FOr example Oracle daes not have a SMALLINT only a number.

I hope this is a good starting point.

Handling multiple IDs in jQuery

Yes, #id selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.

However, for your example, since <script> comes before the elements, you need a document.ready handler, so it waits until the elements are in the DOM to go looking for them, like this:

<script>
  $(function() {
    $("#segement1,#segement2,#segement3").hide()
  });
</script>

<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>

Conditional formatting using AND() function

COLUMN() and ROW() won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.

For instance, if you want to use this conditional formating on a range begining on cell A1, you can try:

`COLUMN(A1)` and `ROW(A1)`

Excel will automatically adapt the conditional formating to the current cell.

How to check if pytorch is using the GPU?

Simply from command prompt or Linux environment run the following command.

python -c 'import torch; print(torch.cuda.is_available())'

The above should print True

python -c 'import torch; print(torch.rand(2,3).cuda())'

This one should print the following:

tensor([[0.7997, 0.6170, 0.7042], [0.4174, 0.1494, 0.0516]], device='cuda:0')

Differences between C++ string == and compare()?

One thing that is not covered here is that it depends if we compare string to c string, c string to string or string to string.

A major difference is that for comparing two strings size equality is checked before doing the compare and that makes the == operator faster than a compare.

here is the compare as i see it on g++ Debian 7

// operator ==
  /**
   *  @brief  Test equivalence of two strings.
   *  @param __lhs  First string.
   *  @param __rhs  Second string.
   *  @return  True if @a __lhs.compare(@a __rhs) == 0.  False otherwise.
   */
  template<typename _CharT, typename _Traits, typename _Alloc>
    inline bool
    operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
           const basic_string<_CharT, _Traits, _Alloc>& __rhs)
    { return __lhs.compare(__rhs) == 0; }

  template<typename _CharT>
    inline
    typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, bool>::__type
    operator==(const basic_string<_CharT>& __lhs,
           const basic_string<_CharT>& __rhs)
    { return (__lhs.size() == __rhs.size()
          && !std::char_traits<_CharT>::compare(__lhs.data(), __rhs.data(),
                            __lhs.size())); }

  /**
   *  @brief  Test equivalence of C string and string.
   *  @param __lhs  C string.
   *  @param __rhs  String.
   *  @return  True if @a __rhs.compare(@a __lhs) == 0.  False otherwise.
   */
  template<typename _CharT, typename _Traits, typename _Alloc>
    inline bool
    operator==(const _CharT* __lhs,
           const basic_string<_CharT, _Traits, _Alloc>& __rhs)
    { return __rhs.compare(__lhs) == 0; }

  /**
   *  @brief  Test equivalence of string and C string.
   *  @param __lhs  String.
   *  @param __rhs  C string.
   *  @return  True if @a __lhs.compare(@a __rhs) == 0.  False otherwise.
   */
  template<typename _CharT, typename _Traits, typename _Alloc>
    inline bool
    operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
           const _CharT* __rhs)
    { return __lhs.compare(__rhs) == 0; }

number_format() with MySQL

CREATE DEFINER=`yourfunctionname`@`%` FUNCTION `money`(
     `betrag` DECIMAL(10,2)

 )
 RETURNS varchar(128) CHARSET latin1
 LANGUAGE SQL
 NOT DETERMINISTIC
 CONTAINS SQL
 SQL SECURITY DEFINER
 COMMENT ''
 return(
     select replace(format(cast(betrag as char),2),',',"'") as betrag
 )

will creating a MySql-Function with this Code:

 select replace(format(cast(amount as char),2),',',"'") as amount_formated

Append a dictionary to a dictionary

Assuming that you do not want to change orig, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:

from itertools import chain
dest = dict(chain(orig.items(), extra.items()))

Or without itertools:

dest = dict(list(orig.items()) + list(extra.items()))

Note that you only need to pass the result of items() into list() on Python 3, on 2.x dict.items() already returns a list so you can just do dict(orig.items() + extra.items()).

As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:

from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))

Check time difference in Javascript

This function returns a string with the difference from a datetime string and the current datetime.

function get_time_diff( datetime )
{
    var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456";

    var datetime = new Date( datetime ).getTime();
    var now = new Date().getTime();

    if( isNaN(datetime) )
    {
        return "";
    }

    console.log( datetime + " " + now);

    if (datetime < now) {
        var milisec_diff = now - datetime;
    }else{
        var milisec_diff = datetime - now;
    }

    var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));

    var date_diff = new Date( milisec_diff );

    return days + " Days "+ date_diff.getHours() + " Hours " + date_diff.getMinutes() + " Minutes " + date_diff.getSeconds() + " Seconds";
}

Tested in the Google Chrome console (press F12)

get_time_diff()
1388534523123 1375877555722
"146 Days 12 Hours 49 Minutes 27 Seconds"

Custom seekbar (thumb size, color and background)

Use tints ;)

<SeekBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="15dp"
        android:minWidth="15dp"
        android:maxHeight="15dp"
        android:maxWidth="15dp"
        android:progress="20"
        android:thumbTint="@color/colorPrimaryDark"
        android:progressTint="@color/colorPrimary"/>

use the color you need in thumbTint and progressTint. It is much faster! :)

Edit ofc you can use in combination with android:progressDrawable="@drawable/seekbar"

How can I verify if one list is a subset of another?

Assuming the items are hashable

>>> from collections import Counter
>>> not Counter([1, 2]) - Counter([1])
False
>>> not Counter([1, 2]) - Counter([1, 2])
True
>>> not Counter([1, 2, 2]) - Counter([1, 2])
False

If you don't care about duplicate items eg. [1, 2, 2] and [1, 2] then just use:

>>> set([1, 2, 2]).issubset([1, 2])
True

Is testing equality on the smaller list after an intersection the fastest way to do this?

.issubset will be the fastest way to do it. Checking the length before testing issubset will not improve speed because you still have O(N + M) items to iterate through and check.

How to send HTML email using linux command line

you should use "append" mode redirection >> instead of >

How to use a SQL SELECT statement with Access VBA

If you wish to use the bound column value, you can simply refer to the combo:

sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo

You can also refer to the column property:

sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"

Dim rs As DAO.Recordset     
Set rs = CurrentDB.OpenRecordset(sSQL)

strText = rs!AText
strText = rs.Fields(1)

In a textbox:

= DlookUp("AText","MyTable","ID=" & MyCombo)

*edited

How to start activity in another application?

If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

Hope it helps.

SQL JOIN vs IN performance?

The optimizer should be smart enough to give you the same result either way for normal queries. Check the execution plan and they should give you the same thing. If they don't, I would normally consider the JOIN to be faster. All systems are different, though, so you should profile the code on your system to be sure.

JPA and Hibernate - Criteria vs. JPQL or HQL

I don't want to kick a dead horse here, but it is important to mention that Criteria queries are now deprecated. Use HQL.

Looping through JSON with node.js

You can iterate through JavaScript objects this way:

for(var attributename in myobject){
    console.log(attributename+": "+myobject[attributename]);
}

myobject could be your json.data

Laravel Rule Validation for Numbers

If I correctly got what you want:

$rules = ['Fno' => 'digits_between:2,5', 'Lno' => 'numeric|min:2'];

or

$rules = ['Fno' => 'numeric|min:2|max:5', 'Lno' => 'numeric|min:2'];

For all the available rules: http://laravel.com/docs/4.2/validation#available-validation-rules

digits_between :min,max

The field under validation must have a length between the given min and max.

numeric

The field under validation must have a numeric value.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

SQL to add column and comment in table in single command

Query to add column with comment are :

alter table table_name 
add( "NISFLAG"    NUMBER(1,0) )

comment on column "ELIXIR"."PRD_INFO_1"."NISPRODGSTAPPL" is 'comment here'

commit;

Downloading a file from spring controllers

If you:

  • Don't want to load the whole file into a byte[] before sending to the response;
  • Want/need to send/download it via InputStream;
  • Want to have full control of the Mime Type and file name sent;
  • Have other @ControllerAdvice picking up exceptions for you (or not).

The code below is what you need:

@RequestMapping(value = "/stuff/{stuffId}", method = RequestMethod.GET)
public ResponseEntity<FileSystemResource> downloadStuff(@PathVariable int stuffId)
                                                                      throws IOException {
    String fullPath = stuffService.figureOutFileNameFor(stuffId);
    File file = new File(fullPath);
    long fileLength = file.length(); // this is ok, but see note below

    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentType("application/pdf");
    respHeaders.setContentLength(fileLength);
    respHeaders.setContentDispositionFormData("attachment", "fileNameIwant.pdf");

    return new ResponseEntity<FileSystemResource>(
        new FileSystemResource(file), respHeaders, HttpStatus.OK
    );
}

More on setContentLength(): First of all, the content-length header is optional per the HTTP 1.1 RFC. Still, if you can provide a value, it is better. To obtain such value, know that File#length() should be good enough in the general case, so it is a safe default choice.
In very specific scenarios, though, it can be slow, in which case you should have it stored previously (e.g. in the DB), not calculated on the fly. Slow scenarios include: if the file is very large, specially if it is on a remote system or something more elaborated like that - a database, maybe.



InputStreamResource

If your resource is not a file, e.g. you pick the data up from the DB, you should use InputStreamResource. Example:

    InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
    return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:

#!/bin/bash

export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost

You might be interested in How to run the sftp command with a password from Bash script?

JavaScript: Object Rename Key

Personally, the most effective way to rename keys in object without implementing extra heavy plugins and wheels:

var str = JSON.stringify(object);
str = str.replace(/oldKey/g, 'newKey');
str = str.replace(/oldKey2/g, 'newKey2');

object = JSON.parse(str);

You can also wrap it in try-catch if your object has invalid structure. Works perfectly :)

How to check if a value exists in a dictionary (python)

Use dictionary views:

if x in d.viewvalues():
    dosomething()..

Case objects vs Enumerations in Scala

Case objects already return their name for their toString methods, so passing it in separately is unnecessary. Here is a version similar to jho's (convenience methods omitted for brevity):

trait Enum[A] {
  trait Value { self: A => }
  val values: List[A]
}

sealed trait Currency extends Currency.Value
object Currency extends Enum[Currency] {
  case object EUR extends Currency
  case object GBP extends Currency
  val values = List(EUR, GBP)
}

Objects are lazy; by using vals instead we can drop the list but have to repeat the name:

trait Enum[A <: {def name: String}] {
  trait Value { self: A =>
    _values :+= this
  }
  private var _values = List.empty[A]
  def values = _values
}

sealed abstract class Currency(val name: String) extends Currency.Value
object Currency extends Enum[Currency] {
  val EUR = new Currency("EUR") {}
  val GBP = new Currency("GBP") {}
}

If you don't mind some cheating, you can pre-load your enumeration values using the reflection API or something like Google Reflections. Non-lazy case objects give you the cleanest syntax:

trait Enum[A] {
  trait Value { self: A =>
    _values :+= this
  }
  private var _values = List.empty[A]
  def values = _values
}

sealed trait Currency extends Currency.Value
object Currency extends Enum[Currency] {
  case object EUR extends Currency
  case object GBP extends Currency
}

Nice and clean, with all the advantages of case classes and Java enumerations. Personally, I define the enumeration values outside of the object to better match idiomatic Scala code:

object Currency extends Enum[Currency]
sealed trait Currency extends Currency.Value
case object EUR extends Currency
case object GBP extends Currency

How to find which git branch I am on when my disk is mounted on other server

Our git repo disk is mounted on AIX box to do BUILD.

It sounds like you mounted the drive on which the git repository is stored on another server, and you are asking how to modify that. If that is the case, this is a bad idea.

The build server should have its own copy of the git repository, and it will be locally managed by git on the build server. The build server's repository will be connected to the "main" git repository with a "remote", and you can issue the command git pull to update the local repository on the build server.

If you don't want to go to the trouble of setting up SSH or a gitolite server or something similar, you can use a file path as the "remote" location. So you could continue to mount the Linux server's file system on the build server, but instead of running the build out of that mounted path, clone the repository into another folder and run it from there.

Execute a large SQL script (with GO commands)

If you don't want to go the SMO route you can search and replace "GO" for ";" and the query as you would. Note that soly the the last result set will be returned.

What is the difference between MVC and MVVM?

MVC is a controlled environment and MVVM is a reactive environment.

In a controlled environment you should have less code and a common source of logic; which should always live within the controller. However; in the web world MVC easily gets divided into view creation logic and view dynamic logic. Creation lives on the server and dynamic lives on the client. You see this a lot with ASP.NET MVC combined with AngularJS whereas the server will create a View and pass in a Model and send it to the client. The client will then interact with the View in which case AngularJS steps in to as a local controller. Once submitted the Model or a new Model is passed back to the server controller and handled. (Thus the cycle continues and there are a lot of other translations of this handling when working with sockets or AJAX etc but over all the architecture is identical.)

MVVM is a reactive environment meaning you typically write code (such as triggers) that will activate based on some event. In XAML, where MVVM thrives, this is all easily done with the built in databinding framework BUT as mentioned this will work on any system in any View with any programming language. It is not MS specific. The ViewModel fires (usually a property changed event) and the View reacts to it based on whatever triggers you create. This can get technical but the bottom line is the View is stateless and without logic. It simply changes state based on values. Furthermore, ViewModels are stateless with very little logic, and Models are the State with essentially Zero logic as they should only maintain state. I describe this as application state (Model), state translator (ViewModel), and then the visual state / interaction (View).

In an MVC desktop or client side application you should have a Model, and the Model should be used by the Controller. Based on the Model the controller will modify the View. Views are usually tied to Controllers with Interfaces so that the Controller can work with a variety of Views. In ASP.NET the logic for MVC is slightly backwards on the server as the Controller manages the Models and passes the Models to a selected View. The View is then filled with data based on the model and has it's own logic (usually another MVC set such as done with AngularJS). People will argue and get this confused with application MVC and try to do both at which point maintaining the project will eventually become a disaster. ALWAYS put the logic and control in one location when using MVC. DO NOT write View logic in the code behind of the View (or in the View via JS for web) to accommodate Controller or Model data. Let the Controller change the View. The ONLY logic that should live in a View is whatever it takes to create and run via the Interface it's using. An example of this is submitting a username and password. Whether desktop or web page (on client) the Controller should handle the submit process whenever the View fires the Submit action. If done correctly you can always find your way around an MVC web or local app easily.

MVVM is personally my favorite as it's completely reactive. If a Model changes state the ViewModel listens and translates that state and that's it!!! The View is then listening to the ViewModel for state change and it also updates based on the translation from the ViewModel. Some people call it pure MVVM but there's really only one and I don't care how you argue it and it's always Pure MVVM where the View contains absolutely no logic.

Here's a slight example: Let's say the you want to have a menu slide in on a button press. In MVC you will have a MenuPressed action in your interface. The Controller will know when you click the Menu button and then tell the View to slide in the Menu based on another Interface method such as SlideMenuIn. A round trip for what reason? Incase the Controller decides you can't or wants to do something else instead that's why. The Controller should be in charge of the View with the View doing nothing unless the Controller says so. HOWEVER; in MVVM the slide menu in animation should be built in and generic and instead of being told to slide it in will do so based on some value. So it listens to the ViewModel and when the ViewModel says, IsMenuActive = true (or however) the animation for that takes place. Now, with that said I want to make another point REALLY CLEAR and PLEASE pay attention. IsMenuActive is probably BAD MVVM or ViewModel design. When designing a ViewModel you should never assume a View will have any features at all and just pass translated model state. That way if you decide to change your View to remove the Menu and just show the data / options another way, the ViewModel doesn't care. So how would you manage the Menu? When the data makes sense that's how. So, one way to do this is to give the Menu a list of options (probably an array of inner ViewModels). If that list has data, the Menu then knows to open via the trigger, if not then it knows to hide via the trigger. You simply have data for the menu or not in the ViewModel. DO NOT decide to show / hide that data in the ViewModel.. simply translate the state of the Model. This way the View is completely reactive and generic and can be used in many different situations.

All of this probably makes absolutely no sense if you're not already at least slightly familiar with the architecture of each and learning it can be very confusing as you'll find ALOT OF BAD information on the net.

So... things to keep in mind to get this right. Decide up front how to design your application and STICK TO IT.

If you do MVC, which is great, then make sure you Controller is manageable and in full control of your View. If you have a large View consider adding controls to the View that have different Controllers. JUST DON'T cascade those controllers to different controllers. Very frustrating to maintain. Take a moment and design things separately in a way that will work as separate components... And always let the Controller tell the Model to commit or persist storage. The ideal dependency setup for MVC in is View ? Controller ? Model or with ASP.NET (don't get me started) Model ? View ? Controller ? Model (where Model can be the same or a totally different Model from Controller to View) ...of course the only need to know of Controller in View at this point is mostly for endpoint reference to know where back to pass a Model.

If you do MVVM, I bless your kind soul, but take the time to do it RIGHT! Do not use interfaces for one. Let your View decide how it's going to look based on values. Play with the View with Mock data. If you end up having a View that is showing you a Menu (as per the example) even though you didn't want it at the time then GOOD. You're view is working as it should and reacting based on the values as it should. Just add a few more requirements to your trigger to make sure this doesn't happen when the ViewModel is in a particular translated state or command the ViewModel to empty this state. In your ViewModel DO NOT remove this with internal logic either as if you're deciding from there whether or not the View should see it. Remember you can't assume there is a menu or not in the ViewModel. And finally, the Model should just allow you to change and most likely store state. This is where validation and all will occur; for example, if the Model can't modify the state then it will simply flag itself as dirty or something. When the ViewModel realizes this it will translate what's dirty, and the View will then realize this and show some information via another trigger. All data in the View can be binded to the ViewModel so everything can be dynamic only the Model and ViewModel has absolutely no idea about how the View will react to the binding. As a matter of fact the Model has no idea of a ViewModel either. When setting up dependencies they should point like so and only like so View ? ViewModel ? Model (and a side note here... and this will probably get argued as well but I don't care... DO NOT PASS THE MODEL to the VIEW unless that MODEL is immutable; otherwise wrap it with a proper ViewModel. The View should not see a model period. I give a rats crack what demo you've seen or how you've done it, that's wrong.)

Here's my final tip... Look at a well designed, yet very simple, MVC application and do the same for an MVVM application. One will have more control with limited to zero flexibility while the other will have no control and unlimited flexibility.

A controlled environment is good for managing the entire application from a set of controllers or (a single source) while a reactive environment can be broken up into separate repositories with absolutely no idea of what the rest of the application is doing. Micro managing vs free management.

If I haven't confused you enough try contacting me... I don't mind going over this in full detail with illustration and examples.

At the end of the day we're all programmers and with that anarchy lives within us when coding... So rules will be broken, theories will change, and all of this will end up hog wash... But when working on large projects and on large teams, it really helps to agree on a design pattern and enforce it. One day it will make the small extra steps taken in the beginning become leaps and bounds of savings later.

Django 1.7 - makemigrations not detecting changes

Make sure your model is not abstract. I actually made that mistake and it took a while, so I thought I'd post it.

Get time in milliseconds using C#

I use the following class. I found it on the Internet once, postulated to be the best NOW().

/// <summary>Class to get current timestamp with enough precision</summary>
static class CurrentMillis
{
    private static readonly DateTime Jan1St1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    /// <summary>Get extra long current timestamp</summary>
    public static long Millis { get { return (long)((DateTime.UtcNow - Jan1St1970).TotalMilliseconds); } }
}

Source unknown.

Python: Converting from ISO-8859-1/latin1 to UTF-8

Decode to Unicode, encode the results to UTF8.

apple.decode('latin1').encode('utf8')

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

RGB to hex and hex to RGB

Using combining anonymous functions and Array.map for a cleaner; more streamlined look.

_x000D_
_x000D_
var write=function(str){document.body.innerHTML=JSON.stringify(str,null,'    ');};_x000D_
_x000D_
function hexToRgb(hex, asObj) {_x000D_
  return (function(res) {_x000D_
    return res == null ? null : (function(parts) {_x000D_
      return !asObj ? parts : { r : parts[0], g : parts[1], b : parts[2] }_x000D_
    }(res.slice(1,4).map(function(val) { return parseInt(val, 16); })));_x000D_
  }(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)));_x000D_
}_x000D_
_x000D_
function rgbToHex(r, g, b) {_x000D_
  return (function(values) {_x000D_
    return '#' + values.map(function(intVal) {_x000D_
      return (function(hexVal) {_x000D_
        return hexVal.length == 1 ? "0" + hexVal : hexVal;_x000D_
      }(intVal.toString(16)));_x000D_
    }).join('');_x000D_
  }(arguments.length === 1 ? Array.isArray(r) ? r : [r.r, r.g, r.b] : [r, g, b]))_x000D_
}_x000D_
_x000D_
// Prints: { r: 255, g: 127, b: 92 }_x000D_
write(hexToRgb(rgbToHex(hexToRgb(rgbToHex(255, 127, 92), true)), true));
_x000D_
body{font-family:monospace;white-space:pre}
_x000D_
_x000D_
_x000D_

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

MySQL Trigger after update only if row has changed

I cant comment, so just beware, that if your column supports NULL values, OLD.x<>NEW.x isnt enough, because

SELECT IF(1<>NULL,1,0)

returns 0 as same as

NULL<>NULL 1<>NULL 0<>NULL 'AAA'<>NULL

So it will not track changes FROM and TO NULL

The correct way in this scenario is

((OLD.x IS NULL AND NEW.x IS NOT NULL) OR (OLD.x IS NOT NULL AND NEW.x IS NULL) OR (OLD.x<>NEW.x))

How to get the width and height of an android.widget.ImageView?

If you have created multiple images dynamically than try this one:

// initialize your images array

private ImageView myImages[] = new ImageView[your_array_length];

// create programatically and add to parent view

 for (int i = 0; i < your_array_length; i++) {
                myImages[i] = new ImageView(this);
                myImages[i].setId(i + 1);
                myImages[i].setBackgroundResource(your_array[i]);
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                        frontWidth[i], frontHeight[i]);
                ((MarginLayoutParams) params).setMargins(frontX_axis[i],
                        frontY_axis[i], 0, 0);
                myImages[i].setAdjustViewBounds(true);
                myImages[i].setLayoutParams(params);

                if (getIntent() != null && i != your_array,length) {
                    final int j = i;
                    myImages[j].getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                        public boolean onPreDraw() {
                            myImages[j].getViewTreeObserver().removeOnPreDrawListener(this);
                    finalHeight = myImages[j].getMeasuredHeight();
                        finalWidth = myImages[j].getMeasuredWidth();
                    your_textview.setText("Height: " + finalHeight + " Width: " + finalWidth);
                            return true;
                        }
                    });
                }
                your_parent_layout.addView(myImages[i], params);
            }

// That's it. Happy Coding.

Creating a simple login form

Check it - You can try this code for your login form design as you ask thank you.

Explain css -

First, we define property font style and width And after that I have defined form id to set background image and the border And after that I have to define the header text in tag and after that I have added new and define by.New to set background properties and width. Thanks

Create a file index.html

<!DOCTYPE html>
<html>
   <head>
      <link rel="stylesheet" href="style.css">
   </head>
   <body>
      <div id="login_form">
         <div class="new"><span>enter login details</span></div>
         <!-- This is your header text-->
         <form name="f1" method="post" action="login.php" id="f1">
            <table>
               <tr>
                  <td class="f1_label">User Name :</td>
                  <!-- This is your first Input Box Label-->
                  <td>
                     <input type="text" name="username" value="" /><!-- This is your first Input Box-->
                  </td>
               </tr>
               <tr>
                  <td class="f1_label">Password  :</td>
                  <!-- This is your Second Input Box Label-->
                  <td>
                     <input type="password" name="password" value=""  /><!-- This is your Second Input Box -->
                  </td>
               </tr>
               <tr>
                  <td>
                     <input type="submit" name="login" value="Log In" style="font-size:18px; " /><!-- This is your submit button -->
                  </td>
               </tr>
            </table>
         </form>
      </div>
   </body>
</html>

Create css file style.css

body {
    font-style: italic;
    width: 50%;
    margin: 0px auto;
}

#login_form {}

#f1 {
    background-color: #FFF;
    border-style: solid;
    border-width: 1px;
    padding: 23px 1px 20px 114px;
}

.f1_label {
    white-space: nowrap;
}

span {
    color: white;
}

.new {
    background: black;
    text-align: center;
}

How do I find the version of Apache running without access to the command line?

If they have error pages enabled, you can go to a non-existent page and look at the bottom of the 404 page.

iPhone App Development on Ubuntu

Not officially, no. It's just Objective-C though and the compiler's open source - you could probably get the headers and compile it and somehow get the binary on the device. Another option is compiling on the device. All these options will require jailbreaking though.
A Mac Mini is just $599...

What is a postback?

A post back is anything that cause the page from the client's web browser to be pushed back to the server.

There's alot of info out there, search google for postbacks.

Most of the time, any ASP control will cause a post back (button/link click) but some don't unless you tell them to (checkbox/combobox)

How can I mock the JavaScript window object using Jest?

I found an easy way to do it: delete and replace

describe('Test case', () => {
  const { open } = window;

  beforeAll(() => {
    // Delete the existing
    delete window.open;
    // Replace with the custom value
    window.open = jest.fn();
    // Works for `location` too, eg:
    // window.location = { origin: 'http://localhost:3100' };
  });

  afterAll(() => {
    // Restore original
    window.open = open;
  });

  it('correct url is called', () => {
    statementService.openStatementsReport(111);
    expect(window.open).toBeCalled(); // Happy happy, joy joy
  });
});

Why is the minidlna database not being refreshed?

There is a patch for the sourcecode of minidlna at sourceforge available that does not make a full rescan, but a kind of incremental scan. That worked fine, but with some later version, the patch is broken. See here Link to SF

Regards Gerry

How to set the text/value/content of an `Entry` widget using a button in tkinter

One way would be to inherit a new class,EntryWithSet, and defining set method that makes use of delete and insert methods of the Entry class objects:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


class EntryWithSet(tk.Entry):
    """
    A subclass to Entry that has a set method for setting its text to
    a given string, much like a Variable class.
    """

    def __init__(self, master, *args, **kwargs):
        tk.Entry.__init__(self, master, *args, **kwargs)


    def set(self, text_string):
        """
        Sets the object's text to text_string.
        """

        self.delete('0', 'end')
        self.insert('0', text_string)


def on_button_click():
    import random, string
    rand_str = ''.join(random.choice(string.ascii_letters) for _ in range(19))
    entry.set(rand_str)


if __name__ == '__main__':
    root = tk.Tk()
    entry = EntryWithSet(root)
    entry.pack()
    tk.Button(root, text="Set", command=on_button_click).pack()
    tk.mainloop()

how to open a jar file in Eclipse

The jar file is just an executable java program. If you want to modify the code, you have to open the .java files.

How do I read all classes from a Java package in the classpath?

Scannotation and Reflections use class path scanning approach:

Reflections reflections = new Reflections("my.package");
Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);

Another approach is to use Java Pluggable Annotation Processing API to write annotation processor which will collect all annotated classes at compile time and build the index file for runtime use. This mechanism is implemented in ClassIndex library:

Iterable<Class> classes = ClassIndex.getPackageClasses("my.package");

How to get unique device hardware id in Android?

I use following code to get Android id.

String android_id = Secure.getString(this.getContentResolver(),
            Secure.ANDROID_ID);

Log.d("Android","Android ID : "+android_id);

enter image description here

How do I get the old value of a changed cell in Excel VBA?

Place the following in the CODE MODULE of a WORKSHEET to track the last value for every cell in the used range:

Option Explicit

Private r As Range
Private Const d = "||"

Public Function ValueLast(r As Range)
    On Error Resume Next
    ValueLast = Split(r.ID, d)(1)
End Function

Private Sub Worksheet_Activate()
    For Each r In Me.UsedRange: Record r: Next
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    For Each r In Target: Record r: Next
End Sub

Private Sub Record(r)
    r.ID = r.Value & d & Split(r.ID, d)(0)
End Sub

And that's it.

This solution uses the obscure and almost never used Range.ID property, which allows the old values to persist when the workbook is saved and closed.

At any time you can get at the old value of a cell and it will indeed be different than a new current value:

With Sheet1
    MsgBox .[a1].Value
    MsgBox .ValueLast(.[a1])
End With

Using multiple parameters in URL in express

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

How to enable C++17 compiling in Visual Studio?

MSBuild (Visual Studio project/solution *.vcproj/*.sln):

Add to Additional options in Project Settings: /std:c++latest to enable latest features - currently C++17 as of VS2017, VS2015 Update 3.

https://blogs.msdn.microsoft.com/vcblog/2016/06/07/standards-version-switches-in-the-compiler/

/permissive- will disable non-standard C++ extensions and will enable standard conformance in VS2017.

https://blogs.msdn.microsoft.com/vcblog/2016/11/16/permissive-switch/

EDIT (Oct 2018): The latest VS2017 features are documented here:

https://docs.microsoft.com/en-gb/cpp/build/reference/std-specify-language-standard-version

VS2017 supports: /std:[c++14|c++17|c++latest] now. These flags can be set via the project's property pages:

To set this compiler option in the Visual Studio development environment

  1. Open the project's Property Pages dialog box. For details, see Working with Project Properties.
  2. Select Configuration Properties, C/C++, Language.
  3. In C++ Language Standard, choose the language standard to support from the dropdown control, then choose OK or Apply to save your changes.

CMake:

Visual Studio 2017 (15.7+) supports CMake projects. CMake makes it possible to enable modern C++ features in various ways. The most basic option is to enable a modern C++ standard by setting a target's property in CMakeLists.txt:

add_library (${PROJECT_NAME})
set_property (TARGET ${PROJECT_NAME}
  PROPERTY
    # Enable C++17 standard compliance
    CXX_STANDARD 17
)

In the case of an interface library:

add_library (${PROJECT_NAME} INTERFACE)
target_compile_features (${PROJECT_NAME}
  INTERFACE
    # Enable C++17 standard compliance
    cxx_std_17
)

How to ignore the first line of data when processing CSV data?

Well, my mini wrapper library would do the job as well.

>>> import pyexcel as pe
>>> data = pe.load('all16.csv', name_columns_by_row=0)
>>> min(data.column[1])

Meanwhile, if you know what header column index one is, for example "Column 1", you can do this instead:

>>> min(data.column["Column 1"])

How to remove application from app listings on Android Developer Console

No, you cannot delete the application once you have published it in Google Play. Google will keep all the apk files. But you can unpublish the version, if you dont want that version to be availaible to user.

hibernate: LazyInitializationException: could not initialize proxy

The problem is that you are trying to access a collection in an object that is detached. You need to re-attach the object before accessing the collection to the current session. You can do that through

session.update(object);

Using lazy=false is not a good solution because you are throwing away the Lazy Initialization feature of hibernate. When lazy=false, the collection is loaded in memory at the same time that the object is requested. This means that if we have a collection with 1000 items, they all will be loaded in memory, despite we are going to access them or not. And this is not good.

Please read this article where it explains the problem, the possible solutions and why is implemented this way. Also, to understand Sessions and Transactions you must read this other article.

How to find the Number of CPU Cores via .NET/C#?

The the easyest way = Environment.ProcessorCount
Exemple from Environment.ProcessorCount Property

using System;

class Sample 
{
    public static void Main() 
    {
        Console.WriteLine("The number of processors " +
            "on this computer is {0}.", 
            Environment.ProcessorCount);
    }
}

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

$(form).ajaxSubmit is not a function

this is new function so you have to add other lib file after jQuery lib

<script src="http://malsup.github.com/jquery.form.js"></script>

it will work.. I have tested.. hope it will work for you..

Axios get access to response header fields

This really helped me, thanks Nick Uraltsev for your answer.

For those of you using nodejs with cors:

...
const cors = require('cors');

const corsOptions = {
  exposedHeaders: 'Authorization',
};

app.use(cors(corsOptions));
...

In the case you are sending the response in the way of res.header('Authorization', `Bearer ${token}`).send();

How to check if character is a letter in Javascript?

I`m posting here because I didn't want to post a new question. Assuming there aren't any single character declarations in the code, you can eval() the character to cause an error and check the type of the character. Something like:

_x000D_
_x000D_
function testForLetter(character) {_x000D_
  try {_x000D_
    //Variable declarations can't start with digits or operators_x000D_
    //If no error is thrown check for dollar or underscore. Those are the only nonletter characters that are allowed as identifiers_x000D_
    eval("let " + character + ";");_x000D_
    let regExSpecial = /[^\$_]/;_x000D_
    return regExSpecial.test(character);_x000D_
  } catch (error) {_x000D_
    return false;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(testForLetter("!")); //returns false;_x000D_
console.log(testForLetter("5")); //returns false;_x000D_
console.log(testForLetter("?")); //returns true;_x000D_
console.log(testForLetter("_")); //returns false;
_x000D_
_x000D_
_x000D_

How to get .app file of a xcode application

Build a release version, and the .app file is under build/Release folder of your project. Just copy it to Applications folder of your friend's machine. I don't think you need to build a installer.

Where to put default parameter value in C++?

You may do in either (according to standard), but remember, if your code is seeing the declaration without default argument(s) before the definition that contains default argument, then compilation error can come.

For example, if you include header containing function declaration without default argument list, thus compiler will look for that prototype as it is unaware of your default argument values and hence prototype won't match.

If you are putting function with default argument in definition, then include that file but I won't suggest that.

How does Junit @Rule work?

Rules are used to enhance the behaviour of each test method in a generic way. Junit rule intercept the test method and allows us to do something before a test method starts execution and after a test method has been executed.

For example, Using @Timeout rule we can set the timeout for all the tests.

public class TestApp {
    @Rule
    public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);

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

 }

@TemporaryFolder rule is used to create temporary folders, files. Every time the test method is executed, a temporary folder is created and it gets deleted after the execution of the method.

public class TempFolderTest {

 @Rule
 public TemporaryFolder tempFolder= new TemporaryFolder();

 @Test
 public void testTempFolder() throws IOException {
  File folder = tempFolder.newFolder("demos");
  File file = tempFolder.newFile("Hello.txt");

  assertEquals(folder.getName(), "demos");
  assertEquals(file.getName(), "Hello.txt");

 }


}

You can see examples of some in-built rules provided by junit at this link.

How do you remove a specific revision in the git history?

If all you want to do is remove the changes made in revision 3, you might want to use git revert.

Git revert simply creates a new revision with changes that undo all of the changes in the revision you are reverting.

What this means, is that you retain information about both the unwanted commit, and the commit that removes those changes.

This is probably a lot more friendly if it's at all possible the someone has pulled from your repository in the mean time, since the revert is basically just a standard commit.

What does InitializeComponent() do, and how does it work in WPF?

Looking at the code always helps too. That is, you can actually take a look at the generated partial class (that calls LoadComponent) by doing the following:

  1. Go to the Solution Explorer pane in the Visual Studio solution that you are interested in.
  2. There is a button in the tool bar of the Solution Explorer titled 'Show All Files'. Toggle that button.
  3. Now, expand the obj folder and then the Debug or Release folder (or whatever configuration you are building) and you will see a file titled YourClass.g.cs.

The YourClass.g.cs ... is the code for generated partial class. Again, if you open that up you can see the InitializeComponent method and how it calls LoadComponent ... and much more.

Taking multiple inputs from user in python

Python and all other imperative programming languages execute one command after another. Therefore, you can just write:

first  = raw_input('Enter 1st number: ')
second = raw_input('Enter second number: ')

Then, you can operate on the variables first and second. For example, you can convert the strings stored in them to integers and multiply them:

product = int(first) * int(second)
print('The product of the two is ' + str(product))

log4j:WARN No appenders could be found for logger in web.xml

If still help, verify the name of archive, it must be exact "log4j.properties" or "log4j.xml" (case sensitive), and follow the hint by "Alain O'Dea". I was geting the same error, but after make these changes everthing works fine. just like a charm :-). hope this helps.

Understanding Spring @Autowired usage

TL;DR

The @Autowired annotation spares you the need to do the wiring by yourself in the XML file (or any other way) and just finds for you what needs to be injected where and does that for you.

Full explanation

The @Autowired annotation allows you to skip configurations elsewhere of what to inject and just does it for you. Assuming your package is com.mycompany.movies you have to put this tag in your XML (application context file):

<context:component-scan base-package="com.mycompany.movies" />

This tag will do an auto-scanning. Assuming each class that has to become a bean is annotated with a correct annotation like @Component (for simple bean) or @Controller (for a servlet control) or @Repository (for DAO classes) and these classes are somewhere under the package com.mycompany.movies, Spring will find all of these and create a bean for each one. This is done in 2 scans of the classes - the first time it just searches for classes that need to become a bean and maps the injections it needs to be doing, and on the second scan it injects the beans. Of course, you can define your beans in the more traditional XML file or with an @Configuration class (or any combination of the three).

The @Autowired annotation tells Spring where an injection needs to occur. If you put it on a method setMovieFinder it understands (by the prefix set + the @Autowired annotation) that a bean needs to be injected. In the second scan, Spring searches for a bean of type MovieFinder, and if it finds such bean, it injects it to this method. If it finds two such beans you will get an Exception. To avoid the Exception, you can use the @Qualifier annotation and tell it which of the two beans to inject in the following manner:

@Qualifier("redBean")
class Red implements Color {
   // Class code here
}

@Qualifier("blueBean")
class Blue implements Color {
   // Class code here
}

Or if you prefer to declare the beans in your XML, it would look something like this:

<bean id="redBean" class="com.mycompany.movies.Red"/>

<bean id="blueBean" class="com.mycompany.movies.Blue"/>

In the @Autowired declaration, you need to also add the @Qualifier to tell which of the two color beans to inject:

@Autowired
@Qualifier("redBean")
public void setColor(Color color) {
  this.color = color;
}

If you don't want to use two annotations (the @Autowired and @Qualifier) you can use @Resource to combine these two:

@Resource(name="redBean")
public void setColor(Color color) {
  this.color = color;
}

The @Resource (you can read some extra data about it in the first comment on this answer) spares you the use of two annotations and instead, you only use one.

I'll just add two more comments:

  1. Good practice would be to use @Inject instead of @Autowired because it is not Spring-specific and is part of the JSR-330 standard.
  2. Another good practice would be to put the @Inject / @Autowired on a constructor instead of a method. If you put it on a constructor, you can validate that the injected beans are not null and fail fast when you try to start the application and avoid a NullPointerException when you need to actually use the bean.

Update: To complete the picture, I created a new question about the @Configuration class.

Why does my 'git branch' have no master?

I ran into the same issue and figured out the problem. When you initialize a repository there aren't actually any branches. When you start a project run git add . and then git commit and the master branch will be created.

Without checking anything in you have no master branch. In that case you need to follow the steps other people here have suggested.

How do I move a redis database from one server to another?

I also want to do the same thing: migrate a db from a standalone redis instance to a another redis instances(redis sentinel).

Because the data is not critical(session data), i will give https://github.com/yaauie/redis-copy a try.

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

The insert or replace query would insert a new record if id=1 does not already exist.

The update query would only oudate id=1 if it aready exist, it would not create a new record if it didn't exist.

What's the difference between a web site and a web application?

Both are 'websites' ( sites on the web ). So I would suggest that the question is easier to answer if worded in a different way. "What is the difference between a web-site which transforms data or information in a significant way, according to the point of view of some specific 'user' or 'customer' and a web-site that does not?"

From that it's easier to see that what we call a web-application is a system at a site on the web which takes input, acts on that input in a way that transforms it and produces output of value to some particular customer or user.

The other thing is more like a poster or brochure. At least to most of its audience. In the same way that a brochure may have been created using DTP software, a brochure site may still be managed via some sort of CMS or blogging software. To the owner of that site, the CMS is the web-application, but to the general public the same site may be seen as a simple brochure ( or 'website' ).

Returning http status code from Web Api controller

Another option:

return new NotModified();

public class NotModified : IHttpActionResult
{
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.NotModified);
        return Task.FromResult(response);
    }
}

Swift: Sort array of objects alphabetically

For those using Swift 3, the equivalent method for the accepted answer is:

movieArr.sorted { $0.Name < $1.Name }