Programs & Examples On #Die

die is a function in several languages. In Perl, die raises an exception or aborts the program. In PHP, die exits the program. In jQuery, the die method removes an event handler.

How to terminate the script in JavaScript?

This code will stop execution of all JavaScripts in current window:

_x000D_
_x000D_
    for(;;);
_x000D_
_x000D_
_x000D_

What are the differences in die() and exit() in PHP?

They sound about the same, however, the exit() also allows you to set the exit code of your PHP script.

Usually you don't really need this, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way.

Then you can use exit() and catch that later on. Die() however doesn't support that.

Die() always exists with code 0. So essentially a die() command does the following:

<?php
echo "I am going to die";
exit(0);
?>

Which is the same as:

<?php
die("I am going to die");
?>

Accessing a value in a tuple that is in a list

You can also use sequence unpacking with zip:

L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]

_, res = zip(*L)

print(res)

# (2, 3, 5, 4, 7, 7, 8)

This also creates a tuple _ from the discarded first elements. Extracting only the second is possible, but more verbose:

from itertools import islice

res = next(islice(zip(*L), 1, None))

How to change the type of a field?

To convert int32 to string in mongo without creating an array just add "" to your number :-)

db.foo.find( { 'mynum' : { $type : 16 } } ).forEach( function (x) {   
  x.mynum = x.mynum + ""; // convert int32 to string
  db.foo.save(x);
});

Can I change the checkbox size using CSS?

I was looking to make a checkbox that was just a little bit larger and looked at the source code for 37Signals Basecamp to find the following solution-

You can change the font size to make the checkbox slightly larger:

font-size: x-large;

Then, you can align the checkbox properly by doing:

vertical-align: top;
margin-top: 3px; /* change to center it */

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

May I suggest a php+css solution I used on my site? It's simple and no js problems :)

url to page: <a href="page.php?tab=menu1">link to menu1</a>

<?
$tab = $_GET['tab'];
?>
<ul class="nav nav-tabs">
  <li class="<? if ($tab=='menu1' OR $tab=='menu2') 
{
echo "";
} 
else {
echo "active";
}
?>"><a data-toggle="tab" href="#home">Prodotti</a></li>
  <li class="<? if ($tab=='menu1') 
{
echo "active";
} 
?>"><a data-toggle="tab" href="#menu1">News</a></li>
  <li class="<? if ($tab=='menu2') 
{
echo "active";
} 
?>"><a data-toggle="tab" href="#menu2">Gallery</a></li>
</ul>

<div class="tab-content">
  <div id="home" class="tab-pane fade <? if ($tab=='menu1' OR $tab=='menu2') 
{
echo "";
} 
else {
echo "in active";
}
?>
">
    <h3>Prodotti</h3>
    <p>Contenuto della pagina, zona prodotti</p>
  </div>
  <div id="menu1" class="tab-pane fade <? if ($tab=='menu1') 
{
echo "in active";
} 
?>">
    <h3>News</h3>
    <p>Qui ci saranno le news.</p>
  </div>
  <div id="menu2" class="tab-pane fade <? if ($tab=='menu2') 
{
echo "in active";
} 
?>">
    <h3>Gallery</h3>
    <p>Qui ci sarà la gallery</p>
  </div>
</div>

Eclipse cannot load SWT libraries

on my Ubuntu 12.04 32 bit. I edit the command to:

ln -s /usr/lib/jni/libswt-* ~/.swt/lib/linux/x86/

And on Ubuntu 12.04 64 bit try:

ln -s /usr/lib/jni/libswt-* ~/.swt/lib/linux/x86_64/

javascript change background color on click

If you want change background color on button click, you should use JavaScript function and change a style in the HTML page.

function chBackcolor(color) {
   document.body.style.background = color;
}

It is a function in JavaScript for change color, and you will be call this function in your event, for example :

<input type="button" onclick="chBackcolor('red');">

I recommend to use jQuery for this.

If you want it only for some seconds, you can use setTimeout function:

window.setTimeout("chBackColor()",10000);

How to convert byte array to string and vice versa?

The "proper conversion" between byte[] and String is to explicitly state the encoding you want to use. If you start with a byte[] and it does not in fact contain text data, there is no "proper conversion". Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.

If you really must use a String to hold binary data then the safest way is to use Base64 encoding.

HTML: How to limit file upload to be only images?

Edited

If things were as they SHOULD be, you could do this via the "Accept" attribute.

http://www.webmasterworld.com/forum21/6310.htm

However, browsers pretty much ignore this, so this is irrelavant. The short answer is, i don't think there is a way to do it in HTML. You'd have to check it server-side instead.

The following older post has some information that could help you with alternatives.

File input 'accept' attribute - is it useful?

How to uncheck a radio button?

Try

$(this).attr("checked" , false );

Run a single migration file

Method 1 :

rake db:migrate:up VERSION=20080906120000

Method 2:

In Rails Console 1. Copy paste the migration class in console (say add_name_to_user.rb) 2. Then in console, type the following

Sharding.run_on_all_shards{AddNameToUser.up}

It is done!!

How to check if two arrays are equal with JavaScript?

Check every each value by a for loop once you checked the size of the array.

function equalArray(a, b) {
    if (a.length === b.length) {
        for (var i = 0; i < a.length; i++) {
            if (a[i] !== b[i]) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}

Combining (concatenating) date and time into a datetime

An easier solution (tested on SQL Server 2014 SP1 CU6)

Code:

DECLARE @Date date = SYSDATETIME();

DECLARE @Time time(0) = SYSDATETIME();

SELECT CAST(CONCAT(@Date, ' ', @Time) AS datetime2(0));

This would also work given a table with a specific date and a specific time field. I use this method frequently given that we have vendor data that uses date and time in two separate fields.

Eclipse projects not showing up after placing project files in workspace/projects

I had the same problem over and over again the solution that a have found works for now

  1. Close Eclipse.
  2. go to workspace.metadata.plugins
  3. remove org.eclipse.core.resources
  4. Start Eclipse
  5. Do File->Import
  6. General->Existing Projects into Workspace and import all the project from the workspace

what are the .map files used for in Bootstrap 3.x?

These are source maps. Provide these alongside compressed source files; developer tools such as those in Firefox and Chrome will use them to allow debugging as if the code was not compressed.

How to remove multiple deleted files in Git repository

You can use

git commit -m "remove files" -a
git push

After you had delete files manually.

What is the most efficient way to create HTML elements using jQuery?

I am using jquery.min v2.0.3 . It's for me better to use following:

var select = jQuery("#selecter");
jQuery("`<option/>`",{value: someValue, text: someText}).appendTo(select);

as following:

var select = jQuery("#selecter");
jQuery(document.createElement('option')).prop({value: someValue, text: someText}).appendTo(select);

Processing time of first code is much lower than second code.

How to parse XML in Bash?

While there are quite a few ready-made console utilities that might do what you want, it will probably take less time to write a couple of lines of code in a general-purpose programming language such as Python which you can easily extend and adapt to your needs.

Here is a python script which uses lxml for parsing — it takes the name of a file or a URL as the first parameter, an XPath expression as the second parameter, and prints the strings/nodes matching the given expression.

Example 1

#!/usr/bin/env python
import sys
from lxml import etree

tree = etree.parse(sys.argv[1])
xpath_expression = sys.argv[2]

#  a hack allowing to access the
#  default namespace (if defined) via the 'p:' prefix    
#  E.g. given a default namespaces such as 'xmlns="http://maven.apache.org/POM/4.0.0"'
#  an XPath of '//p:module' will return all the 'module' nodes
ns = tree.getroot().nsmap
if ns.keys() and None in ns:
    ns['p'] = ns.pop(None)
#   end of hack    

for e in tree.xpath(xpath_expression, namespaces=ns):
    if isinstance(e, str):
        print(e)
    else:
        print(e.text and e.text.strip() or etree.tostring(e, pretty_print=True))

lxml can be installed with pip install lxml. On ubuntu you can use sudo apt install python-lxml.

Usage

python xpath.py myfile.xml "//mynode"

lxml also accepts a URL as input:

python xpath.py http://www.feedforall.com/sample.xml "//link"

Note: If your XML has a default namespace with no prefix (e.g. xmlns=http://abc...) then you have to use the p prefix (provided by the 'hack') in your expressions, e.g. //p:module to get the modules from a pom.xml file. In case the p prefix is already mapped in your XML, then you'll need to modify the script to use another prefix.


Example 2

A one-off script which serves the narrow purpose of extracting module names from an apache maven file. Note how the node name (module) is prefixed with the default namespace {http://maven.apache.org/POM/4.0.0}:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modules>
        <module>cherries</module>
        <module>bananas</module>
        <module>pears</module>
    </modules>
</project>

module_extractor.py:

from lxml import etree
for _, e in etree.iterparse(open("pom.xml"), tag="{http://maven.apache.org/POM/4.0.0}module"):
    print(e.text)

removing html element styles via javascript

Remove removeProperty

_x000D_
_x000D_
var el=document.getElementById("id");


el.style.removeProperty('display')

console.log("display removed"+el.style["display"])

console.log("color "+el.style["color"])
_x000D_
<div id="id" style="display:block;color:red">s</div>
_x000D_
_x000D_
_x000D_

Find duplicate characters in a String and count the number of occurances using Java

Finding the duplicates in a String:

Example 1 : Using HashMap

public class a36 {
    public static void main(String[] args) {
        String a = "Gini Rani";
        fix(a);
    }//main
    public static void fix(String a ){
        Map<Character ,Integer> map = new HashMap<>();
        for (int i = 0; i <a.length() ; i++ ) {
        char ch = a.charAt(i);
                map.put(ch , map.getOrDefault(ch,0) +1 );
        }//for

       List<Character> list = new ArrayList<>();
       Set<Map.Entry<Character ,Integer> > entrySet = map.entrySet();

       for (  Map.Entry<Character ,Integer> entry : entrySet) {
             list.add( entry.getKey()  ); 

             System.out.printf(  " %s : %d %n" ,  entry.getKey(), entry.getValue()           );
       }//for
       System.out.println("Duplicate elements => " + list);

    }//fix
}

Example 2 : using Arrays.stream() in Java 8

public class a37 {
    public static void main(String[] args) {
        String aa = "Protijayi Gini";
        String[] stringarray = aa.split("");

    Map<String , Long> map =  Arrays.stream(stringarray)
        .collect(Collectors.groupingBy(c -> c , Collectors.counting()));
        map.forEach( (k, v) -> System.out.println(k + " : "+ v)        );
    }
}

Making a UITableView scroll when text field is selected

Here is how I made this work, which is a mixture of Sam Ho and Marcel W's answers, and some of my own bug fixes made to my crappy code. I was using a UITableViewController. The table now resizes correctly when the keyboard is shown.

1) In viewDidLoad I added:

self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

2) I had forgotten to call the super equivalents in viewWillAppear and awakeFromNib. I added these back in.

Avoid browser popup blockers

Based on Jason Sebring's very useful tip, and on the stuff covered here and there, I found a perfect solution for my case:

Pseudo code with Javascript snippets:

  1. immediately create a blank popup on user action

     var importantStuff = window.open('', '_blank');
    

    (Enrich the call to window.open with whatever additional options you need.)

    Optional: add some "waiting" info message. Examples:

    a) An external HTML page: replace the above line with

     var importantStuff = window.open('http://example.com/waiting.html', '_blank');
    

    b) Text: add the following line below the above one:

     importantStuff.document.write('Loading preview...');
    
  2. fill it with content when ready (when the AJAX call is returned, for instance)

     importantStuff.location.href = 'https://example.com/finally.html';
    

    Alternatively, you could close the window here if you don't need it after all (if ajax request fails, for example - thanks to @Goose for the comment):

     importantStuff.close();
    

I actually use this solution for a mailto redirection, and it works on all my browsers (windows 7, Android). The _blank bit helps for the mailto redirection to work on mobile, btw.

How to check certificate name and alias in keystore files?

You can run from Java code.

try {

        File file = new File(keystore location);
        InputStream is = new FileInputStream(file);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        String password = "password";
        keystore.load(is, password.toCharArray());


        Enumeration<String> enumeration = keystore.aliases();
        while(enumeration.hasMoreElements()) {
            String alias = enumeration.nextElement();
            System.out.println("alias name: " + alias);
            Certificate certificate = keystore.getCertificate(alias);
            System.out.println(certificate.toString());

        }

    } catch (java.security.cert.CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(null != is)
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

Certificate class holds all information about the keystore.

UPDATE- OBTAIN PRIVATE KEY

Key key = keyStore.getKey(alias, password.toCharArray());
String encodedKey = new Base64Encoder().encode(key.getEncoded());
System.out.println("key ? " + encodedKey);

@prateek Hope this is what you looking for!

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece (in core since Perl 5.10) also has a strftime function and by default overloads localtime and gmtime to return Time::Piece objects:

use Time::Piece;
print localtime->strftime('%Y-%m-%d');

or without the overridden localtime:

use Time::Piece (); 
print Time::Piece::localtime->strftime('%F %T');

CSS opacity only to background color, not the text on it?

Use:

background:url("location of image"); // Use an image with opacity

This method will work in all browsers.

Integrity constraint violation: 1452 Cannot add or update a child row:

In case someone is using Laravel and is getting this problem. I was getting this as well and the issue was in the order in which I was inserting the ids (i.e., the foreign keys) in the pivot table.

To be concrete, find below an example for a many to many relationship:

wordtokens <-> wordtoken_wordchunk <-> wordchunks

// wordtoken_wordchunk table
Schema::create('wordtoken_wordchunk', function(Blueprint $table) {
        $table->integer('wordtoken_id')->unsigned();
        $table->integer('wordchunk_id')->unsigned();

        $table->foreign('wordtoken_id')->references('id')->on('word_tokens')->onDelete('cascade');
        $table->foreign('wordchunk_id')->references('id')->on('wordchunks')->onDelete('cascade');

        $table->primary(['wordtoken_id', 'wordchunk_id']);
    });

// wordchunks table
Schema::create('wordchunks', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('text');
    });

// wordtokens table
Schema::create('word_tokens', function (Blueprint $table) {
        $table->increments('id');
        $table->string('text');
});

Now my models look like follows:

class WordToken extends Model
{
   public function wordchunks() {
      return $this->belongsToMany('App\Wordchunk');
   }
}

class Wordchunk extends Model
{

    public function wordTokens() {
        return $this->belongsToMany('App\WordToken', 'wordtoken_wordchunk', 'wordchunk_id', 'wordtoken_id');
    }
}

I fixed the problem by exchanging the order of 'wordchunk_id' and 'wordtoken_id' in the Wordchunk model.

For code completion, this is how I persist the models:

private function persistChunks($chunks) {
    foreach ($chunks as $chunk) {
        $model = new Wordchunk();
        $model->text = implode(' ', array_map(function($token) {return $token->text;}, $chunk));
        $tokenIds = array_map(function($token) {return $token->id;}, $chunk);
        $model->save();
        $model->wordTokens()->attach($tokenIds);
    }
}

fatal: git-write-tree: error building trees

Use:

git reset --mixed

instead of git reset --hard. You will not lose any changes.

How to call a method after a delay in Android

Similar solution but much cleaner to use

Write this function out side of class

fun delay(duration: Long, `do`: () -> Unit) {

    Handler().postDelayed(`do`, duration)

}

Usage:

delay(5000) {
    //Do your work here
}

replacing text in a file with Python

I might consider using a dict and re.sub for something like this:

import re
repldict = {'zero':'0', 'one':'1' ,'temp':'bob','garage':'nothing'}
def replfunc(match):
    return repldict[match.group(0)]

regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open('file.txt') as fin, open('fout.txt','w') as fout:
    for line in fin:
        fout.write(regex.sub(replfunc,line))

This has a slight advantage to replace in that it is a bit more robust to overlapping matches.

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

int main(int argc, char *argv[]){

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      perror("stat");
      return errno;
    }
    getcwd(currentPath, FILENAME_MAX);


    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  }
  closedir(dip);
  return 0;
}

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
    }

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
      }
    }

    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  }
  /*Changing back here is necessary because of how stat is done*/
    chdir("..");
    closedir(dip);
}

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    chdir("..");
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }

  else{
    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    chdir(currentPath);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }
}

Paging with LINQ for objects

There are two main options:

.NET >= 4.0 Dynamic LINQ:

  1. Add using System.Linq.Dynamic; at the top.
  2. Use: var people = people.AsQueryable().OrderBy("Make ASC, Year DESC").ToList();

You can also get it by NuGet.

.NET < 4.0 Extension Methods:

private static readonly Hashtable accessors = new Hashtable();

private static readonly Hashtable callSites = new Hashtable();

private static CallSite<Func<CallSite, object, object>> GetCallSiteLocked(string name) {
    var callSite = (CallSite<Func<CallSite, object, object>>)callSites[name];
    if(callSite == null)
    {
        callSites[name] = callSite = CallSite<Func<CallSite, object, object>>.Create(
                    Binder.GetMember(CSharpBinderFlags.None, name, typeof(AccessorCache),
                new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));
    }
    return callSite;
}

internal static Func<dynamic,object> GetAccessor(string name)
{
    Func<dynamic, object> accessor = (Func<dynamic, object>)accessors[name];
    if (accessor == null)
    {
        lock (accessors )
        {
            accessor = (Func<dynamic, object>)accessors[name];
            if (accessor == null)
            {
                if(name.IndexOf('.') >= 0) {
                    string[] props = name.Split('.');
                    CallSite<Func<CallSite, object, object>>[] arr = Array.ConvertAll(props, GetCallSiteLocked);
                    accessor = target =>
                    {
                        object val = (object)target;
                        for (int i = 0; i < arr.Length; i++)
                        {
                            var cs = arr[i];
                            val = cs.Target(cs, val);
                        }
                        return val;
                    };
                } else {
                    var callSite = GetCallSiteLocked(name);
                    accessor = target =>
                    {
                        return callSite.Target(callSite, (object)target);
                    };
                }
                accessors[name] = accessor;
            }
        }
    }
    return accessor;
}
public static IOrderedEnumerable<dynamic> OrderBy(this IEnumerable<dynamic> source, string property)
{
    return Enumerable.OrderBy<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> OrderByDescending(this IEnumerable<dynamic> source, string property)
{
    return Enumerable.OrderByDescending<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenBy(this IOrderedEnumerable<dynamic> source, string property)
{
    return Enumerable.ThenBy<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}
public static IOrderedEnumerable<dynamic> ThenByDescending(this IOrderedEnumerable<dynamic> source, string property)
{
    return Enumerable.ThenByDescending<dynamic, object>(source, AccessorCache.GetAccessor(property), Comparer<object>.Default);
}

Eclipse keyboard shortcut to indent source code to the left?

i'd rather go to menu source em click on "Cleanup Document"

Detect Route Change with react-router

You can make use of history.listen() function when trying to detect the route change. Considering you are using react-router v4, wrap your component with withRouter HOC to get access to the history prop.

history.listen() returns an unlisten function. You'd use this to unregister from listening.

You can configure your routes like

index.js

ReactDOM.render(
      <BrowserRouter>
            <AppContainer>
                   <Route exact path="/" Component={...} />
                   <Route exact path="/Home" Component={...} />
           </AppContainer>
        </BrowserRouter>,
  document.getElementById('root')
);

and then in AppContainer.js

class App extends Component {
  
  componentWillMount() {
    this.unlisten = this.props.history.listen((location, action) => {
      console.log("on route change");
    });
  }
  componentWillUnmount() {
      this.unlisten();
  }
  render() {
     return (
         <div>{this.props.children}</div>
      );
  }
}
export default withRouter(App);

From the history docs:

You can listen for changes to the current location using history.listen:

history.listen((location, action) => {
      console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

The location object implements a subset of the window.location interface, including:

**location.pathname** - The path of the URL
**location.search** - The URL query string
**location.hash** - The URL hash fragment

Locations may also have the following properties:

location.state - Some extra state for this location that does not reside in the URL (supported in createBrowserHistory and createMemoryHistory)

location.key - A unique string representing this location (supported in createBrowserHistory and createMemoryHistory)

The action is one of PUSH, REPLACE, or POP depending on how the user got to the current URL.

When you are using react-router v3 you can make use of history.listen() from history package as mentioned above or you can also make use browserHistory.listen()

You can configure and use your routes like

import {browserHistory} from 'react-router';

class App extends React.Component {

    componentDidMount() {
          this.unlisten = browserHistory.listen( location =>  {
                console.log('route changes');
                
           });
      
    }
    componentWillUnmount() {
        this.unlisten();
     
    }
    render() {
        return (
               <Route path="/" onChange={yourHandler} component={AppContainer}>
                   <IndexRoute component={StaticContainer}  />
                   <Route path="/a" component={ContainerA}  />
                   <Route path="/b" component={ContainerB}  />
            </Route>
        )
    }
} 

Find kth smallest element in a binary search tree in Optimum way

You can use iterative inorder traversal: http://en.wikipedia.org/wiki/Tree_traversal#Iterative_Traversal with a simple check for kth element after poping a node out of the stack.

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

you can try in this way if you are using thymeleaf

sec:authorize="hasAnyRole(T(com.orsbv.hcs.model.SystemRole).ADMIN.getName(),
               T(com.orsbv.hcs.model.SystemRole).SUPER_USER.getName(),'ROLE_MANAGEMENT')"

this will return true if the user has the mentioned roles,false otherwise.

Please note you have to use sec tag in your html declaration tag like this

<html xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

How do I format date in jQuery datetimepicker?

Newer versions of datetimepicker (I'm using is use 2.3.7) use format:"Y/m/d" not dateFormat...

so

jQuery('#timePicker').datetimepicker({
    format: 'd-m-y',
    value: new Date()
});

See http://xdsoft.net/jqplugins/datetimepicker/

Get the first item from an iterable that matches a condition

By using

(index for index, value in enumerate(the_iterable) if condition(value))

one can check the condition of the value of the first item in the_iterable, and obtain its index without the need to evaluate all of the items in the_iterable.

The complete expression to use is

first_index = next(index for index, value in enumerate(the_iterable) if condition(value))

Here first_index assumes the value of the first value identified in the expression discussed above.

Delete a single record from Entity Framework?

Here's a safe way:

using (var transitron = ctx.Database.BeginTransaction())
{
  try
  {
    var employer = new Employ { Id = 1 };
    ctx.Entry(employer).State = EntityState.Deleted;
    ctx.SaveChanges();
    transitron.Commit();
  }
  catch (Exception ex)
  {
    transitron.Rollback();
    //capture exception like: entity does not exist, Id property does not exist, etc...
  }
}

Here you can pile up all the changes you want, so you can do a series of deletion before the SaveChanges and Commit, so they will be applied only if they are all successful.

jquery count li elements inside ul -> length?

alert( "Size: " + $("li").size() ); 

or

alert( "Size: " + $("li").length );

You can find some examples of the .size() method here.

Using :: in C++

One use for the 'Unary Scope Resolution Operator' or 'Colon Colon Operator' is for local and global variable selection of identical names:

    #include <iostream>
    using namespace std;
    
    int variable = 20;
    
    int main()
    {
    float variable = 30;
    
    cout << "This is local to the main function: " << variable << endl;
    cout << "This is global to the main function: " << ::variable << endl;
    
    return 0;
    }

The resulting output would be:

This is local to the main function: 30

This is global to the main function: 20

Other uses could be: Defining a function from outside of a class, to access a static variable within a class or to use multiple inheritance.

How to compare dates in datetime fields in Postgresql?

When you compare update_date >= '2013-05-03' postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.

So for update_date = '2013-05-03 14:45:00' your expression will be that:

'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'

This is always false

To solve this problem cast update_date to date:

select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result

postgresql COUNT(DISTINCT ...) very slow

-- My default settings (this is basically a single-session machine, so work_mem is pretty high)
SET effective_cache_size='2048MB';
SET work_mem='16MB';

\echo original
EXPLAIN ANALYZE
SELECT
        COUNT (distinct val) as aantal
FROM one
        ;

\echo group by+count(*)
EXPLAIN ANALYZE
SELECT
        distinct val
       -- , COUNT(*)
FROM one
GROUP BY val;

\echo with CTE
EXPLAIN ANALYZE
WITH agg AS (
    SELECT distinct val
    FROM one
    GROUP BY val
    )
SELECT COUNT (*) as aantal
FROM agg
        ;

Results:

original                                                      QUERY PLAN                                                      
----------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=36448.06..36448.07 rows=1 width=4) (actual time=1766.472..1766.472 rows=1 loops=1)
   ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=31.371..185.914 rows=1499845 loops=1)
 Total runtime: 1766.642 ms
(3 rows)

group by+count(*)
                                                         QUERY PLAN                                                         
----------------------------------------------------------------------------------------------------------------------------
 HashAggregate  (cost=36464.31..36477.31 rows=1300 width=4) (actual time=412.470..412.598 rows=1300 loops=1)
   ->  HashAggregate  (cost=36448.06..36461.06 rows=1300 width=4) (actual time=412.066..412.203 rows=1300 loops=1)
         ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=26.134..166.846 rows=1499845 loops=1)
 Total runtime: 412.686 ms
(4 rows)

with CTE
                                                             QUERY PLAN                                                             
------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=36506.56..36506.57 rows=1 width=0) (actual time=408.239..408.239 rows=1 loops=1)
   CTE agg
     ->  HashAggregate  (cost=36464.31..36477.31 rows=1300 width=4) (actual time=407.704..407.847 rows=1300 loops=1)
           ->  HashAggregate  (cost=36448.06..36461.06 rows=1300 width=4) (actual time=407.320..407.467 rows=1300 loops=1)
                 ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=24.321..165.256 rows=1499845 loops=1)
       ->  CTE Scan on agg  (cost=0.00..26.00 rows=1300 width=0) (actual time=407.707..408.154 rows=1300 loops=1)
     Total runtime: 408.300 ms
    (7 rows)

The same plan as for the CTE could probably also be produced by other methods (window functions)

Difference between DOMContentLoaded and load events

See the difference yourself:

DEMO

From Microsoft IE

The DOMContentLoaded event fires when parsing of the current page is complete; the load event fires when all files have finished loading from all resources, including ads and images. DOMContentLoaded is a great event to use to hookup UI functionality to complex web pages.

From Mozilla Developer Network

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

Export multiple classes in ES6 modules

For exporting the instances of the classes you can use this syntax:

// export index.js
const Foo = require('./my/module/foo');
const Bar = require('./my/module/bar');

module.exports = {
    Foo : new Foo(),
    Bar : new Bar()
};

// import and run method
const {Foo,Bar} = require('module_name');
Foo.test();

LINQ select in C# dictionary

This will return all the values matching your key valueTitle

subList.SelectMany(m => m).Where(kvp => kvp.Key == "valueTitle").Select(k => k.Value).ToList();

How to access a dictionary key value present inside a list?

First of all don't use 'list' as variable name.

If you have simple dictionaries with unique keys then you can do the following(note that new dictionary object with all items from sub-dictionaries will be created):

res  = {}
for line in listOfDicts:
   res.update(line)
res['d']
>>> 4

Otherwise:

getValues = lambda key,inputData: [subVal[key] for subVal in inputData if key in subVal]
getValues('d', listOfDicts)
>>> [4]

Or very base:

def get_value(listOfDicts, key):
    for subVal in listOfDicts:
        if key in subVal:
            return subVal[key]

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

Make a dictionary in Python from input values

This is what we ended up using:

n = 3
d = dict(raw_input().split() for _ in range(n))
print d

Input:

A1023 CRT
A1029 Regulator
A1030 Therm

Output:

{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

How can I check if the array of objects have duplicate property values?

//checking duplicate elements in an array
var arr=[1,3,4,6,8,9,1,3,4,7];
var hp=new Map();
console.log(arr.sort());
var freq=0;
for(var i=1;i<arr.length;i++){
// console.log(arr[i-1]+" "+arr[i]);
if(arr[i]==arr[i-1]){
freq++;

}
else{
hp.set(arr[i-1],freq+1);
freq=0;
}
}
console.log(hp);

How is Java platform-independent when it needs a JVM to run?

Doesn't independent means that Java code should be able to run on any machine and would need no special software to be installed (JVM in this case has to be present in the machine)?

With Java, you can compile source code on Windows and the compiled code (bytecode to be precise) can be executed (interpreted) on any platform running a JVM. So yes you need a JVM but the JVM can run any compiled code, the compiled code is platform independent.

In other words, you have both portability of source code and portability of compiled code.

Like, for example, we need to have Turbo C Compiler in order to compile C/C++ source code and then execute it.. The machine has to have the C compiler.

The machine doesn't have to have a C compiler, the machine has to use a platform specific binary. With C or C++, the compiled code is specific to each architecture, it is platform independent.

In other words, with C / C++ you have portability of source code (with some discipline) but not portability of compiled code: you need to recompile for each architecture into platform specific binaries.

Finding the source code for built-in Python functions?

Since Python is open source you can read the source code.

To find out what file a particular module or function is implemented in you can usually print the __file__ attribute. Alternatively, you may use the inspect module, see the section Retrieving Source Code in the documentation of inspect.

For built-in classes and methods this is not so straightforward since inspect.getfile and inspect.getsource will return a type error stating that the object is built-in. However, many of the built-in types can be found in the Objects sub-directory of the Python source trunk. For example, see here for the implementation of the enumerate class or here for the implementation of the list type.

.htaccess not working apache

I cleared this use. By using this site click Here , follow the steps, the same steps follows upto the ubuntu version 18.04

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

We can use LIMIT like bellow:

Model::take(20)->get();

Position absolute but relative to parent

div#father {
    position: relative;
}
div#son1 {
    position: absolute;
    /* put your coords here */
}
div#son2 {
    position: absolute;
    /* put your coords here */
}

Horizontal scroll on overflow of table

I think your overflow should be on the outer container. You can also explicitly set a min width for the columns. Like this:

.search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }

Fiddle: http://jsfiddle.net/5WsEt/

MVC 4 Data Annotations "Display" Attribute

If two different views are sharing the same model (for instance, maybe one is for mobile output and one is regular), it could be nice to have the string reside in a single place: as metadata on the ViewModel.

Additionally, if you had an inherited version of the model that necessitated a different display, it could be useful. For instance:

public class BaseViewModel
{
    [Display(Name = "Basic Name")]
    public virtual string Name { get; set; }
}

public class OtherViewModel : BaseViewModel
{
    [Display(Name = "Customized Inherited Name")]
    public override string Name { get; set; }
}

I'll admit that that example is pretty contrived...

Those are the best arguments in favor of using the attribute that I can come up with. My personal opinion is that, for the most part, that sort of thing is best left to the markup.

I can't understand why this JAXB IllegalAnnotationException is thrown

This is because, by default, Jaxb when serializes a pojo, looks for the annotations over the public members(getters or setters) of the properties. But, you are providing annotations on fields. so, either change and set the annotations on setters or getters of properties, or sets the XmlAccessortype to field.

Option 1::

@XmlRootElement(name = "fields")
@XmlAccessorType(XmlAccessType.FIELD)
public class Fields {

        @XmlElement(name = "field")
        List<Field> fields = new ArrayList<Field>();
        //getter, setter
}

@XmlAccessorType(XmlAccessType.FIELD)
public class Field {

       @XmlAttribute(name = "mappedField")
       String mappedField;
       //getter,setter
}

Option 2::

@XmlRootElement(name = "fields")
public class Fields {

        List<Field> fields = new ArrayList<Field>();

        @XmlElement(name = "field")
        public List<Field> getFields() {

        }

        //setter
}

@XmlAccessorType(XmlAccessType.FIELD)
public class Field {

       String mappedField;

       @XmlAttribute(name = "mappedField")
       public String getMappedField() {

       }

        //setter
}

For more detail and depth, check the following JDK documentation http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/XmlAccessorType.html

T-sql - determine if value is integer

I think that there is something wrong with your database design. I think it is a really bad idea to mix varchar and numbers in one column? What is the reason for that?

Of course you can check if there are any chars other than [0-9], but imagine you have a 1m rows in table and your are checking every row. I think it won't work well.

Anyway if you really want to do it I suggest doing it on the client side.

Android textview outline text

I've just been trying to figure out how to do this and couldn't find a good guide online but eventually figured it out. As Steve Pomeroy suggested, you do have to do something more involved. In order to get the outlined text effect, you draw the text twice: once with a thick outline and then the second time we draw the main text over the outline. But, the task is made easier because you can very easily adapt one of the code samples provided with the SDK, namely the one under this name in your SDK directory: "/samples/android-/ApiDemos/src/com/example/android/apis/view/LabelView.java". Which can also found on the Android developer website here.

Depending on what you're doing, it's very easy to see you will only need to make minor modifications to that code, such as changing it to extend from TextView, etc. Before I discovered this sample I forgot to override onMeasure() (which you must do in addition to overriding onDraw() as is mentioned in the "Building Custom Components" guide on the Android Developer website), which is part of why I was having trouble.

Once you've done that, you can do what I did:

public class TextViewOutline extends TextView {

private Paint mTextPaint;
private Paint mTextPaintOutline; //add another paint attribute for your outline
...
//modify initTextViewOutline to setup the outline style
   private void initTextViewOutline() {
       mTextPaint = new Paint();
       mTextPaint.setAntiAlias(true);
       mTextPaint.setTextSize(16);
       mTextPaint.setColor(0xFF000000);
       mTextPaint.setStyle(Paint.Style.FILL);

       mTextPaintOutline = new Paint();
       mTextPaintOutline.setAntiAlias(true);
       mTextPaintOutline.setTextSize(16);
       mTextPaintOutline.setColor(0xFF000000);
       mTextPaintOutline.setStyle(Paint.Style.STROKE);
       mTextPaintOutline.setStrokeWidth(4);

       setPadding(3, 3, 3, 3);
}
...
//make sure to update other methods you've overridden to handle your new paint object
...
//and finally draw the text, mAscent refers to a member attribute which had
//a value assigned to it in the measureHeight and Width methods
   @Override
   protected void onDraw(Canvas canvas) {
       super.onDraw(canvas);
       canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, 
           mTextPaintOutline);
       canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, mTextPaint);
   }

So, in order to get the outlined text effect, you draw the text twice: once with a thick outline and then the second time we draw the main text over the outline.

Convert a date format in epoch

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:

String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454

Date.getTime() returns the epoch time in milliseconds.

Read a file line by line assigning the value to a variable

I encourage you to use the -r flag for read which stands for:

-r  Do not treat a backslash character in any special way. Consider each
    backslash to be part of the input line.

I am citing from man 1 read.

Another thing is to take a filename as an argument.

Here is updated code:

#!/usr/bin/bash
filename="$1"
while read -r line; do
    name="$line"
    echo "Name read from file - $name"
done < "$filename"

Get element by id - Angular2

(<HTMLInputElement>document.getElementById('loginInput')).value = '123';

Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.

UPDATE::

This can also be done using ViewChild with #localvariable as shown here, as mentioned in here

<textarea  #someVar  id="tasknote"
                  name="tasknote"
                  [(ngModel)]="taskNote"
                  placeholder="{{ notePlaceholder }}"
                  style="background-color: pink"
                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} 

</textarea>

import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer2) {}

ngAfterViewInit() {
      console.log(this.rd); 
      this.el.nativeElement.focus();      //<<<=====same as oldest way
}

Removing App ID from Developer Connection

Does deleting the AppID do anything to disable versions of an Enterprise distributed app "in the wild" ??

If not, is there any way to kill off an Enterprise app before it's expiry?

CSS customized scroll bar in div

This is what Google has used in some of its applications for a long time now. See in the code that, if you apply next classes, they somehow hide the scrollbar in Chrome, but it still works.

The classes are jfk-scrollbar, jfk-scrollbar-borderless, and jfk-scrollbar-dark

_x000D_
_x000D_
.testg{ border:1px solid black;  max-height:150px;  overflow-y: scroll; overflow-x: hidden; width: 250px;}_x000D_
.content{ height: 700px}_x000D_
_x000D_
/* The google css code for scrollbars */_x000D_
::-webkit-scrollbar {_x000D_
    height: 16px;_x000D_
    overflow: visible;_x000D_
    width: 16px_x000D_
}_x000D_
::-webkit-scrollbar-button {_x000D_
    height: 0;_x000D_
    width: 0_x000D_
}_x000D_
::-webkit-scrollbar-track {_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px_x000D_
}_x000D_
::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 7px 0 0_x000D_
}_x000D_
::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .1)_x000D_
}_x000D_
::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .1)_x000D_
}_x000D_
::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .2)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .2)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .25), inset -1px 0 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), inset 0 -1px 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(0, 0, 0, .2);_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px;_x000D_
    min-height: 28px;_x000D_
    padding: 100px 0 0;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 7px 0 0;_x000D_
    padding: 0 0 0 100px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(0, 0, 0, .4);_x000D_
    box-shadow: inset 1px 1px 1px rgba(0, 0, 0, .25)_x000D_
}_x000D_
::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    box-shadow: inset 1px 1px 3px rgba(0, 0, 0, 0.35)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(255, 255, 255, .3);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset 0 -1px 0 rgba(255, 255, 255, .1)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb:horizontal {_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset -1px 0 0 rgba(255, 255, 255, .1)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(255, 255, 255, .6);_x000D_
    box-shadow: inset 1px 1px 1px rgba(255, 255, 255, .37)_x000D_
}_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(255, 255, 255, .75);_x000D_
    box-shadow: inset 1px 1px 3px rgba(255, 255, 255, .5)_x000D_
}_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-track {_x000D_
    border-width: 0 1px 0 6px_x000D_
}_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
}_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .035);_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14), inset -1px -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar-dark::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .07);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .25), inset -1px -1px 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-thumb {_x000D_
    border-width: 0 1px 0 6px_x000D_
}_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
}_x000D_
::-webkit-scrollbar-corner {_x000D_
    background: transparent_x000D_
}_x000D_
body::-webkit-scrollbar-track-piece {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 0 0 0 3px;_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
body::-webkit-scrollbar-track-piece:horizontal {_x000D_
    border-width: 3px 0 0;_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
body::-webkit-scrollbar-thumb {_x000D_
    border-width: 1px 1px 1px 5px_x000D_
}_x000D_
body::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 5px 1px 1px_x000D_
}_x000D_
body::-webkit-scrollbar-corner {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 3px 0 0 3px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar {_x000D_
    height: 16px;_x000D_
    overflow: visible;_x000D_
    width: 16px_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-button {_x000D_
    height: 0;_x000D_
    width: 0_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track {_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 7px 0 0_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .1)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .1)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .2)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .2)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .25), inset -1px 0 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), inset 0 -1px 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(0, 0, 0, .2);_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px;_x000D_
    min-height: 28px;_x000D_
    padding: 100px 0 0;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 7px 0 0;_x000D_
    padding: 0 0 0 100px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(0, 0, 0, .4);_x000D_
    box-shadow: inset 1px 1px 1px rgba(0, 0, 0, .25)_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    box-shadow: inset 1px 1px 3px rgba(0, 0, 0, 0.35)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(255, 255, 255, .3);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset 0 -1px 0 rgba(255, 255, 255, .1)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset -1px 0 0 rgba(255, 255, 255, .1)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(255, 255, 255, .6);_x000D_
    box-shadow: inset 1px 1px 1px rgba(255, 255, 255, .37)_x000D_
}_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(255, 255, 255, .75);_x000D_
    box-shadow: inset 1px 1px 3px rgba(255, 255, 255, .5)_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-track {_x000D_
    border-width: 0 1px 0 6px_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .035);_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14), inset -1px -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .07);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .25), inset -1px -1px 0 rgba(255, 255, 255, .15)_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    border-width: 0 1px 0 6px_x000D_
}_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
}_x000D_
.jfk-scrollbar::-webkit-scrollbar-corner {_x000D_
    background: transparent_x000D_
}_x000D_
body.jfk-scrollbar::-webkit-scrollbar-track-piece {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 0 0 0 3px;_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
body.jfk-scrollbar::-webkit-scrollbar-track-piece:horizontal {_x000D_
    border-width: 3px 0 0;_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
}_x000D_
body.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    border-width: 1px 1px 1px 5px_x000D_
}_x000D_
body.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 5px 1px 1px_x000D_
}_x000D_
body.jfk-scrollbar::-webkit-scrollbar-corner {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 3px 0 0 3px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14)_x000D_
}
_x000D_
<div class="testg">_x000D_
    <div class="content">_x000D_
        Look Ma'  my scrollbars doesn't have arrows <br /><br />_x000D_
        content, content, content <br /> content, content, content <br /> content, content, content s<br />  content, content, content <br/> content, content, content <br/> content, content, content d<br/>  content, content, content <br/> _x000D_
    </div>_x000D_
</div>_x000D_
<br/>_x000D_
<div class="testg jfk-scrollbar jfk-scrollbar-borderless jfk-scrollbar-dark">_x000D_
    <div class="content">_x000D_
        Look Ma'  my scrollbars dissapear in chrome<br /><br />_x000D_
        content, content, content <br /> content, content, content <br /> content, content, content s<br />  content, content, content <br/> content, content, content <br/> content, content, content d<br/>  content, content, content <br/> _x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/76kcuem0/32/

I just found it useful to remove the arrows from the scrollbars. As of 2015 it's been used in Google Maps when searching for places in the list of results in its material design UI.

NSOperation vs Grand Central Dispatch

GCD is very easy to use - if you want to do something in the background, all you need to do is write the code and dispatch it on a background queue. Doing the same thing with NSOperation is a lot of additional work.

The advantage of NSOperation is that (a) you have a real object that you can send messages to, and (b) that you can cancel an NSOperation. That's not trivial. You need to subclass NSOperation, you have to write your code correctly so that cancellation and correctly finishing a task both work correctly. So for simple things you use GCD, and for more complicated things you create a subclass of NSOperation. (There are subclasses NSInvocationOperation and NSBlockOperation, but everything they do is easier done with GCD, so there is no good reason to use them).

Starting Docker as Daemon on Ubuntu

I know this questions has been answered, however the reason this is happening to you, was probably because you did not add your username to the docker group.

Here are the steps to do it:

Add the docker group if it doesn't already exist:

sudo groupadd docker

Add the connected user ${USER} to the docker group. Change the user name to match your preferred user:

sudo gpasswd -a ${USER} docker

Restart the Docker daemon:

sudo service docker restart

If you are on Ubuntu 14.04-15.10* use docker.io instead:

sudo service docker.io restart

(If you are on Ubuntu 16.04 the service is named "docker" simply)

Either do a newgrp docker or log out/in to activate the changes to groups.

What's the difference between returning value or Promise.resolve from then()

The only difference is that you're creating an unnecessary promise when you do return Promise.resolve("bbb"). Returning a promise from an onFulfilled() handler kicks off promise resolution. That's how promise chaining works.

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:

Join:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
    { 
        yield return resultSelector(outerElement, innerElement); 
    } 
} 

GroupJoin:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 
} 

Read more here:

Best way to remove an event handler in jQuery?

if you set the onclick via html you need to removeAttr ($(this).removeAttr('onclick'))

if you set it via jquery (as the after the first click in my examples above) then you need to unbind($(this).unbind('click'))

live output from subprocess command

TLDR for Python 3:

import subprocess
import sys
with open('test.log', 'wb') as f: 
    process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
    for c in iter(lambda: process.stdout.read(1), b''): 
        sys.stdout.buffer.write(c)
        f.buffer.write(c)

You have two ways of doing this, either by creating an iterator from the read or readline functions and do:

import subprocess
import sys
with open('test.log', 'w') as f:  # replace 'w' with 'wb' for Python 3
    process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
    for c in iter(lambda: process.stdout.read(1), ''):  # replace '' with b'' for Python 3
        sys.stdout.write(c)
        f.write(c)

or

import subprocess
import sys
with open('test.log', 'w') as f:  # replace 'w' with 'wb' for Python 3
    process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
    for line in iter(process.stdout.readline, ''):  # replace '' with b'' for Python 3
        sys.stdout.write(line)
        f.write(line)

Or you can create a reader and a writer file. Pass the writer to the Popen and read from the reader

import io
import time
import subprocess
import sys

filename = 'test.log'
with io.open(filename, 'wb') as writer, io.open(filename, 'rb', 1) as reader:
    process = subprocess.Popen(command, stdout=writer)
    while process.poll() is None:
        sys.stdout.write(reader.read())
        time.sleep(0.5)
    # Read the remaining
    sys.stdout.write(reader.read())

This way you will have the data written in the test.log as well as on the standard output.

The only advantage of the file approach is that your code doesn't block. So you can do whatever you want in the meantime and read whenever you want from the reader in a non-blocking way. When you use PIPE, read and readline functions will block until either one character is written to the pipe or a line is written to the pipe respectively.

How can I initialize a MySQL database with schema in a Docker container?

After to struggle a little bit with that, take a look the Dockerfile using named volumes (db-data). It's important declare a plus at final part, where I mentioned that volume is [external]

All worked great this way!

version: "3"

services:

  database:
    image: mysql:5.7
    container_name: mysql
    ports:
      - "3306:3306"
    volumes:
      - db-data:/docker-entrypoint-initdb.d
    environment:
      - MYSQL_DATABASE=sample
      - MYSQL_ROOT_PASSWORD=root

volumes:
  db-data:
    external: true

How can I tell gcc not to inline a function?

Use the noinline attribute:

int func(int arg) __attribute__((noinline))
{
}

You should probably use it both when you declare the function for external use and when you write the function.

Replacing .NET WebBrowser control with a better browser, like Chrome?

I know this isn't a 'replacement' WebBrowser control, but I was having some awful rendering issues whilst showing a page that was using BootStrap 3+ for layout etc, and then I found a post that suggested I use the following. Apparently, it's specific to IE and tells it to use the latest variation found on the client machine for rendering (so it won't use IE7, which I believe is the default).

So just put:

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

somewhere in the head part of your document.

Obviously, if it's not your document, this won't help - though I personally consider it to be a security hole if you're reading pages not created by yourself through the WebBrowser control - why not just use a web browser!

Group by with multiple columns using lambda

Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.

return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
                .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
                .SelectMany(a => a)
                .ToList();

Where CustomerGroupingKey takes the group keys:

    private class CustomerGroupingKey
    {
        public CustomerGroupingKey(string country, string gender)
        {
            Country = country;
            Gender = gender;
        }

        public string Country { get; }

        public string Gender { get; }
    }

How can I find the location of origin/master in git, and how do I change it?

I was wondering the same thing about my repo. In my case I had an old remote that I wasn't pushing to anymore so I needed to remove it.

Get list of remotes:

git remote

Remove the one that you don't need

git remote rm {insert remote to remove}

Trim to remove white space

No need for jQuery

JavaScript does have a native .trim() method.

var name = "    John Smith  ";
name = name.trim();

console.log(name); // "John Smith"

Example Here

String.prototype.trim()

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

"unadd" a file to svn before commit

Try svn revert filename for every file you don't need and haven't yet committed. Or alternatively do svn revert -R folder for the problematic folder and then re-do the operation with correct ignoring configuration.

From the documentation:

 you can undo any scheduling operations:

$ svn add mistake.txt whoops
A         mistake.txt
A         whoops
A         whoops/oopsie.c

$ svn revert mistake.txt whoops
Reverted mistake.txt
Reverted whoops

How to remove all null elements from a ArrayList or String Array?

If you prefer immutable data objects, or if you just dont want to be destructive to the input list, you can use Guava's predicates.

ImmutableList.copyOf(Iterables.filter(tourists, Predicates.notNull()))

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

if A vs if A is not None:

It depends on the context.

I use if A: when I'm expecting A to be some sort of collection, and I only want to execute the block if the collection isn't empty. This allows the caller to pass any well-behaved collection, empty or not, and have it do what I expect. It also allows None and False to suppress execution of the block, which is occasionally convenient to calling code.

OTOH, if I expect A to be some completely arbitrary object but it could have been defaulted to None, then I always use if A is not None, as calling code could have deliberately passed a reference to an empty collection, empty string, or a 0-valued numeric type, or boolean False, or some class instance that happens to be false in boolean context.

And on the other other hand, if I expect A to be some more-specific thing (e.g. instance of a class I'm going to call methods of), but it could have been defaulted to None, and I consider default boolean conversion to be a property of the class I don't mind enforcing on all subclasses, then I'll just use if A: to save my fingers the terrible burden of typing an extra 12 characters.

UIButton: set image for selected-highlighted state

Correct me if I am wrong. By doing

   [button setSelected:YES];

you are clearly changing the state of the buttons as selected. So naturally by the code you have provided the image will that for the selected state in your case checked.png

How to POST the data from a modal form of Bootstrap?

I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.

<form name="paymentitrform" id="paymentitrform" class="payment"
                    method="post"
                    action="abc.php">
          <input name="email" value="" placeholder="email" />
          <input type="hidden" name="planamount" id="planamount" value="0">
                                <input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
                                    name="planform">

                </form>

You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button

    function form_submit() {
        document.getElementById("paymentitrform").submit();
   }  

Getting URL parameter in java and extract a specific text from that URL

Import these libraries

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

Similar to the verisimilitude, but with the capabilities of handling multivalue parameters. Note: I've seen HTTP GET requests without a value, in this case the value will be null.

public static List<NameValuePair> getQueryMap(String query)  
{  
    List<NameValuePair> queryMap = new ArrayList<NameValuePair>();
    String[] params = query.split(Pattern.quote("&"));  
    for (String param : params)
    {
        String[] chunks = param.split(Pattern.quote("="));
        String name = chunks[0], value = null;  
        if(chunks.length > 1) {
            value = chunks[1];
        }
        queryMap.add(new BasicNameValuePair(name, value));
    }
    return queryMap;
}

Example:

GET /bottom.gif?e235c08=1509896923&%49%6E%...

Specifying an Index (Non-Unique Key) Using JPA

With JPA 2.1 you should be able to do it.

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;

@Entity
@Table(name = "region",
       indexes = {@Index(name = "my_index_name",  columnList="iso_code", unique = true),
                  @Index(name = "my_index_name2", columnList="name",     unique = false)})
public class Region{

    @Column(name = "iso_code", nullable = false)
    private String isoCode;

    @Column(name = "name", nullable = false)
    private String name;

} 

Update: If you ever need to create and index with two or more columns you may use commas. For example:

@Entity
@Table(name    = "company__activity", 
       indexes = {@Index(name = "i_company_activity", columnList = "activity_id,company_id")})
public class CompanyActivity{

How to while loop until the end of a file in Python without checking for empty line?

I discovered while following the above suggestions that for line in f: does not work for a pandas dataframe (not that anyone said it would) because the end of file in a dataframe is the last column, not the last row. for example if you have a data frame with 3 fields (columns) and 9 records (rows), the for loop will stop after the 3rd iteration, not after the 9th iteration. Teresa

get jquery `$(this)` id

this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.

$("select").change(function() {    
    alert("Changed: " + this.id);
}

Live example

You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:

$("#container").change(function(event) {
    alert("Field " + event.target.id + " changed");
});

Live example

(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Just add this at start: image = cv2.imread(image)

Detect Android phone via Javascript / jQuery

;(function() {
    var redirect = false
    if (navigator.userAgent.match(/iPhone/i)) {
        redirect = true
    }
    if (navigator.userAgent.match(/iPod/i)) {
        redirect = true
    }
    var isAndroid = /(android)/i.test(navigator.userAgent)
    var isMobile = /(mobile)/i.test(navigator.userAgent)
    if (isAndroid && isMobile) {
        redirect = true
    }
    if (redirect) {
        window.location.replace('jQueryMobileSite')
    }
})()

Java LinkedHashMap get first or last entry

Though linkedHashMap doesn't provide any method to get first, last or any specific object.

But its pretty trivial to get :

Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();  
Set<Integer> al =   orderMap.keySet();

now using iterator on al object ; you can get any object.

Adding onClick event dynamically using jQuery

Or you can use an arrow function to define it:

$(document).ready(() => {
  $('#bfCaptchaEntry').click(()=>{
    
  });
});

For better browser support:

$(document).ready(function() {
  $('#bfCaptchaEntry').click(function (){
    
  });
});

Automatic prune with Git fetch or pull

If you want to always prune when you fetch, I can suggest to use Aliases.

Just type git config -e to open your editor and change the configuration for a specific project and add a section like

[alias]
pfetch = fetch --prune   

the when you fetch with git pfetch the prune will be done automatically.

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Use component scanning as given below, if com.project.action.PasswordHintAction is annotated with stereotype annotations

<context:component-scan base-package="com.project.action"/>

EDIT

I see your problem, in PasswordHintActionTest you are autowiring PasswordHintAction. But you did not create bean configuration for PasswordHintAction to autowire. Add one of stereotype annotation(@Component, @Service, @Controller) to PasswordHintAction like

@Component
public class PasswordHintAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;

or create xml configuration in applicationcontext.xml like

<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />

How to clone all remote branches in Git?

Why you only see "master"

git clone downloads all remote branches but still considers them "remote", even though the files are located in your new repository. There's one exception to this, which is that the cloning process creates a local branch called "master" from the remote branch called "master". By default, git branch only shows local branches, which is why you only see "master".

git branch -a shows all branches, including remote branches.


How to get local branches

If you actually want to work on a branch, you'll probably want a "local" version of it. To simply create local branches from remote branches (without checking them out and thereby changing the contents of your working directory), you can do that like this:

git branch branchone origin/branchone
git branch branchtwo origin/branchtwo
git branch branchthree origin/branchthree

In this example, branchone is the name of a local branch you're creating based on origin/branchone; if you instead want to create local branches with different names, you can do this:

git branch localbranchname origin/branchone

Once you've created a local branch, you can see it with git branch (remember, you don't need -a to see local branches).

How to convert list to string

By using ''.join

list1 = ['1', '2', '3']
str1 = ''.join(list1)

Or if the list is of integers, convert the elements before joining them.

list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)

How do I mock an autowired @Value field in Spring with Mockito?

Whenever possible, I set the field visibility as package-protected so it can be accessed from the test class. I document that using Guava's @VisibleForTesting annotation (in case the next guy wonders why it's not private). This way I don't have to rely on the string name of the field and everything stays type-safe.

I know it goes against standard encapsulation practices we were taught in school. But as soon as there is some agreement in the team to go this way, I found it the most pragmatic solution.

Django values_list vs values

The values() method returns a QuerySet containing dictionaries:

<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>

The values_list() method returns a QuerySet containing tuples:

<QuerySet [(1,), (2,)]>

If you are using values_list() with a single field, you can use flat=True to return a QuerySet of single values instead of 1-tuples:

<QuerySet [1, 2]>

SQL query to get most recent row for each instance of a given key

Try this:

Select u.[username]
      ,u.[ip]
      ,q.[time_stamp]
From [users] As u
Inner Join (
    Select [username]
          ,max(time_stamp) as [time_stamp]
    From [users]
    Group By [username]) As [q]
On u.username = q.username
And u.time_stamp = q.time_stamp

How do I remove blank pages coming between two chapters in Appendix?

it is very easy:

add \documentclass[oneside]{book} and youre fine ;)

How to install popper.js with Bootstrap 4?

npm install bootstrap jquery --save

You don't have to install popper.js with npm as it comes with npm Bootstrap in bootstrap.bundle.js.

Bundled JS files (bootstrap.bundle.js and minified bootstrap.bundle.min.js) include Popper, but not jQuery.

Source to Verify: Link

Now you only have to do this in your HTML file:

<script src="node_modules/jquery/dist/jquery.slim.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Hibernate-sequence doesn't exist

Run this query

create sequence hibernate_sequence start with 1 increment by 1

Android Studio Stuck at Gradle Download on create new project

The gradle included with Android Studio is located in /Applications/Android Studio.app/plugins/gradle/lib

To go into the Android Studio.app directory I did cd "Android Studio.app"

or you could just do cd /Applications/Android\ Studio.app/plugins/gradle/lib

Adding a Button to a WPF DataGrid

XAML :

<DataGrid x:Name="dgv_Students" AutoGenerateColumns="False"  ItemsSource="{Binding People}" Margin="10,20,10,0" Style="{StaticResource AzureDataGrid}" FontFamily="B Yekan" Background="#FFB9D1BA" >
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Click="Button_Click_dgvs">Text</Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    </DataGrid.Columns>

Code Behind :

       private IEnumerable<DataGridRow> GetDataGridRowsForButtons(DataGrid grid)
{ //IQueryable 
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (null != row & row.IsSelected) yield return row;
    }
}

void Button_Click_dgvs(object sender, RoutedEventArgs e)
{

    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
        if (vis is DataGridRow)
        {
           // var row = (DataGrid)vis;

            var rows = GetDataGridRowsForButtons(dgv_Students);
            string id;
            foreach (DataGridRow dr in rows)
            {
                id = (dr.Item as tbl_student).Identification_code;
                MessageBox.Show(id);
                 break;
            }
            break;
        }
}

After clicking on the Button, the ID of that row is returned to you and you can use it for your Button name.

Google Chrome "window.open" workaround?

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

Change the value in app.config file dynamically

 XmlReaderSettings _configsettings = new XmlReaderSettings();
 _configsettings.IgnoreComments = true;

 XmlReader _configreader = XmlReader.Create(ConfigFilePath, _configsettings);
 XmlDocument doc_config = new XmlDocument();
 doc_config.Load(_configreader);
 _configreader.Close();

 foreach (XmlNode RootName in doc_config.DocumentElement.ChildNodes)
 {
     if (RootName.LocalName == "appSettings")
     {
         if (RootName.HasChildNodes)
         {
             foreach (XmlNode _child in RootName.ChildNodes)
             {
                 if (_child.Attributes["key"].Value == "HostName")
                 {
                     if (_child.Attributes["value"].Value == "false")
                         _child.Attributes["value"].Value = "true";
                 }
             }
         }
     }
 }
 doc_config.Save(ConfigFilePath);

C char* to int conversion

atoi can do that for you

Example:

char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

How to remove specific substrings from a set of strings in Python?

If list

I was doing something for a list which is a set of strings and you want to remove all lines that have a certain substring you can do this

import re
def RemoveInList(sub,LinSplitUnOr):
    indices = [i for i, x in enumerate(LinSplitUnOr) if re.search(sub, x)]
    A = [i for j, i in enumerate(LinSplitUnOr) if j not in indices]
    return A

where sub is a patter that you do not wish to have in a list of lines LinSplitUnOr

for example

A=['Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad']
sub = 'good'
A=RemoveInList(sub,A)

Then A will be

enter image description here

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

You will want to use a CONVERT() statement.

Try the following;

SELECT CONVERT(VARCHAR(10), SA.[RequestStartDate], 103) as 'Service Start Date', CONVERT(VARCHAR(10), SA.[RequestEndDate], 103) as 'Service End Date', FROM (......) SA WHERE.....

See MSDN Cast and Convert for more information.

How can I run an EXE program from a Windows Service using C#?

i have tried this article Code Project, it is working fine for me. I have used the code too. article is excellent in explanation with screenshot.

I am adding necessary explanation to this scenario

You have just booted up your computer and are about to log on. When you log on, the system assigns you a unique Session ID. In Windows Vista, the first User to log on to the computer is assigned a Session ID of 1 by the OS. The next User to log on will be assigned a Session ID of 2. And so on and so forth. You can view the Session ID assigned to each logged on User from the Users tab in Task Manager. enter image description here

But your windows service is brought under session ID of 0. This session is isolated from other sessions. This ultimately prevent the windows service to invoke the application running under user session's like 1 or 2.

In order to invoke the application from windows service you need to copy the control from winlogon.exe which acts as present logged user as shown in below screenshot. enter image description here

Important codes

// obtain the process id of the winlogon process that 
// is running within the currently active session
Process[] processes = Process.GetProcessesByName("winlogon");
foreach (Process p in processes)
{
    if ((uint)p.SessionId == dwSessionId)
    {
        winlogonPid = (uint)p.Id;
    }
}

// obtain a handle to the winlogon process
hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);

// obtain a handle to the access token of the winlogon process
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
{
    CloseHandle(hProcess);
    return false;
}

// Security attibute structure used in DuplicateTokenEx and   CreateProcessAsUser
// I would prefer to not have to use a security attribute variable and to just 
// simply pass null and inherit (by default) the security attributes
// of the existing token. However, in C# structures are value types and   therefore
// cannot be assigned the null value.
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);

// copy the access token of the winlogon process; 
// the newly created token will be a primary token
if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, 
    (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, 
    (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
    {
      CloseHandle(hProcess);
      CloseHandle(hPToken);
      return false;
    }

 STARTUPINFO si = new STARTUPINFO();
 si.cb = (int)Marshal.SizeOf(si);

// interactive window station parameter; basically this indicates 
// that the process created can display a GUI on the desktop
si.lpDesktop = @"winsta0\default";

// flags that specify the priority and creation method of the process
int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;

// create a new process in the current User's logon session
 bool result = CreateProcessAsUser(hUserTokenDup,  // client's access token
                            null,             // file to execute
                            applicationName,  // command line
                            ref sa,           // pointer to process    SECURITY_ATTRIBUTES
                            ref sa,           // pointer to thread SECURITY_ATTRIBUTES
                            false,            // handles are not inheritable
                            dwCreationFlags,  // creation flags
                            IntPtr.Zero,      // pointer to new environment block 
                            null,             // name of current directory 
                            ref si,           // pointer to STARTUPINFO structure
                            out procInfo      // receives information about new process
                            );

How to import a new font into a project - Angular 5

the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face

@font-face {
  font-family: 'Name You Font';
  src: url('assets/font/xxyourfontxxx.eot');
  src: local('Cera Pro Medium'), local('CeraPro-Medium'),
  url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
  url('assets/font/xxyourfontxxx.woff') format('woff'),
  url('assets/font/xxyourfontxxx.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}

So you can just indicate your fontfamily name that you already choosed

NOTE: the font-weight and font-style depend on your .woff .ttf ... files

How to generate sample XML documents from their DTD or XSD?

The OpenXSD library mentions that they have support for generating XML instances based on the XSD. Check that out.

What's the difference between the atomic and nonatomic attributes?

There is no such keyword "atomic"

@property(atomic, retain) UITextField *userName;

We can use the above like

@property(retain) UITextField *userName;

See Stack Overflow question I am getting issues if I use @property(atomic,retain)NSString *myString.

Git - deleted some files locally, how do I get them from a remote repository

If you have deleted multiple files locally but not committed, you can force checkout

$ git checkout -f HEAD

random.seed(): What does it do?

In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.

How do I keep CSS floats in one line?

Solution 1:

display:table-cell (not widely supported)

Solution 2:

tables

(I hate hacks.)

jQuery: Can I call delay() between addClass() and such?

delay does not work on none queue functions, so we should use setTimeout().

And you don't need to separate things. All you need to do is including everything in a setTimeOut method:

setTimeout(function () {
    $("#div").addClass("error").delay(1000).removeClass("error");
}, 1000);

Call a stored procedure with another in Oracle

@Michael Lockwood - you don't need to use the keyword "CALL" anywhere. You just need to mention the procedure call directly.

That is

Begin
   proc1(input1, input2);
end;
/

instead of

Begin
   call proc1(input1, input2);
end;
/

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

Make a float only show two decimal places

Here's some methods to format dynamically according to a precision:

+ (NSNumber *)numberFromString:(NSString *)string
{
    if (string.length) {
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        f.numberStyle = NSNumberFormatterDecimalStyle;
        return [f numberFromString:string];
    } else {
        return nil;
    }
}

+ (NSString *)stringByFormattingString:(NSString *)string toPrecision:(NSInteger)precision
{
    NSNumber *numberValue = [self numberFromString:string];

    if (numberValue) {
        NSString *formatString = [NSString stringWithFormat:@"%%.%ldf", (long)precision];
        return [NSString stringWithFormat:formatString, numberValue.floatValue];
    } else {
        /* return original string */
        return string;
    }
}

e.g.

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:4];

=> 2.3453

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:0];

=> 2

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:2];

=> 2.35 (round up)

Set View Width Programmatically

check it in mdpi device.. If the ad displays correctly, the error should be in "px" to "dip" conversion..

How to pass anonymous types as parameters?

Normally, you do this with generics, for example:

MapEntToObj<T>(IQueryable<T> query) {...}

The compiler should then infer the T when you call MapEntToObj(query). Not quite sure what you want to do inside the method, so I can't tell whether this is useful... the problem is that inside MapEntToObj you still can't name the T - you can either:

  • call other generic methods with T
  • use reflection on T to do things

but other than that, it is quite hard to manipulate anonymous types - not least because they are immutable ;-p

Another trick (when extracting data) is to also pass a selector - i.e. something like:

Foo<TSource, TValue>(IEnumerable<TSource> source,
        Func<TSource,string> name) {
    foreach(TSource item in source) Console.WriteLine(name(item));
}
...
Foo(query, x=>x.Title);

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Laravel supports aliases on tables and columns with AS. Try

$users = DB::table('really_long_table_name AS t')
           ->select('t.id AS uid')
           ->get();

Let's see it in action with an awesome tinker tool

$ php artisan tinker
[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});
// NULL
[2] > DB::table('really_long_table_name')->insert(['id' => null]);
// true
[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
// array(
//   0 => object(stdClass)(
//     'uid' => '1'
//   )
// )

Convert Enum to String

I don't know what the "preferred" method is (ask 100 people and get 100 different opinions) but do what's simplest and what works. GetName works but requires a lot more keystrokes. ToString() seems to do the job very well.

How to embed fonts in CSS?

When I went to Google fonts all they gave me were true type font files .ttf and didn't explain at all how to use the @font-face to include them into my document. I tried the web font generator from font squirrel too, which just kept running the loading gif and not working... I then found this site -

https://transfonter.org/

I had great success using the following method:

I selected the Add Fonts button, leaving the default options, added all of my .ttf that Google gave me for Open Sans (which was like 10, I chose a lot of options...).

Then I selected the Convert button.

Heres the best part!

They gave me a zip file with all the font format files I selected, .ttf, .woff and .eot. Inside that zip file they had a demo.html file that I just double clicked on and it opened up a web page in my browser showing me example usages of all the different css font options, how to implement them, and what they looked like etc.

@font-face

I still didn't know at this point how to include the fonts into my stylesheet properly using @font-face but then I noticed that this demo.html came with it's own stylesheet in the zip as well. I opened the stylesheet and it showed how to bring in all of the fonts using @font-face so I was able to quickly, and easily, copy paste this into my project -

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-BoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-BoldItalic.ttf') format('truetype');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-LightItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-LightItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-LightItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-LightItalic.ttf') format('truetype');
    font-weight: 300;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-SemiBold.eot');
    src: url('fonts/Open_Sans/OpenSans-SemiBold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-SemiBold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-SemiBold.ttf') format('truetype');
    font-weight: 600;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Regular.eot');
    src: url('fonts/Open_Sans/OpenSans-Regular.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Regular.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Light.eot');
    src: url('fonts/Open_Sans/OpenSans-Light.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Light.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Light.ttf') format('truetype');
    font-weight: 300;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Italic.eot');
    src: url('fonts/Open_Sans/OpenSans-Italic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Italic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-SemiBoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-SemiBoldItalic.ttf') format('truetype');
    font-weight: 600;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot');
    src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-ExtraBold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-ExtraBold.ttf') format('truetype');
    font-weight: 800;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.ttf') format('truetype');
    font-weight: 800;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Bold.eot');
    src: url('fonts/Open_Sans/OpenSans-Bold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Bold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}

The demo.html also had it's own inline stylesheet that was interesting to take a look at, though I am familiar with working with font weights and styles once they are included so I didn't need it much. For an example of how to implement a font style onto an html element for reference purposes you could use the following method in a similar case to mine after @font-face has been used properly -

html, body{
    margin: 0;
    font-family: 'Open Sans';
}
.banner h1{
    font-size: 43px;
    font-weight: 700;
}
.banner p{
    font-size: 24px;
    font-weight: 300;
    font-style: italic;
}

'Use of Unresolved Identifier' in Swift

If this is regarding a class you created, be sure that the class is not nested.

F.e

A.swift

class A {

   class ARelated {

   }
}

calling var b = ARelated() will give 'Use of unresolved identifier: ARelated'.

You can either:

1) separate the classes if wanted on the same file:

A.swift

class A {

}

class ARelated {

}

2) Maintain your same structure and use the enclosing class to get to the subclass:

var b = A.ARelated

How to Split Image Into Multiple Pieces in Python

I find it easier to skimage.util.view_as_windows or `skimage.util.view_as_blocks which also allows you to configure the step

http://scikit-image.org/docs/dev/api/skimage.util.html?highlight=view_as_windows#skimage.util.view_as_windows

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
    return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
           + foo;
}

Download TS files from video stream

1) Please read instructions by @aalhanane (after "paste URL m3u8" step you have to type name for the file, eg "video" then click on "hand" icon next to "quality" and only after that you should select "one on one" and "download").

2) The stream splits video and audio, so you need to download them separately and then use the same m3u8x to join them https://youtu.be/he-tDNiVl2M (optionally convert to mp4).

3) m3u8x can download video without any issues but in my case it cannot extract audio links. So I simply downloaded the *.m3u8 file and searched for line which contains GROUP-ID="audio-0" and then scroll right and copied the link (!including token!) and paste it straight into "Quality URL" field of m3u8x app. Then "one on one" and download it similar to video stream.

Once I had both video and audio, I joined and success =)

p.s. in case automatic extraction will stop working in the future, you can use the same method to extract video links manually.

Generate insert script for selected records?

If possible use Visual Studio. The Microsoft SQL Server Data Tools (SSDT) bring a built in functionality for this since the March 2014 release:

  1. Open Visual Studio
  2. Open "View" ? "SQL Server Object Explorer"
  3. Add a connection to your Server
  4. Expand the relevant database
  5. Expand the "Tables" folder
  6. Right click on relevant table
  7. Select "View Data" from context menu
  8. In the new window, viewing the data use the "Sort and filter dataset" functionality in the tool bar to apply your filter. Note that this functionality is limited and you can't write explicit SQL queries.
  9. After you have applied your filter and see only the data you want, click on "Script" or "Script to file" in the tool bar
  10. Voilà - Here you have your insert script for your filtered data

Note: Be careful, the "View Data" window is just like SSMS "Edit Top 200 Rows"- you can edit data right away

(Tested with Visual Studio 2015 with Microsoft SQL Server Data Tools (SSDT) Version 14.0.60812.0 and Microsoft SQL Server 2012)

Execute and get the output of a shell command in node.js

This is the method I'm using in a project I am currently working on.

var exec = require('child_process').exec;
function execute(command, callback){
    exec(command, function(error, stdout, stderr){ callback(stdout); });
};

Example of retrieving a git user:

module.exports.getGitUser = function(callback){
    execute("git config --global user.name", function(name){
        execute("git config --global user.email", function(email){
            callback({ name: name.replace("\n", ""), email: email.replace("\n", "") });
        });
    });
};

Ruby Hash to array of values

hash  = { :a => ["a", "b", "c"], :b => ["b", "c"] }
hash.values #=> [["a","b","c"],["b","c"]]

Printing leading 0's in C

If you need to store the ZIP Code in a character array, zipcode[], you can use this:

snprintf(zipcode, 6, "%05.5d", atoi(zipcode));

In Maven how to exclude resources from the generated jar?

Put those properties files in src/test/resources. Files in src/test/resources are available within Eclipse automatically via eclipse:eclipse but will not be included in the packaged JAR by Maven.

How to specify a multi-line shell variable?

Use read with a heredoc as shown below:

read -d '' sql << EOF
select c1, c2 from foo
where c1='something'
EOF

echo "$sql"

How can I disable a button in a jQuery dialog from a function?

I had one button I didn't want displayed till a trigger point.

At first I tried this which works: -

$(":button:contains('OK')").hide();

but leaves a line (because they have all gone!), so added this instead in my CSS: -

.ui-dialog .ui-dialog-buttonpane {
display: none;
}

This hides ALL the buttons.

I can re-enable when needed by : -

$('.ui-dialog .ui-dialog-buttonpane').css({"display":"block"}); //show button

Key Shortcut for Eclipse Imports

CTRL + 1 can also be used which will suggest to import.

What's the best way to generate a UML diagram from Python source code?

It is worth mentioning Gaphor. A Python modelling/UML tool.

What is the equivalent of Java's final in C#?

Java class final and method final -> sealed. Java member variable final -> readonly for runtime constant, const for compile time constant.

No equivalent for Local Variable final and method argument final

How to concatenate multiple column values into a single column in Panda dataframe

If you have a list of columns you want to concatenate and maybe you'd like to use some separator, here's what you can do

def concat_columns(df, cols_to_concat, new_col_name, sep=" "):
    df[new_col_name] = df[cols_to_concat[0]]
    for col in cols_to_concat[1:]:
        df[new_col_name] = df[new_col_name].astype(str) + sep + df[col].astype(str)

This should be faster than apply and takes an arbitrary number of columns to concatenate.

Terminating a script in PowerShell

I used this for a reruning of a program. I don't know if it would help, but it is a simple if statement requiring only two different entry's. It worked in powershell for me.

$rerun = Read-Host "Rerun report (y/n)?"

if($rerun -eq "y") { Show-MemoryReport }
if($rerun -eq "n") { Exit }

Don't know if this helps, but i believe this would be along the lines of terminating a program after you have run it. However in this case, every defined input requires a listed and categorized output. You could also have the exit call up a new prompt line and terminate the program that way.

How to deserialize a JObject to .NET object

According to this post, it's much better now:

// pick out one album
JObject jalbum = albums[0] as JObject;

// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();

Documentation: Convert JSON to a Type

Where is SQLite database stored on disk?

In Windows 10 if in the prompt command the path where you start sqlite is

C:\users\USER_NAME

You can find it in the user home folder. The .db file is stored where you start the sqlite command. I hope this solve the issue

Regex to split a CSV

Yet another answer with a few extra features like support for quoted values that contain escaped quotes and CR/LF characters (single values that span multiple lines).

NOTE: Though the solution below can likely be adapted for other regex engines, using it as-is will require that your regex engine treats multiple named capture groups using the same name as one single capture group. (.NET does this by default)


When multiple lines/records of a CSV file/stream (matching RFC standard 4180) are passed to the regular expression below it will return a match for each non-empty line/record. Each match will contain a capture group named Value that contains the captured values in that line/record (and potentially an OpenValue capture group if there was an open quote at the end of the line/record).

Here's the commented pattern (test it on Regexstorm.net):

(?<=\r|\n|^)(?!\r|\n|$)                       // Records start at the beginning of line (line must not be empty)
(?:                                           // Group for each value and a following comma or end of line (EOL) - required for quantifier (+?)
  (?:                                         // Group for matching one of the value formats before a comma or EOL
    "(?<Value>(?:[^"]|"")*)"|                 // Quoted value -or-
    (?<Value>(?!")[^,\r\n]+)|                 // Unquoted value -or-
    "(?<OpenValue>(?:[^"]|"")*)(?=\r|\n|$)|   // Open ended quoted value -or-
    (?<Value>)                                // Empty value before comma (before EOL is excluded by "+?" quantifier later)
  )
  (?:,|(?=\r|\n|$))                           // The value format matched must be followed by a comma or EOL
)+?                                           // Quantifier to match one or more values (non-greedy/as few as possible to prevent infinite empty values)
(?:(?<=,)(?<Value>))?                         // If the group of values above ended in a comma then add an empty value to the group of matched values
(?:\r\n|\r|\n|$)                              // Records end at EOL


Here's the raw pattern without all the comments or whitespace.

(?<=\r|\n|^)(?!\r|\n|$)(?:(?:"(?<Value>(?:[^"]|"")*)"|(?<Value>(?!")[^,\r\n]+)|"(?<OpenValue>(?:[^"]|"")*)(?=\r|\n|$)|(?<Value>))(?:,|(?=\r|\n|$)))+?(?:(?<=,)(?<Value>))?(?:\r\n|\r|\n|$)


Here is a visualization from Debuggex.com (capture groups named for clarity): Debuggex.com visualization

Examples on how to use the regex pattern can be found on my answer to a similar question here, or on C# pad here, or here.

Run cron job only if it isn't already running

Use flock. It's new. It's better.

Now you don't have to write the code yourself. Check out more reasons here: https://serverfault.com/a/82863

/usr/bin/flock -n /tmp/my.lockfile /usr/local/bin/my_script

How to start an application without waiting in a batch file?

If your exe takes arguments,

start MyApp.exe -arg1 -arg2

Looping through a Scripting.Dictionary using index/item number

Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.

For i = 0 To d.Count - 1
    s = d.Items()(i)
    Debug.Print s
Next i()

KEYS works the same way

For i = 0 To d.Count - 1
    Debug.Print d.Keys()(i), d.Items()(i)
Next i

This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".

Debug.Print Split("A,B,C,D", ",")(2)

SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.

Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.

In excel how do I reference the current row but a specific column?

To static either a row or a column, put a $ sign in front of it. So if you were to use the formula =AVERAGE($A1,$C1) and drag it down the entire sheet, A and C would remain static while the 1 would change to the current row

If you're on Windows, you can achieve the same thing by repeatedly pressing F4 while in the formula editing bar. The first F4 press will static both (it will turn A1 into $A$1), then just the row (A$1) then just the column ($A1)

Although technically with the formulas that you have, dragging down for the entirety of the column shouldn't be a problem without putting a $ sign in front of the column. Setting the column as static would only come into play if you're dragging ACROSS columns and want to keep using the same column, and setting the row as static would be for dragging down rows but wanting to use the same row.

XPath to return only elements containing the text, and not its parents

Do you want to find elements that contain "match", or that equal "match"?

This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2):

//*[text()='match']

This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2):

//*[normalize-space(text())='match']

This will find all elements that contain 'match' in the text node value (matches random2 and random3):

//*[contains(text(),'match')]

This XPATH 2.0 solution uses the matches() function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^) or a word boundary (i.e. \W) and terminated by the end of the string (i.e. $) or a word boundary. The third parameter i evaluates the regex pattern case-insensitive. (matches random2)

//*[matches(text(),'(^|\W)match($|\W)','i')]

Is there a good Valgrind substitute for Windows?

Development environment for Windows you are using may contain its own tools. Visual Studio, for example, lets you detect and isolate memory leaks in your programs

Proper way to exit command line program?

Using control-z suspends the process (see the output from stty -a which lists the key stroke under susp). That leaves it running, but in suspended animation (so it is not using any CPU resources). It can be resumed later.

If you want to stop a program permanently, then any of interrupt (often control-c) or quit (often control-\) will stop the process, the latter producing a core dump (unless you've disabled them). You might also use a HUP or TERM signal (or, if really necessary, the KILL signal, but try the other signals first) sent to the process from another terminal; or you could use control-z to suspend the process and then send the death threat from the current terminal, and then bring the (about to die) process back into the foreground (fg).

Note that all key combinations are subject to change via the stty command or equivalents; the defaults may vary from system to system.

Should I add the Visual Studio .suo and .user files to source control?

We don't commit the binary file (*.suo), but we commit the .user file. The .user file contains for example the start options for debugging the project. You can find the start options in the properties of the project in the tab "Debug". We used NUnit in some projects and configured the nunit-gui.exe as the start option for the project. Without the .user file, each team member would have to configure it separately.

Hope this helps.

Changing navigation title programmatically

I prefer using self.navigationItem.title = "Your Title Here" over self.title = "Your Title Here" to provide title in the navigation bar since tab bar also uses self.title to alter its title. You should try the following code once.

Note: calling the super view lifecycle is necessary before you do any stuffs.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavBar()
    }
}

private func setupNavBar() {
    self.navigationItem.title = "Your Title Here"
}

Set default value of javascript object attributes

I think the simplest approach is using Object.assign.

If you have this Class:

class MyHelper {
    constructor(options) {
        this.options = Object.assign({
            name: "John",
            surname: "Doe",
            birthDate: "1980-08-08"
        }, options);
    }
}

You can use it like this:

let helper = new MyHelper({ name: "Mark" });
console.log(helper.options.surname); // this will output "Doe"

Documentation (with polyfill): https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

How can I transform string to UTF-8 in C#?

Your code is reading a sequence of UTF8-encoded bytes, and decoding them using an 8-bit encoding.

You need to fix that code to decode the bytes as UTF8.

Alternatively (not ideal), you could convert the bad string back to the original byte array—by encoding it using the incorrect encoding—then re-decode the bytes as UTF8.

SyntaxError: missing ; before statement

Or you might have something like this (redeclaring a variable):

var data = [];
var data = 

What are the differences between json and simplejson Python modules?

Another reason projects use simplejson is that the builtin json did not originally include its C speedups, so the performance difference was noticeable.

How to hide a div after some time period?

setTimeout('$("#someDivId").hide()',1500);

Convert datetime value into string

This is super old, but I figured I'd add my 2c. DATE_FORMAT does indeed return a string, but I was looking for the CAST function, in the situation that I already had a datetime string in the database and needed to pattern match against it:

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

In this case, you'd use:

CAST(date_value AS char)

This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.

$date + 1 year?

I prefer the OO approach:

$date = new \DateTimeImmutable('today'); //'today' gives midnight, leave blank for current time.
$futureDate = $date->add(\DateInterval::createFromDateString('+1 Year'))

Use DateTimeImmutable otherwise you will modify the original date too! more on DateTimeImmutable: http://php.net/manual/en/class.datetimeimmutable.php


If you just want from todays date then you can always do:

new \DateTimeImmutable('-1 Month');

How to force Eclipse to ask for default workspace?

I first tried the -clean option, but that didn't solve the problem.

Then I added the -data option with the correct path to the workspace.

That solved the problem for me.

Slide div left/right using jQuery

The easiest way to do so is using jQuery and animate.css animation library.

Javascript

/* --- Show DIV --- */
$( '.example' ).removeClass( 'fadeOutRight' ).show().addClass( 'fadeInRight' );

/* --- Hide DIV --- */
$( '.example' ).removeClass( 'fadeInRight' ).addClass( 'fadeOutRight' );


HTML

<div class="example">Some text over here.</div>


Easy enough to implement. Just don't forget to include the animate.css file in the header :)

IllegalMonitorStateException on wait() call

I know this thread is almost 2 years old but still need to close this since I also came to this Q/A session with same issue...

Please read this definition of illegalMonitorException again and again...

IllegalMonitorException is thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.

This line again and again says, IllegalMonitorException comes when one of the 2 situation occurs....

1> wait on an object's monitor without owning the specified monitor.

2> notify other threads waiting on an object's monitor without owning the specified monitor.

Some might have got their answers... who all doesn't, then please check 2 statements....

synchronized (object)

object.wait()

If both object are same... then no illegalMonitorException can come.

Now again read the IllegalMonitorException definition and you wont forget it again...

jQuery: How to get the HTTP status code from within the $.ajax.error method?

You should create a map of actions using the statusCode setting:

$.ajax({
  statusCode: {
    400: function() {
      alert('400 status code! user error');
    },
    500: function() {
      alert('500 status code! server error');
    }
  }
});

Reference (Scroll to: 'statusCode')

EDIT (In response to comments)

If you need to take action based on the data returned in the response body (which seems odd to me), you will need to use error: instead of statusCode:

error:function (xhr, ajaxOptions, thrownError){
    switch (xhr.status) {
        case 404:
             // Take action, referencing xhr.responseText as needed.
    }
} 

WCF error - There was no endpoint listening at

in my case

my service has function to Upload Files

and this error just shown up on trying to upload Big Files

so I found this answer to Increase maxRequestLength to needed value in web.config

and problem solved

if you don't make any upload or download operations maybe this answer will not help you

How can I format DateTime to web UTC format?

Try this:

DateTime date = DateTime.ParseExact(
    "Tue, 1 Jan 2008 00:00:00 UTC", 
    "ddd, d MMM yyyy HH:mm:ss UTC", 
    CultureInfo.InvariantCulture);

Previously asked question

iptables block access to port 8000 except from IP address

Another alternative is;

sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP

I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

Edit**

According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP

configuring project ':app' failed to find Build Tools revision

For me, dataBinding { enabled true } was enabled in gradle, removing this helped me

What does LayoutInflater in Android do?

This class is used to instantiate layout XML file into its corresponding View objects. It is never be used directly -- use getLayoutInflater() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on. For example:

LayoutInflater inflater = (LayoutInflater)context.getSystemService
      (Context.LAYOUT_INFLATER_SERVICE);

Reference: http://developer.android.com/reference/android/view/LayoutInflater.html

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

Easy way to export multiple data.frame to multiple Excel worksheets

for a lapply-friendly version..

library(data.table)
library(xlsx)

path2txtlist <- your.list.of.txt.files
wb <- createWorkbook()
lapply(seq_along(path2txtlist), function (j) {
sheet <- createSheet(wb, paste("sheetname", j))
addDataFrame(fread(path2txtlist[j]), sheet=sheet, startColumn=1, row.names=FALSE)
})

saveWorkbook(wb, "My_File.xlsx")

Using curl POST with variables defined in bash script functions

  • the info from Sir Athos worked perfectly !!

Here's how I had to use it in my curl script for couchDB. It really helped out a lot. Thanks!

bin/curl -X PUT "db_domain_name_:5984/_config/vhosts/$1.couchdb" -d '"/'"$1"'/"' --user "admin:*****"

Loop through files in a folder in matlab

Looping through all the files in the folder is relatively easy:

files = dir('*.csv');
for file = files'
    csv = load(file.name);
    % Do some stuff
end

Calculate execution time of a SQL query?

I found this one more helpful and simple

DECLARE @StartTime datetime,@EndTime datetime   
SELECT @StartTime=GETDATE() 
--Your Query to be run goes here--  
SELECT @EndTime=GETDATE()   
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in milliseconds]   

UIImage resize (Scale proportion)

This change worked for me:

// The size returned by CGImageGetWidth(imgRef) & CGImageGetHeight(imgRef) is incorrect as it doesn't respect the image orientation!
// CGImageRef imgRef = [image CGImage];
// CGFloat width = CGImageGetWidth(imgRef);
// CGFloat height = CGImageGetHeight(imgRef);
//
// This returns the actual width and height of the photo (and hence solves the problem
CGFloat width = image.size.width; 
CGFloat height = image.size.height;
CGRect bounds = CGRectMake(0, 0, width, height);

HTML-encoding lost when attribute read from input field

_x000D_
_x000D_
function encodeHTML(str) {_x000D_
    return document.createElement("a").appendChild( _x000D_
        document.createTextNode(str)).parentNode.innerHTML;_x000D_
};_x000D_
_x000D_
function decodeHTML(str) {_x000D_
    var element = document.createElement("a"); _x000D_
    element.innerHTML = str;_x000D_
    return element.textContent;_x000D_
};_x000D_
var str = "<"_x000D_
var enc = encodeHTML(str);_x000D_
var dec = decodeHTML(enc);_x000D_
console.log("str: " + str, "\nenc: " + enc, "\ndec: " + dec);
_x000D_
_x000D_
_x000D_

SQL Server - inner join when updating

UPDATE R 
SET R.status = '0' 
FROM dbo.ProductReviews AS R
INNER JOIN dbo.products AS P 
       ON R.pid = P.id 
WHERE R.id = '17190' 
  AND P.shopkeeper = '89137';

How to get a complete list of ticker symbols from Yahoo Finance?

NASDAQ Stock lists ftp://ftp.nasdaqtrader.com/symboldirectory

The 2 files nasdaqlisted.txt and otherlisted.txt are | pipe separated. That should give you a good list of all stocks.

How to convert latitude or longitude to meters?

The earth is an annoyingly irregular surface, so there is no simple formula to do this exactly. You have to live with an approximate model of the earth, and project your coordinates onto it. The model I typically see used for this is WGS 84. This is what GPS devices usually use to solve the exact same problem.

NOAA has some software you can download to help with this on their website.

Semi-transparent color layer over background-image?

You can also add opacity to your overlay color.

Instead of doing

background: url('../img/bg/diagonalnoise.png');
background-color: rgba(248, 247, 216, 0.7);

You can do:

background: url('../img/bg/diagonalnoise.png');

Then create a new style for the opacity color:

.colorStyle{
    background-color: rgba(248, 247, 216, 0.7);
    opacity: 0.8;
}

Change the opacity to whatever number you want below 1. Then you make this color style the same size as your image. It should work.

How to expand/collapse a diff sections in Vimdiff?

Aside from the ones you mention, I only use frequently when diffing the following:

  • :diffupdate :diffu -> recalculate the diff, useful when after making several changes vim's isn't showing minimal changes anymore. Note that it only works if the files have been modified inside vimdiff. Otherwise, use:
    • :e to reload the files if they have been modified outside of vimdiff.
  • :set noscrollbind -> temporarily disable simultaneous scrolling on both buffers, reenable by :set scrollbind and scrolling.

Most of what you asked for is folding: vim user manual's chapter on folding. Outside of diffs I sometime use:

  • zo -> open fold.
  • zc -> close fold.

But you'll probably be better served by:

  • zr -> reducing folding level.
  • zm -> one more folding level, please.

or even:

  • zR -> Reduce completely the folding, I said!.
  • zM -> fold Most!.

The other thing you asked for, use n lines of folding, can be found at the vim reference manual section on options, via the section on diff:

  • set diffopt=<TAB>, then update or add context:n.

You should also take a look at the user manual section on diff.

html div onclick event

Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.

<div class="expandable-panel-heading">
<h2>
  <a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>

http://jsfiddle.net/NXML7/1/

CSS Display an Image Resized and Cropped

If you are using Bootstrap, try using { background-size: cover; } for the <div> maybe give the div a class say <div class="example" style=url('../your_image.jpeg');> so it becomes div.example{ background-size: cover}

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

Run this code It will open google print service popup.

function openPrint(x) {

   if (x > 0) { 
       openPrint(--x); print(x); openPrint(--x);
   }

}

Try it on console where x is integer .

openPrint(1);   // Will open Chrome Print Popup Once
openPrint(2);   // Will open Chrome Print Popup Twice after 1st close and so on

Thanks

MySQL Error 1264: out of range value for column

tl;dr

Make sure your AUTO_INCREMENT is not out of range. In that case, set a new value for it with:

ALTER TABLE table_name AUTO_INCREMENT=100 -- Change 100 to the desired number

Explanation

AUTO_INCREMENT can contain a number that is bigger than the maximum value allowed by the datatype. This can happen if you filled up a table that you emptied afterward but the AUTO_INCREMENT stayed the same, but there might be different reasons as well. In this case a new entry's id would be out of range.

Solution

If this is the cause of your problem, you can fix it by setting AUTO_INCREMENT to one bigger than the latest row's id. So if your latest row's id is 100 then:

ALTER TABLE table_name AUTO_INCREMENT=101

If you would like to check AUTO_INCREMENT's current value, use this command:

SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND   TABLE_NAME   = 'TableName';

How do I use $rootScope in Angular to store variables?

Sharing data between controllers is what Factories/Services are very good for. In short, it works something like this.

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

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

    itemsService.add = function(item) {
        items.push(item);
    };
    itemsService.list = function() {
        return items;
    };

    return itemsService;
});

function Ctrl1($scope,items) {
    $scope.list = items.list; 
}

function Ctrl2($scope, items) {
    $scope.add = items.add;
}

You can see a working example in this fiddle: http://jsfiddle.net/mbielski/m8saa/

How to clear the canvas for redrawing

This worked for my pieChart in chart.js

<div class="pie_nut" id="pieChartContainer">
    <canvas id="pieChart" height="5" width="6"></canvas> 
</div>

$('#pieChartContainer').html(''); //remove canvas from container
$('#pieChartContainer').html('<canvas id="pieChart" height="5" width="6"></canvas>'); //add it back to the container

phpmyadmin "Not Found" after install on Apache, Ubuntu

Create a link in /var/www like this:

sudo ln -s /usr/share/phpmyadmin /var/www/

Note: since 14.04 you may want to use /var/www/html/ instead of /var/www/

If that's not working for you, you need to include PHPMyAdmin inside apache configuration.

Open apache.conf using your favorite editor, mine is nano :)

sudo nano /etc/apache2/apache2.conf

Then add the following line:

Include /etc/phpmyadmin/apache.conf

For Ubuntu 15.04 and 16.04

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
sudo a2enconf phpmyadmin.conf
sudo service apache2 reload

ValidateAntiForgeryToken purpose, explanation and example

The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks.

A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user. For more information on this please visit http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages.

It is simple to use, you need to decorate method with ValidateAntiForgeryToken attribute as below:

[HttpPost]  
[ValidateAntiForgeryToken]  
public ActionResult CreateProduct(Product product)  
{
  if (ModelState.IsValid)  
  {
    //your logic 
  }
  return View(ModelName);
}

It is derived from System.Web.Mvc namespace.

And in your view, add this code to add the token so it is used to validate the form upon submission.

@Html.AntiForgeryToken()

How to set the custom border color of UIView programmatically?

Write the code in your viewDidLoad()

self.view.layer.borderColor = anyColor().CGColor

And you can set Color with RGB

func anyColor() -> UIColor {
    return UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
}

Learn something about CALayer in UIKit

How to disable Home and other system buttons in Android?

You can't disable Home button from ICS onwords but can disable other buttons as follows

@Override
public boolean dispatchKeyEvent(KeyEvent keyEvent){
   return true;
}

How do you plot bar charts in gnuplot?

plot "data.dat" using 2: xtic(1) with histogram

Here data.dat contains data of the form

title 1
title2 3
"long title" 5

How do I do an initial push to a remote repository with Git?

If your project doesn't have an upstream branch, that is if this is the very first time the remote repository is going to know about the branch created in your local repository the following command should work.

git push --set-upstream origin <branch-name>

How to change theme for AlertDialog

I guess it cannot be done. At least not with the Builder. I'm working with 1.6 and the Implementation in Builder.create() is:

public AlertDialog create() {
    final AlertDialog dialog = new AlertDialog(P.mContext);
    P.apply(dialog.mAlert);
    [...]
}

which calls the "not-theme-aware" constructor of AlertDialog, which looks like this:

protected AlertDialog(Context context) {
    this(context, com.android.internal.R.style.Theme_Dialog_Alert);
}

There is a second constructor in AlertDialog for changing themes:

protected AlertDialog(Context context, int theme) {
    super(context, theme);
    [...]
}

that the Builder just doesn't call.

If the Dialog is pretty generic anyway, I'd try writing a subclass of AlertDialog, calling the second constructor and use that class instead of the Builder-mechanism.

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

I agree with the other answerers that in most cases (almost always) it is necessary to sanitize Your input.

But consider such code (it is for a REST controller):

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
            case 'GET':
                return $this->doGet($request, $object);
            case 'POST':
                return $this->doPost($request, $object);
            case 'PUT':
                return $this->doPut($request, $object);
            case 'DELETE':
                return $this->doDelete($request, $object);
            default:
                return $this->onBadRequest();
}

It would not be very useful to apply sanitizing here (although it would not break anything, either).

So, follow recommendations, but not blindly - rather understand why they are for :)

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

Unexpected token < in first line of HTML

I had the same issue. I published the angular/core application on iis.

To change the Identity of the application pool solved my issue. Now the Identity is LocalSystem

How to strip HTML tags from string in JavaScript?

cleanText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");

Distilled from this website (web.achive).

This regex looks for <, an optional slash /, one or more characters that are not >, then either > or $ (the end of the line)

Examples:

'<div>Hello</div>' ==> 'Hello'
 ^^^^^     ^^^^^^
'Unterminated Tag <b' ==> 'Unterminated Tag '
                  ^^

But it is not bulletproof:

'If you are < 13 you cannot register' ==> 'If you are '
            ^^^^^^^^^^^^^^^^^^^^^^^^
'<div data="score > 42">Hello</div>' ==> ' 42">Hello'
 ^^^^^^^^^^^^^^^^^^          ^^^^^^

If someone is trying to break your application, this regex will not protect you. It should only be used if you already know the format of your input. As other knowledgable and mostly sane people have pointed out, to safely strip tags, you must use a parser.

If you do not have acccess to a convenient parser like the DOM, and you cannot trust your input to be in the right format, you may be better off using a package like sanitize-html, and also other sanitizers are available.