Programs & Examples On #Jcc

C++ code generator of wrappers for Java libraries

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

There is now a headless version of opencv-python which removes the graphical dependencies (like libSM). You can see the normal / headless version on the releases page (and the GitHub issue leading to this); just add -headless when installing, e.g.,

pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless

What are the integrity and crossorigin attributes?

Technically, the Integrity attribute helps with just that - it enables the proper verification of the data source. That is, it merely allows the browser to verify the numbers in the right source file with the amounts requested by the source file located on the CDN server.

Going a bit deeper, in case of the established encrypted hash value of this source and its checked compliance with a predefined value in the browser - the code executes, and the user request is successfully processed.

Crossorigin attribute helps developers optimize the rates of CDN performance, at the same time, protecting the website code from malicious scripts.

In particular, Crossorigin downloads the program code of the site in anonymous mode, without downloading cookies or performing the authentication procedure. This way, it prevents the leak of user data when you first load the site on a specific CDN server, which network fraudsters can easily replace addresses.

Source: https://yon.fun/what-is-link-integrity-and-crossorigin/

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

Why does typeof array with objects return "object" and not "array"?

Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.

Associative Array

var a = new Array(1,2,3); 
a['key'] = 'experiment';
Array.isArray(a);

returns true

Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.

Object

var a = {1:1, 2:2, 3:3,'key':'experiment'}; 
Array.isArray(a)

returns false

JSON returns an Object ... could return an Associative Array ... but it is not like that

How do I connect to a Websphere Datasource with a given JNDI name?

Jason,

This is how it works.

Localnamespace - java:comp/env is a local name space used by the application. The name that you use in it jdbc/db is just an alias. It does not refer to a physical resource.

During deployment this alias should be mapped to a physical resource (in your case a data source) that is defined on the WAS/WPS run time.

This is actually stored in ejb-bnd.xmi files. In the latest versions the XMIs are replaced with XML files. These files are referred to as the Binding files.

HTH Manglu

Calling Java from Python

I've been integrating a lot of stuff into Python lately, including Java. The most robust method I've found is to use IKVM and a C# wrapper.

IKVM has a neat little application that allows you to take any Java JAR, and convert it directly to .Net DLL. It simply translates the JVM bytecode to CLR bytecode. See http://sourceforge.net/p/ikvm/wiki/Ikvmc/ for details.

The converted library behaves just like a native C# library, and you can use it without needing the JVM. You can then create a C# DLL wrapper project, and add a reference to the converted DLL.

You can now create some wrapper stubs that call the methods that you want to expose, and mark those methods as DllEport. See https://stackoverflow.com/a/29854281/1977538 for details.

The wrapper DLL acts just like a native C library, with the exported methods looking just like exported C methods. You can connect to them using ctype as usual.

I've tried it with Python 2.7, but it should work with 3.0 as well. Works on Windows and the Linuxes

If you happen to use C#, then this is probably the best approach to try when integrating almost anything into python.

Jackson serialization: ignore empty values (or null)

You need to add import com.fasterxml.jackson.annotation.JsonInclude;

Add

@JsonInclude(JsonInclude.Include.NON_NULL)

on top of POJO

If you have nested POJO then

@JsonInclude(JsonInclude.Include.NON_NULL)

need to add on every values.

NOTE: JAXRS (Jersey) automatically handle this scenario 2.6 and above.

Class 'ViewController' has no initializers in swift

Sometimes this error also appears when you have a var or a let that hasn't been intialized.

For example

class ViewController: UIViewController {
    var x: Double
    // or
    var y: String
    // or
    let z: Int
}

Depending on what your variable is supposed to do you might either set that var type as an optional or initialize it with a value like the following

class ViewController: UIViewCOntroller {
    // Set an initial value for the variable
    var x: Double = 0
    // or an optional String
    var y: String?
    // or
    let z: Int = 2
}

How exactly does <script defer="defer"> work?

Should be also noted that there might be problems in IE<=9 when using script defer in certain situations. More on this: https://github.com/h5bp/lazyweb-requests/issues/42

What is the use of style="clear:both"?

When you use float without width, there remains some space in that row. To block this space you can use clear:both; in next element.

Where does Internet Explorer store saved passwords?

No guarantee, but I suspect IE uses the older Protected Storage API.

How do you reverse a string in place in JavaScript?

I know that this is an old question that has been well answered, but for my own amusement I wrote the following reverse function and thought I would share it in case it was useful for anyone else. It handles both surrogate pairs and combining marks:

function StringReverse (str)
{
  var charArray = [];
  for (var i = 0; i < str.length; i++)
    {
      if (i+1 < str.length)
        {
          var value = str.charCodeAt(i);
          var nextValue = str.charCodeAt(i+1);
          if (   (   value >= 0xD800 && value <= 0xDBFF
                  && (nextValue & 0xFC00) == 0xDC00) // Surrogate pair)
              || (nextValue >= 0x0300 && nextValue <= 0x036F)) // Combining marks
            {
              charArray.unshift(str.substring(i, i+2));
              i++; // Skip the other half
              continue;
            }
        }

      // Otherwise we just have a rogue surrogate marker or a plain old character.
      charArray.unshift(str[i]);
    }

  return charArray.join('');
}

All props to Mathias, Punycode, and various other references for schooling me on the complexities of character encoding in JavaScript.

Stop mouse event propagation

I used

<... (click)="..;..; ..someOtherFunctions(mybesomevalue); $event.stopPropagation();" ...>...

in short just seperate other things/function calls with ';' and add $event.stopPropagation()

How to import Google Web Font in CSS file?

You can also use @font-face to link to the URLs. http://www.css3.info/preview/web-fonts-with-font-face/

Does the CMS support iframes? You might be able to throw an iframe into the top of your content, too. This would probably be slower - better to include it in your CSS.

How to shift a column in Pandas DataFrame

Lets define the dataframe from your example by

>>> df = pd.DataFrame([[206, 214], [226, 234], [245, 253], [265, 272], [283, 291]], 
    columns=[1, 2])
>>> df
     1    2
0  206  214
1  226  234
2  245  253
3  265  272
4  283  291

Then you could manipulate the index of the second column by

>>> df[2].index = df[2].index+1

and finally re-combine the single columns

>>> pd.concat([df[1], df[2]], axis=1)
       1      2
0  206.0    NaN
1  226.0  214.0
2  245.0  234.0
3  265.0  253.0
4  283.0  272.0
5    NaN  291.0

Perhaps not fast but simple to read. Consider setting variables for the column names and the actual shift required.

Edit: Generally shifting is possible by df[2].shift(1) as already posted however would that cut-off the carryover.

Return multiple values from a function in swift

you should return three different values from this method and get these three in a single variable like this.

func getTime()-> (hour:Int,min:Int,sec:Int){
//your code
return (hour,min,sec)
}

get the value in single variable

let getTime = getTime()

now you can access the hour,min and seconds simply by "." ie.

print("hour:\(getTime.hour) min:\(getTime.min) sec:\(getTime.sec)")

Run a command over SSH with JSch

I am using JSCH since about 2000 and still find it a good library to use. I agree it is not documented well enough but the provided examples seem good enough to understand that is required in several minutes, and user friendly Swing, while this is quite original approach, allows to test the example quickly to make sure it actually works. It is not always true that every good project needs three times more documentation than the amount of code written, and even when such is present, this not always helps to write faster a working prototype of your concept.

Append text to textarea with javascript

Use event delegation by assigning the onclick to the <ol>. Then pass the event object as the argument, and using that, grab the text from the clicked element.

_x000D_
_x000D_
function addText(event) {_x000D_
    var targ = event.target || event.srcElement;_x000D_
    document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
  <li>Hello</li>_x000D_
  <li>World</li>_x000D_
  <li>Earthlings</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Note that this method of passing the event object works in older IE as well as W3 compliant systems.

php pdo: get the columns name of a table

Just Put your Database name,username,password (Where i marked ?) and table name.& Yuuppiii!.... you get all data from your main database (with column name)

<?php 

function qry($q){

    global $qry;
    try {   
    $host = "?";
    $dbname = "?";
    $username = "?";
    $password = "?";
    $dbcon = new PDO("mysql:host=$host; 
    dbname=$dbname","$username","$password");
}
catch (Exception $e) {

    echo "ERROR ".$e->getMEssage();

}

    $qry = $dbcon->query($q);
    $qry->setFetchMode(PDO:: FETCH_OBJ);

    return $qry;

}


echo "<table>";

/*Get Colums Names in table row */
$columns = array();

$qry1= qry("SHOW COLUMNS FROM Your_table_name");

while (@$column = $qry1->fetch()->Field) {
    echo "<td>".$column."</td>";
    $columns[] = $column;

}

echo "<tr>";

/* Fetch all data into a html table * /

$qry2 = qry("SELECT * FROM Your_table_name");

while ( $details = $qry2->fetch()) {

    echo "<tr>";
    foreach ($columns as $c_name) {
    echo "<td>".$details->$c_name."</td>";

}

}

echo "</table>";

?>

Understanding string reversal via slicing

The "-1" part represents the "step" part of the slicing—in this case, it goes through the string 1 character at a time, but backwards (a negative step means start from the end of the string). If you specify the step to be 2, for instance, you would get every other character of the string, starting with the first one. If you specify a step of -2, then you'd get every other character of the string, starting with the last character and working backwards.

So, in a nutshell, if a = '12345':

  • a[::2] becomes 135
  • a[::-1] becomes 54321
  • a[::-2] becomes 531

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

perform an action on checkbox checked or unchecked event on html form

Given you use JQuery, you can do something like below :

HTML

<form id="myform">
    syn<input type="checkbox" name="checkfield" id="g01-01"  onclick="doalert()"/>
</form>

JS

function doalert() {
  if ($("#g01-01").is(":checked")) {
    alert ("hi");
  } else {
    alert ("bye");
  }
}

Is jQuery $.browser Deprecated?

From the official documentation at http://api.jquery.com/jQuery.browser/:

This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin.

You can use for example jquery-migrate-1.4.1.js to keep your existing code or plugins that use $.browser still working while you find a way to totally get rid of $.browser from your code in the future.

Fast way to get the min/max values among properties of object

// Sorted
let Sorted = Object.entries({ "a":4, "b":0.5 , "c":0.35, "d":5 }).sort((prev, next) => prev[1] - next[1])
>> [ [ 'c', 0.35 ], [ 'b', 0.5 ], [ 'a', 4 ], [ 'd', 5 ] ]


//Min:
Sorted.shift()
>> [ 'c', 0.35 ]

// Max:
Sorted.pop()
>> [ 'd', 5 ]

error: ORA-65096: invalid common user or role name in oracle

SQL> alter session set "_ORACLE_SCRIPT"=true;  
SQL> create user sec_admin identified by "Chutinhbk123@!";

What does "while True" mean in Python?

Nothing evaluates to True faster than True. So, it is good if you use while True instead of while 1==1 etc.

type object 'datetime.datetime' has no attribute 'datetime'

You should really import the module into its own alias.

import datetime as dt
my_datetime = dt.datetime(year, month, day)

The above has the following benefits over the other solutions:

  • Calling the variable my_datetime instead of date reduces confusion since there is already a date in the datetime module (datetime.date).
  • The module and the class (both called datetime) do not shadow each other.

In a simple to understand explanation, what is Runnable in Java?

Runnable is an interface defined as so:

interface Runnable {
    public void run();
}

To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {

It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.

If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.

It should also be noted that Threads implement Runnable, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable) without overriding Thread's run method.

What is the difference between "is None" and "== None"

It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None differently from is None.

In particular the output of a == None does not even have to be boolean !! - a frequent cause of bugs.

For a specific example take a numpy array where the == comparison is implemented elementwise:

import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False

Quick Way to Implement Dictionary in C

Section 6.6 of The C Programming Language presents a simple dictionary (hashtable) data structure. I don't think a useful dictionary implementation could get any simpler than this. For your convenience, I reproduce the code here.

struct nlist { /* table entry: */
    struct nlist *next; /* next entry in chain */
    char *name; /* defined name */
    char *defn; /* replacement text */
};

#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE]; /* pointer table */

/* hash: form hash value for string s */
unsigned hash(char *s)
{
    unsigned hashval;
    for (hashval = 0; *s != '\0'; s++)
      hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;
}

/* lookup: look for s in hashtab */
struct nlist *lookup(char *s)
{
    struct nlist *np;
    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
        if (strcmp(s, np->name) == 0)
          return np; /* found */
    return NULL; /* not found */
}

char *strdup(char *);
/* install: put (name, defn) in hashtab */
struct nlist *install(char *name, char *defn)
{
    struct nlist *np;
    unsigned hashval;
    if ((np = lookup(name)) == NULL) { /* not found */
        np = (struct nlist *) malloc(sizeof(*np));
        if (np == NULL || (np->name = strdup(name)) == NULL)
          return NULL;
        hashval = hash(name);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    } else /* already there */
        free((void *) np->defn); /*free previous defn */
    if ((np->defn = strdup(defn)) == NULL)
       return NULL;
    return np;
}

char *strdup(char *s) /* make a duplicate of s */
{
    char *p;
    p = (char *) malloc(strlen(s)+1); /* +1 for ’\0’ */
    if (p != NULL)
       strcpy(p, s);
    return p;
}

Note that if the hashes of two strings collide, it may lead to an O(n) lookup time. You can reduce the likelihood of collisions by increasing the value of HASHSIZE. For a complete discussion of the data structure, please consult the book.

Python pandas: fill a dataframe row by row

My approach was, but I can't guarantee that this is the fastest solution.

df = pd.DataFrame(columns=["firstname", "lastname"])
df = df.append({
     "firstname": "John",
     "lastname":  "Johny"
      }, ignore_index=True)

mysql_fetch_array() expects parameter 1 to be resource problem

You are not doing error checking after the call to mysql_query:

$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if (!$result) { // add this check.
    die('Invalid query: ' . mysql_error());
}

In case mysql_query fails, it returns false, a boolean value. When you pass this to mysql_fetch_array function (which expects a mysql result object) we get this error.

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

Why use double indirection? or Why use pointers to pointers?

Why double pointers?

The objective is to change what studentA points to, using a function.

#include <stdio.h>
#include <stdlib.h>


typedef struct Person{
    char * name;
} Person; 

/**
 * we need a ponter to a pointer, example: &studentA
 */
void change(Person ** x, Person * y){
    *x = y; // since x is a pointer to a pointer, we access its value: a pointer to a Person struct.
}

void dontChange(Person * x, Person * y){
    x = y;
}

int main()
{

    Person * studentA = (Person *)malloc(sizeof(Person));
    studentA->name = "brian";

    Person * studentB = (Person *)malloc(sizeof(Person));
    studentB->name = "erich";

    /**
     * we could have done the job as simple as this!
     * but we need more work if we want to use a function to do the job!
     */
    // studentA = studentB;

    printf("1. studentA = %s (not changed)\n", studentA->name);

    dontChange(studentA, studentB);
    printf("2. studentA = %s (not changed)\n", studentA->name);

    change(&studentA, studentB);
    printf("3. studentA = %s (changed!)\n", studentA->name);

    return 0;
}

/**
 * OUTPUT:
 * 1. studentA = brian (not changed)
 * 2. studentA = brian (not changed)
 * 3. studentA = erich (changed!)
 */

How do I change the background of a Frame in Tkinter?

You use ttk.Frame, bg option does not work for it. You should create style and apply it to the frame.

from tkinter import *
from tkinter.ttk import * 

root = Tk()

s = Style()
s.configure('My.TFrame', background='red')

mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()

How do I find all of the symlinks in a directory tree?

What I do is create a script in my bin directory that is like an alias. For example I have a script named lsd ls -l | grep ^d

you could make one lsl ls -lR | grep ^l

Just chmod them +x and you are good to go.

Meaning of "[: too many arguments" error from if [] (square brackets)

I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-

export k=$(date "+%k");
if [ $k -ge 16 ] 
    then exit 0; 
else 
    echo "good job for nothing"; 
fi;

that way I resolved my problem. Hope that will help for you too.

Align DIV to bottom of the page

Nathan Lee's answer is perfect. I just wanted to add something about position:absolute;. If you wanted to use position:absolute; like you had in your code, you have to think of it as pushing it away from one side of the page.

For example, if you wanted your div to be somewhere in the bottom, you would have to use position:absolute; top:500px;. That would push your div 500px from the top of the page. Same rule applies for all other directions.

DEMO

How can I open a link in a new window?

this solution also considered the case that url is empty and disabled(gray) the empty link.

_x000D_
_x000D_
$(function() {_x000D_
  changeAnchor();_x000D_
});_x000D_
_x000D_
function changeAnchor() {_x000D_
  $("a[name$='aWebsiteUrl']").each(function() { // you can write your selector here_x000D_
    $(this).css("background", "none");_x000D_
    $(this).css("font-weight", "normal");_x000D_
_x000D_
    var url = $(this).attr('href').trim();_x000D_
    if (url == " " || url == "") { //disable empty link_x000D_
      $(this).attr("class", "disabled");_x000D_
      $(this).attr("href", "javascript:void(0)");_x000D_
    } else {_x000D_
      $(this).attr("target", "_blank");// HERE set the non-empty links, open in new window_x000D_
    }_x000D_
  });_x000D_
}
_x000D_
a.disabled {_x000D_
  text-decoration: none;_x000D_
  pointer-events: none;_x000D_
  cursor: default;_x000D_
  color: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<a name="aWebsiteUrl" href="http://www.baidu.com" class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href=" " class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href="http://www.alibaba.com" class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href="http://www.qq.com" class='#'>[website]</a>
_x000D_
_x000D_
_x000D_

Partly JSON unmarshal into a map in Go

This can be accomplished by Unmarshaling into a map[string]json.RawMessage.

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)

To further parse sendMsg, you could then do something like:

var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

For say, you can do the same thing and unmarshal into a string:

var str string
err = json.Unmarshal(objmap["say"], &str)

EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:

type sendMsg struct {
    User string
    Msg  string
}

Example: https://play.golang.org/p/OrIjvqIsi4-

Remove all non-"word characters" from a String in Java, leaving accented characters?

Well, here is one solution I ended up with, but I hope there's a more elegant one...

StringBuilder result = new StringBuilder();
for(int i=0; i<name.length(); i++) {
    char tmpChar = name.charAt( i );
    if (Character.isLetterOrDigit( tmpChar) || tmpChar == '_' ) {
        result.append( tmpChar );
    }
}

result ends up with the desired result...

Split output of command by columns using Bash?

Your command

ps | egrep 11383 | cut -d" " -f 4

misses a tr -s to squeeze spaces, as unwind explains in his answer.

However, you maybe want to use awk, since it handles all of these actions in a single command:

ps | awk '/11383/ {print $4}'

This prints the 4th column in those lines containing 11383. If you want this to match 11383 if it appears in the beginning of the line, then you can say ps | awk '/^11383/ {print $4}'.

Handling errors in Promise.all

As @jib said,

Promise.all is all or nothing.

Though, you can control certain promises that are "allowed" to fail and we would like to proceed to .then.

For example.

  Promise.all([
    doMustAsyncTask1,
    doMustAsyncTask2,
    doOptionalAsyncTask
    .catch(err => {
      if( /* err non-critical */) {
        return
      }
      // if critical then fail
      throw err
    })
  ])
  .then(([ mustRes1, mustRes2, optionalRes ]) => {
    // proceed to work with results
  })

return SQL table as JSON in python

One simple example for return SQL table as formatted JSON and fix error as he had @Whitecat

I get the error datetime.datetime(1941, 10, 31, 0, 0) is not JSON serializable

In that example you should use JSONEncoder.

import json
import pymssql

# subclass JSONEncoder
class DateTimeEncoder(JSONEncoder):
        #Override the default method
        def default(self, obj):
            if isinstance(obj, (datetime.date, datetime.datetime)):
                return obj.isoformat()

def mssql_connection():
    try:
        return pymssql.connect(server="IP.COM", user="USERNAME", password="PASSWORD", database="DATABASE")
    except Exception:
        print("\nERROR: Unable to connect to the server.")
        exit(-1)

def query_db(query):
    cur = mssql_connection().cursor()
    cur.execute(query)
    r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()]
    cur.connection.close()
    return r

def write_json(query_path):
    # read sql from file
    with open("../sql/my_sql.txt", 'r') as f:
        sql = f.read().replace('\n', ' ')
    # creating and writing to a json file and Encode DateTime Object into JSON using custom JSONEncoder
    with open("../output/my_json.json", 'w', encoding='utf-8') as f:
        json.dump(query_db(sql), f, ensure_ascii=False, indent=4, cls=DateTimeEncoder) 

if __name__ == "__main__":
    write_json()

# You get formatted my_json.json, for example:
[
   {
      "divroad":"N",
      "featcat":null,
      "countyfp":"001",
      "date":"2020-08-28"
   }
]

How to remove item from array by value?

In all values unique, you can:

a = new Set([1,2,3,4,5]) // a = Set(5) {1, 2, 3, 4, 5}
a.delete(3) // a = Set(5) {1, 2, 4, 5} 
[...a] // [1, 2, 4, 5]

Checking if a variable is initialized

There is no way of checking of the contents of a variable are undefined or not. The best thing you can do is to assign a signal/sentinel value (for example in the constructor) to indicate that further initialization will need to be carried out.

How to Use Order By for Multiple Columns in Laravel 4?

Simply invoke orderBy() as many times as you need it. For instance:

User::orderBy('name', 'DESC')
    ->orderBy('email', 'ASC')
    ->get();

Produces the following query:

SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC

How do you format an unsigned long long int using printf?

Non-standard things are always strange :)

for the long long portion under GNU it's L, ll or q

and under windows I believe it's ll only

Show loading gif after clicking form submit using jQuery

Better and clean example using JS only

Reference: TheDeveloperBlog.com

Step 1 - Create your java script and place it in your HTML page.

<script type="text/javascript">
    function ShowLoading(e) {
        var div = document.createElement('div');
        var img = document.createElement('img');
        img.src = 'loading_bar.GIF';
        div.innerHTML = "Loading...<br />";
        div.style.cssText = 'position: fixed; top: 5%; left: 40%; z-index: 5000; width: 422px; text-align: center; background: #EDDBB0; border: 1px solid #000';
        div.appendChild(img);
        document.body.appendChild(div);
        return true;
        // These 2 lines cancel form submission, so only use if needed.
        //window.event.cancelBubble = true;
        //e.stopPropagation();
    }
</script>

in your form call the java script function on submit event.

<form runat="server"  onsubmit="ShowLoading()">
</form>

Soon after you submit the form, it will show you the loading image.

Android: Scale a Drawable or background image?

One option to try is to put the image in the drawable-nodpi folder and set background of a layout to the drawable resource id.

This definitely works with scaling down, I haven't tested with scaling up though.

TypeError: $(...).DataTable is not a function

CAUSE

There could be multiple reasons for this error.

  • jQuery DataTables library is missing.
  • jQuery library is loaded after jQuery DataTables.
  • Multiple versions of jQuery library is loaded.

SOLUTION

Include only one version of jQuery library version 1.7 or newer before jQuery DataTables.

For example:

<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>

See jQuery DataTables: Common JavaScript console errors for more information on this and other common console errors.

How to clear a data grid view

IF you want to clear not only Data, but also ComboBoxes, Checkboxes, try

dataGridView.Columns.Clear();

MySQL query to select events between start/end date

select * from tbl where (endDate>=@starDate and startDate<=@endDate)

attached the diagram for explanationenter image description here

storing simple data in DB StartDate =10/01/2020 and endDate=20/01/2020. user can provide @startDate(d1) and @endDate(d2) to search.

here 6 scenarios can happen depicted by the 4 red lines (match data) 2 green lines (no match data).

so by conclusion from the image, to get data from DB by providing d1,d2. ED must be greater than d1(@startDate) and SD must be less than d2(@endDate).

"Multiple definition", "first defined here" errors

The problem here is that you are including commands.c in commands.h before the function prototype. Therefore, the C pre-processor inserts the content of commands.c into commands.h before the function prototype. commands.c contains the function definition. As a result, the function definition ends up before than the function declaration causing the error.

The content of commands.h after the pre-processor phase looks like this:

#ifndef COMMANDS_H_
#define COMMANDS_H_

// function definition
void f123(){

}

// function declaration
void f123();

#endif /* COMMANDS_H_ */

This is an error because you can't declare a function after its definition in C. If you swapped #include "commands.c" and the function declaration the error shouldn't happen because, now, the function prototype comes before the function declaration.

However, including a .c file is a bad practice and should be avoided. A better solution for this problem would be to include commands.h in commands.c and link the compiled version of command to the main file. For example:

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123(); // function declaration

#endif

commands.c

#include "commands.h"

void f123(){} // function definition

Resize jqGrid when browser is resized?

Hello Stack overflow enthusiasts. I enjoyed most of answers, and I even up-voted a couple, but none of them worked for me on IE 8 for some strange reason... I did however run into these links... This guy wrote a library that seems to work. Include it in your projects in adittion to jquery UI, throw in the name of your table and the div.

http://stevenharman.net/blog/archive/2009/08/21/creating-a-fluid-jquery-jqgrid.aspx

http://code.google.com/p/codeincubator/source/browse/#svn%2FSamples%2Fsteveharman%2FjQuery%2Fjquery.jqgrid.fluid%253Fstate%253Dclosed

Can you force Vue.js to reload/re-render?

<my-component :key="uniqueKey" />

along with it use this.$set(obj,'obj_key',value) and update uniqueKey for every update in object (obj) value for every update this.uniqueKey++

it worked for me this way

In Python, how do you convert a `datetime` object to seconds?

Maybe off-the-topic: to get UNIX/POSIX time from datetime and convert it back:

>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0

# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)

Note that different timezones have impact on results, e.g. my current TZ/DST returns:

>>>  time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h

therefore one should consider normalizing to UTC by using UTC versions of the functions.

Note that previous result can be used to calculate UTC offset of your current timezone. In this example this is +1h, i.e. UTC+0100.

References:

Convert Map<String,Object> to Map<String,String>

Use the Java 8 way of converting a Map<String, Object> to Map<String, String>. This solution handles null values.

Map<String, String> keysValuesStrings = keysValues.entrySet().stream()
    .filter(entry -> entry.getValue() != null)
    .collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().toString()));

Zip lists in Python

zip takes a bunch of lists likes

a: a1 a2 a3 a4 a5 a6 a7...
b: b1 b2 b3 b4 b5 b6 b7...
c: c1 c2 c3 c4 c5 c6 c7...

and "zips" them into one list whose entries are 3-tuples (ai, bi, ci). Imagine drawing a zipper horizontally from left to right.

How to Get the HTTP Post data in C#?

Try this

string[] keys = Request.Form.AllKeys;
var value = "";
for (int i= 0; i < keys.Length; i++) 
{
   // here you get the name eg test[0].quantity
   // keys[i];
   // to get the value you use
   value = Request.Form[keys[i]];
}

T-SQL split string

All the functions for string splitting that use some kind of Loop-ing (iterations) have bad performance. They should be replaced with set-based solution.

This code executes excellent.

CREATE FUNCTION dbo.SplitStrings
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN 
   (  
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM 
      ( 
        SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)
   );
GO

Calling a user defined function in jQuery

If you want to call a normal function via a jQuery event, you can do it like this:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#btnSun').click(myFunction);_x000D_
});_x000D_
_x000D_
function myFunction() {_x000D_
  alert('hi');_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="btnSun">Say hello!</button>
_x000D_
_x000D_
_x000D_

How can I get the name of an object in Python?

That's not really possible, as there could be multiple variables that have the same value, or a value might have no variable, or a value might have the same value as a variable only by chance.

If you really want to do that, you can use

def variable_for_value(value):
    for n,v in globals().items():
        if v == value:
            return n
    return None

However, it would be better if you would iterate over names in the first place:

my_list = ["x", "y", "z"] # x, y, z have been previously defined

for name in my_list:
    print "handling variable ", name
    bla = globals()[name]
    # do something to bla

 

Python "SyntaxError: Non-ASCII character '\xe2' in file"

for me, the problem was caused by typing my code into Mac Notes and then copied it from Mac Notes and pasted into my vim session to create my file. This made my single quotes the curved type. to fix it I opened my file in vim and replaced all my curved single quotes with the straight kind, just by removing and retyping the same character. It was Mac Notes that made the same key stroke produce the curved single quote.

Disabled href tag

$(document).ready(function() {
   $('a').click(function(e) {
     e.preventDefault();
  });
});

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

How to enable external request in IIS Express?

I did the following and was able to connect:

1) changed IIS express config binding from local host to '*'

binding protocol="http" bindingInformation="*:8888:*"

2) Defined inbound rule on firewall to allow the particular port for the protocol type: tcp

3) Add the following command to add network configuration for your port: netsh http add urlacl url=http://*:8888/ user=everyone

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

This code seems completely unnecessary:

String serverURLS = getRecipientURL(message);

serverURLS = "https:\\\\abc.my.domain.com:55555\\update";

if (serverURLS != null){
    serverURL = new URL(serverURLS);
}
  1. serverURLS is assigned the result of getRecipientURL(message)
  2. Then immediately you overwrite the value of serverURLS, making the previous statement a dead store
  3. Then, because if (serverURLS != null) evaluates to true, since you just assigned the variable a value in the preceding statement, you assign a value to serverURL. It is impossible for if (serverURLS != null) to evaluate to false!
  4. You never actually use the variable serverURLS beyond the previous line of code.

You could replace all of this with just:

serverURL = new URL("https:\\\\abc.my.domain.com:55555\\update");

What is the most efficient way to loop through dataframes with pandas?

I believe the most simple and efficient way to loop through DataFrames is using numpy and numba. In that case, looping can be approximately as fast as vectorized operations in many cases. If numba is not an option, plain numpy is likely to be the next best option. As has been noted many times, your default should be vectorization, but this answer merely considers efficient looping, given the decision to loop, for whatever reason.

For a test case, let's use the example from @DSM's answer of calculating a percentage change. This is a very simple situation and as a practical matter you would not write a loop to calculate it, but as such it provides a reasonable baseline for timing vectorized approaches vs loops.

Let's set up the 4 approaches with a small DataFrame, and we'll time them on a larger dataset below.

import pandas as pd
import numpy as np
import numba as nb

df = pd.DataFrame( { 'close':[100,105,95,105] } )

pandas_vectorized = df.close.pct_change()[1:]

x = df.close.to_numpy()
numpy_vectorized = ( x[1:] - x[:-1] ) / x[:-1]
        
def test_numpy(x):
    pct_chng = np.zeros(len(x))
    for i in range(1,len(x)):
        pct_chng[i] = ( x[i] - x[i-1] ) / x[i-1]
    return pct_chng

numpy_loop = test_numpy(df.close.to_numpy())[1:]

@nb.jit(nopython=True)
def test_numba(x):
    pct_chng = np.zeros(len(x))
    for i in range(1,len(x)):
        pct_chng[i] = ( x[i] - x[i-1] ) / x[i-1]
    return pct_chng
    
numba_loop = test_numba(df.close.to_numpy())[1:]

And here are the timings on a DataFrame with 100,000 rows (timings performed with Jupyter's %timeit function, collapsed to a summary table for readability):

pandas/vectorized   1,130 micro-seconds
numpy/vectorized      382 micro-seconds
numpy/looped       72,800 micro-seconds
numba/looped          455 micro-seconds

Summary: for simple cases, like this one, you would go with (vectorized) pandas for simplicity and readability, and (vectorized) numpy for speed. If you really need to use a loop, do it in numpy. If numba is available, combine it with numpy for additional speed. In this case, numpy + numba is almost as fast as vectorized numpy code.

Other details:

  • Not shown are various options like iterrows, itertuples, etc. which are orders of magnitude slower and really should never be used.
  • The timings here are fairly typical: numpy is faster than pandas and vectorized is faster than loops, but adding numba to numpy will often speed numpy up dramatically.
  • Everything except the pandas option requires converting the DataFrame column to a numpy array. That conversion is included in the timings.
  • The time to define/compile the numpy/numba functions was not included in the timings, but would generally be a negligible component of the timing for any large dataframe.

Which Java library provides base64 encoding/decoding?

Guava also has Base64 (among other encodings and incredibly useful stuff)

How to execute raw queries with Laravel 5.1?

    DB::statement("your query")

I used it for add index to column in migration

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

At the moment, this can be done as follows

$ANDROID_HOME/build-tools/28.0.3/aapt dump badging /<path to>/<app name>.apk

In General, it will be:

$ANDROID_HOME/build-tools/<version_of_build_tools>/aapt dump badging /<path to>/<app name>.apk

How to make a edittext box in a dialog

I know its too late to answer this question but for others who are searching for some thing similar to this here is a simple code of an alertbox with an edittext

AlertDialog.Builder alert = new AlertDialog.Builder(this); 

or

new AlertDialog.Builder(mContext, R.style.MyCustomDialogTheme);

if you want to change the theme of the dialog.

final EditText edittext = new EditText(ActivityContext);
alert.setMessage("Enter Your Message");
alert.setTitle("Enter Your Title");

alert.setView(edittext);

alert.setPositiveButton("Yes Option", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        //What ever you want to do with the value
        Editable YouEditTextValue = edittext.getText();
        //OR
        String YouEditTextValue = edittext.getText().toString();
    }
});

alert.setNegativeButton("No Option", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // what ever you want to do with No option.
    }
});

alert.show();

Calculate the mean by group

We already have tons of options to get mean by group, adding one more from mosaic package.

mosaic::mean(speed~dive, data = df)
#dive1 dive2 
#0.579 0.440 

This returns a named numeric vector, if needed a dataframe we can wrap it in stack

stack(mosaic::mean(speed~dive, data = df))

#  values   ind
#1  0.579 dive1
#2  0.440 dive2

data

set.seed(123)
df <- data.frame(dive=factor(sample(c("dive1","dive2"),10,replace=TRUE)),
                 speed=runif(10))

How to create a DB link between two oracle instances

If you want to access the data in instance B from the instance A. Then this is the query, you can edit your respective credential.

CREATE DATABASE LINK dblink_passport
CONNECT TO xxusernamexx IDENTIFIED BY xxpasswordxx
USING
'(DESCRIPTION=
(ADDRESS=
(PROTOCOL=TCP)
(HOST=xxipaddrxx / xxhostxx )
(PORT=xxportxx))
(CONNECT_DATA=
(SID=xxsidxx)))';

After executing this query access table

SELECT * FROM tablename@dblink_passport;

You can perform any operation DML, DDL, DQL

How do I avoid the specification of the username and password at every git push?

My Solution on Windows:

  1. Right click at directory to push and select "Git Bash Here".
  2. ssh-keygen -t rsa (Press enter for all values)
  3. Check terminal for: Your public key has been saved in /c/Users/<your_user_name_here>/.ssh/id_rsa.pub
  4. Copy public key from specified file.
  5. Go to your GitHub profile => Settings => SSH and GPG keys => New SSH key => Paste your SSH key there => Save

Center icon in a div - horizontally and vertically

Horizontal centering is as easy as:

text-align: center

Vertical centering when the container is a known height:

height: 100px;
line-height: 100px;
vertical-align: middle

Vertical centering when the container isn't a known height AND you can set the image in the background:

background: url(someimage) no-repeat center center;

What version of Java is running in Eclipse?

String runtimeVersion = System.getProperty("java.runtime.version");

should return you a string along the lines of:

1.5.0_01-b08

That's the version of Java that Eclipse is using to run your code which is not necessarily the same version that's being used to run Eclipse itself.

JavaScript calculate the day of the year (1 - 366)

Math.floor((Date.now() - Date.parse(new Date().getFullYear(), 0, 0)) / 86400000)

this is my solution

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

I had the same issue on Windows 7 and I had to install both JDK and JRE and it's a success.

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

My issue was not sending the response back, so it was hanging. If you are using express make sure that res.send(data), res.json(data) or whatever the api method you wanna use is executed for the route you are testing.

Copy file from source directory to binary directory using CMake

both option are valid and targeting two different steps of your build:

  1. file(COPY ... copies the file in configuration step and only in this step. When you rebuild your project without having changed your cmake configuration, this command won't be executed.
  2. add_custom_command is the preferred choice when you want to copy the file around on each build step.

The right version for your task would be:

add_custom_command(
        TARGET foo POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy
                ${CMAKE_SOURCE_DIR}/test/input.txt
                ${CMAKE_CURRENT_BINARY_DIR}/input.txt)

you can choose between PRE_BUILD, PRE_LINK, POST_BUILD best is you read the documentation of add_custom_command

an example on how to use the first version can be found here: Use CMake add_custom_command to generate source for another target

How to create PDFs in an Android app?

A bit late and I have not yet tested it yet myself but another library that is under the BSD license is Android PDF Writer.

Update I have tried the library myself. Works ok with simple pdf generations (it provide methods for adding text, lines, rectangles, bitmaps, fonts). The only problem is that the generated PDF is stored in a String in memory, this may cause memory issues in large documents.

How can I slice an ArrayList out of an ArrayList in Java?

Although this post is very old. In case if somebody is looking for this..

Guava facilitates partitioning the List into sublists of a specified size

List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
    List<List<Integer>> subSets = Lists.partition(intList, 3);

How to support UTF-8 encoding in Eclipse

I tried all settings mentioned in this post to build my project successfully however that didn't work for me. At last I was able to build my project successfully with mvn -DargLine=-Dfile.encoding=UTF-8 clean insall command.

PG::ConnectionBad - could not connect to server: Connection refused

I stopped the rails server, ran rake db:migrate and started my rails s.

Is there a way to detect if an image is blurry?

Building off of Nike's answer. Its straightforward to implement the laplacian based method with opencv:

short GetSharpness(char* data, unsigned int width, unsigned int height)
{
    // assumes that your image is already in planner yuv or 8 bit greyscale
    IplImage* in = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,1);
    IplImage* out = cvCreateImage(cvSize(width,height),IPL_DEPTH_16S,1);
    memcpy(in->imageData,data,width*height);

    // aperture size of 1 corresponds to the correct matrix
    cvLaplace(in, out, 1);

    short maxLap = -32767;
    short* imgData = (short*)out->imageData;
    for(int i =0;i<(out->imageSize/2);i++)
    {
        if(imgData[i] > maxLap) maxLap = imgData[i];
    }

    cvReleaseImage(&in);
    cvReleaseImage(&out);
    return maxLap;
}

Will return a short indicating the maximum sharpness detected, which based on my tests on real world samples, is a pretty good indicator of if a camera is in focus or not. Not surprisingly, normal values are scene dependent but much less so than the FFT method which has to high of a false positive rate to be useful in my application.

How does C#'s random number generator work?

You can use Random.Next(int maxValue):

Return: A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.

var r = new Random();
// print random integer >= 0 and  < 100
Console.WriteLine(r.Next(100));

For this case however you could use Random.Next(int minValue, int maxValue), like this:

// print random integer >= 1 and < 101
Console.WriteLine(r.Next(1, 101);)
// or perhaps (if you have this specific case)
Console.WriteLine(r.Next(100) + 1);

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

Can I stretch text using CSS?

Always coming back to this page when a designer stretches a font on me. The accepted solution works great, but I frequently run into issues with margins.

Would recommend using the transform on the height instead of the width if you're running into issues, was a life safer for me in my current project.

.font-stretch {
    display: inline-block;
    -webkit-transform: scale(1,.9);
    -moz-transform: scale(1,.9);
    -ms-transform: scale(1,.9);
    -o-transform: scale(1,.9);
    transform: scale(1,.9);
}

Is there an equivalent of CSS max-width that works in HTML emails?

There is a trick you can do for Outlook 2007 using conditional html comments.
The code below will make sure that Outlook table is 800px wide, its not max-width but it works better than letting the table span across the entire window.

<!--[if gte mso 9]>
<style>
#tableForOutlook {
  width:800px;
}
</style>
<![endif]-->

<table style="width:98%;max-width:800px">
<!--[if gte mso 9]>
  <table id="tableForOutlook"><tr><td>
<![endif]-->
    <tr><td>
    [Your Content Goes Here]
    </td></tr>
<!--[if gte mso 9]>
  </td></tr></table>
<![endif]-->
<table>

Get element type with jQuery

you can use .is():

  $( "ul" ).click(function( event ) {
      var target = $( event.target );
      if ( target.is( "li" ) ) {
         target.css( "background-color", "red" );
      }
  });

see source

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

In Visual Studio 2012:

Go to the project properties -> Debug -> Uncheck "Enable the Visual Studio hosting process"

Fastest way to check if a string matches a regexp in ruby?

What I am wondering is if there is any strange way to make this check even faster, maybe exploiting some strange method in Regexp or some weird construct.

Regexp engines vary in how they implement searches, but, in general, anchor your patterns for speed, and avoid greedy matches, especially when searching long strings.

The best thing to do, until you're familiar with how a particular engine works, is to do benchmarks and add/remove anchors, try limiting searches, use wildcards vs. explicit matches, etc.

The Fruity gem is very useful for quickly benchmarking things, because it's smart. Ruby's built-in Benchmark code is also useful, though you can write tests that fool you by not being careful.

I've used both in many answers here on Stack Overflow, so you can search through my answers and will see lots of little tricks and results to give you ideas of how to write faster code.

The biggest thing to remember is, it's bad to prematurely optimize your code before you know where the slowdowns occur.

Can I access a form in the controller?

To be able to access the form in your controller, you have to add it to a dummy scope object.

Something like $scope.dummy = {}

For your situation this would mean something like:

<form name="dummy.customerForm">

In your controller you will be able to access the form by:

$scope.dummy.customerForm

and you will be able to do stuff like

$scope.dummy.customerForm.$setPristine()

WIKI LINK

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use <input type="text" ng-model="someObj.prop1"> rather than <input type="text" ng-model="prop1">

If you really want/need to use a primitive, there are two workarounds:

1.Use $parent.parentScopeProperty in the child scope. This will prevent the child scope from creating its own property. 2.Define a function on the parent scope, and call it from the child, passing the primitive value up to the parent (not always possible)

What's the difference between all the Selection Segues?

For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.

virtualenvwrapper and Python 3

You can make virtualenvwrapper use a custom Python binary instead of the one virtualenvwrapper is run with. To do that you need to use VIRTUALENV_PYTHON variable which is utilized by virtualenv:

$ export VIRTUALENV_PYTHON=/usr/bin/python3
$ mkvirtualenv -a myproject myenv
Running virtualenv with interpreter /usr/bin/python3
New python executable in myenv/bin/python3
Also creating executable in myenv/bin/python
(myenv)$ python
Python 3.2.3 (default, Oct 19 2012, 19:53:16) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Can you find all classes in a package using reflection?

Provided you are not using any dynamic class loaders you can search the classpath and for each entry search the directory or JAR file.

How do you decompile a swf file

Get the Sothink SWF decompiler. Not free, but worth it. Recently used it to decompile an SWF that I had lost the fla for, and I could completely round-trip swf-fla and back!
link text

Bootstrap button - remove outline on Chrome OS X

This will remove it - short and clean:

.btn {
    outline: none !important;
}

Selenium wait until document is ready

Like Rubanov wrote for C#, i write it for Java, and it is:

    public void waitForPageLoaded() {
    ExpectedCondition<Boolean> expectation = new
            ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver driver) {
                    return (((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete")&&((Boolean)((JavascriptExecutor)driver).executeScript("return jQuery.active == 0")));
                }
            };
    try {
        Thread.sleep(100);
        WebDriverWait waitForLoad = new WebDriverWait(driver, 30);
        waitForLoad.until(expectation);
    } catch (Throwable error) {
        Assert.fail("Timeout waiting for Page Load Request to complete.");
    }
}

How does Access-Control-Allow-Origin header work?

i work with express 4 and node 7.4 and angular,I had the same problem me help this:
a) server side: in file app.js i give headers to all response like:

app.use(function(req, res, next) {  
      res.header('Access-Control-Allow-Origin', req.headers.origin);
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
 });  

this must have before all router.
I saw a lot of added this headers:

res.header("Access-Control-Allow-Headers","*");
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');

but i dont need that,
b) client side: in send ajax you need add: "withCredentials: true," like:

$http({
     method: 'POST',
     url: 'url, 
     withCredentials: true,
     data : {}
   }).then(function(response){
        // code  
   }, function (response) {
         // code 
   });

good luck.

sendKeys() in Selenium web driver

Try this, it will surely work:

driver.findElement(By.xpath("//label[text()='User Name:']/following::div/input")).sendKeys("UserName" + Keys.TAB);

What is the difference between Bower and npm?

This answer is an addition to the answer of Sindre Sorhus. The major difference between npm and Bower is the way they treat recursive dependencies. Note that they can be used together in a single project.

On the npm FAQ: (archive.org link from 6 Sep 2015)

It is much harder to avoid dependency conflicts without nesting dependencies. This is fundamental to the way that npm works, and has proven to be an extremely successful approach.

On Bower homepage:

Bower is optimized for the front-end. Bower uses a flat dependency tree, requiring only one version for each package, reducing page load to a minimum.

In short, npm aims for stability. Bower aims for minimal resource load. If you draw out the dependency structure, you will see this:

npm:

project root
[node_modules] // default directory for dependencies
 -> dependency A
 -> dependency B
    [node_modules]
    -> dependency A

 -> dependency C
    [node_modules]
    -> dependency B
      [node_modules]
       -> dependency A 
    -> dependency D

As you can see it installs some dependencies recursively. Dependency A has three installed instances!

Bower:

project root
[bower_components] // default directory for dependencies
 -> dependency A
 -> dependency B // needs A
 -> dependency C // needs B and D
 -> dependency D

Here you see that all unique dependencies are on the same level.

So, why bother using npm?

Maybe dependency B requires a different version of dependency A than dependency C. npm installs both versions of this dependency so it will work anyway, but Bower will give you a conflict because it does not like duplication (because loading the same resource on a webpage is very inefficient and costly, also it can give some serious errors). You will have to manually pick which version you want to install. This can have the effect that one of the dependencies will break, but that is something that you will need to fix anyway.

So, the common usage is Bower for the packages that you want to publish on your webpages (e.g. runtime, where you avoid duplication), and use npm for other stuff, like testing, building, optimizing, checking, etc. (e.g. development time, where duplication is of less concern).

Update for npm 3:

npm 3 still does things differently compared to Bower. It will install the dependencies globally, but only for the first version it encounters. The other versions are installed in the tree (the parent module, then node_modules).

  • [node_modules]
    • dep A v1.0
    • dep B v1.0
      • dep A v1.0 (uses root version)
    • dep C v1.0
      • dep A v2.0 (this version is different from the root version, so it will be an nested installation)

For more information, I suggest reading the docs of npm 3

How do I get the unix timestamp in C as an int?

For 32-bit systems:

fprintf(stdout, "%u\n", (unsigned)time(NULL)); 

For 64-bit systems:

fprintf(stdout, "%lu\n", (unsigned long)time(NULL)); 

add string to String array

Since Java arrays hold a fixed number of values, you need to create a new array with a length of 5 in this case. A better solution would be to use an ArrayList and simply add strings to the array.

Example:

ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test3");
scripts.add("test4");
scripts.add("test5");

// Then later you can add more Strings to the ArrayList
scripts.add("test1");
scripts.add("test2");

Access IP Camera in Python OpenCV

First find out your IP camera's streaming url, like whether it's RTSP/HTTP etc.

Code changes will be as follows:

cap = cv2.VideoCapture("ipcam_streaming_url")

For example:

cap = cv2.VideoCapture("http://192.168.18.37:8090/test.mjpeg")

No mapping found for HTTP request with URI.... in DispatcherServlet with name

Please check your [PROJECT_NAME]\target\classes directory to see whether myController.class is generated or not.

If not, please check all your java source code whether there are any compilation errors.

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Run a Command Prompt command from Desktop Shortcut

I tried this, all it did was open a cmd prompt with "cmd -c (my command)" and didn't actually run it. see below.

C:\windows\System32>cmd -c (powercfg /lastwake) Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\windows\System32>

***Update
I changed my .bat file to read "cmd /k (powercfg /lastwake)" and it worked. You can also leave out the () and it works too.

How to Retrieve value from JTextField in Java Swing?

You can use the getText() method anywhere in your code it is instancely called by your object, So you can use the method anywhere within a calass

How to write a confusion matrix in Python?

Here is a simple implementation that handles an unequal number of classes in the predicted and actual labels (see examples 3 and 4). I hope this helps!

For folks just learning this, here's a quick review. The labels for the columns indicate the predicted class, and the labels for the rows indicate the correct class. In example 1, we have [3 1] on the top row. Again, rows indicate truth, so this means that the correct label is "0" and there are 4 examples with ground truth label of "0". Columns indicate predictions, so we have 3/4 of the samples correctly labeled as "0", but 1/4 was incorrectly labeled as a "1".

def confusion_matrix(actual, predicted):
    classes       = np.unique(np.concatenate((actual,predicted)))
    confusion_mtx = np.empty((len(classes),len(classes)),dtype=np.int)
    for i,a in enumerate(classes):
        for j,p in enumerate(classes):
            confusion_mtx[i,j] = np.where((actual==a)*(predicted==p))[0].shape[0]
    return confusion_mtx

Example 1:

actual    = np.array([1,1,1,1,0,0,0,0])
predicted = np.array([1,1,1,1,0,0,0,1])
confusion_matrix(actual,predicted)

   0  1
0  3  1
1  0  4

Example 2:

actual    = np.array(["a","a","a","a","b","b","b","b"])
predicted = np.array(["a","a","a","a","b","b","b","a"])
confusion_matrix(actual,predicted)

   0  1
0  4  0
1  1  3

Example 3:

actual    = np.array(["a","a","a","a","b","b","b","b"])
predicted = np.array(["a","a","a","a","b","b","b","z"]) # <-- notice the 3rd class, "z"
confusion_matrix(actual,predicted)

   0  1  2
0  4  0  0
1  0  3  1
2  0  0  0

Example 4:

actual    = np.array(["a","a","a","x","x","b","b","b"]) # <-- notice the 4th class, "x"
predicted = np.array(["a","a","a","a","b","b","b","z"])
confusion_matrix(actual,predicted)

   0  1  2  3
0  3  0  0  0
1  0  2  0  1
2  1  1  0  0
3  0  0  0  0

Changing the current working directory in Java?

There is no reliable way to do this in pure Java. Setting the user.dir property via System.setProperty() or java -Duser.dir=... does seem to affect subsequent creations of Files, but not e.g. FileOutputStreams.

The File(String parent, String child) constructor can help if you build up your directory path separately from your file path, allowing easier swapping.

An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.

The relevant Sun bug was closed in 2008 as "will not fix".

How to install APK from PC?

3 Ways to Install Applications On Android Without The Market

And don't forget to enable Unknown sources in your Android device Settings, before installing apk, else Android platform will not allow you to install apk directly

enter image description here

SQL : BETWEEN vs <= and >=

In this scenario col BETWEEN ... AND ... and col <= ... and col >= ... are equivalent.


SQL Standard defines also T461 Symmetric BETWEEN predicate:

 <between predicate part 2> ::=
 [ NOT ] BETWEEN [ ASYMMETRIC | SYMMETRIC ]
 <row value predicand> AND <row value predicand>

Transact-SQL does not support this feature.

BETWEEN requires that values are sorted. For instance:

SELECT 1 WHERE 3 BETWEEN 10 AND 1
-- no rows

<=>

SELECT 1 WHERE 3 >= 10 AND 3 <= 1
-- no rows

On the other hand:

SELECT 1 WHERE 3 BETWEEN SYMMETRIC 1 AND 10;
-- 1

SELECT 1 WHERE 3 BETWEEN SYMMETRIC 10 AND 1
-- 1

It works exactly as the normal BETWEEN but after sorting the comparison values.

db<>fiddle demo

AttributeError: 'tuple' object has no attribute

I am working in python flask: I had the same problem... There was a "," after I declared my my form variables; I am working with wtforms. That is what caused all the confusion

Failed to decode downloaded font

If you are using express you need to allow serving of static content by adding something like: var server = express(); server.use(express.static('./public')); // where public is the app root folder, with the fonts contained therein, at any level, i.e. public/fonts or public/dist/fonts... // If you are using connect, google for a similar configuration.

How can I make an svg scale with its parent container?

To specify the coordinates within the SVG image independently of the scaled size of the image, use the viewBox attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use the width and height attributes to define what the width or height are with respect to the containing page.

For instance, if you have the following:

<svg>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

It will render as a 10px by 20px triangle:

10x20 triangle

Now, if you set only the width and height, that will change the size of the SVG element, but not scale the triangle:

<svg width=100 height=50>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

10x20 triangle

If you set the view box, that causes it to transform the image such that the given box (in the coordinate system of the image) is scaled up to fit within the given width and height (in the coordinate system of the page). For instance, to scale up the triangle to be 100px by 50px:

<svg width=100 height=50 viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you want to scale it up to the width of the HTML viewport:

<svg width="100%" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x150 triangle

Note that by default, the aspect ratio is preserved. So if you specify that the element should have a width of 100%, but a height of 50px, it will actually only scale up to the height of 50px (unless you have a very narrow window):

<svg width="100%" height="50px" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you actually want it to stretch horizontally, disable aspect ratio preservation with preserveAspectRatio=none:

<svg width="100%" height="50px" viewBox="0 0 20 10" preserveAspectRatio="none">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x50 triangle

(note that while in my examples I use syntax that works for HTML embedding, to include the examples as an image in StackOverflow I am instead embedding within another SVG, so I need to use valid XML syntax)

How to remove newlines from beginning and end of a string?

If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:

Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:

 s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")

Complete Example:

public class RemoveLineBreaks {
    public static void main(String[] args) {
        var s = "\nHello\nWorld\n";
        System.out.println("before: >"+s+"<");
        s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
        System.out.println("after: >"+s+"<");
    }
}

It outputs:

before: >
Hello
World
<
after: >Hello
World<

How to get the date and time values in a C program?

To expand on the answer by Ori Osherov

You can use the WinAPI to get the date and time, this method is specific to Windows, but if you are targeting Windows only, or are already using the WinAPI then this is definitly a possibility1:

You can get both the time and date by using the SYSTEMTIME struct. You also need to call one of two functions (either GetLocalTime() or GetSystemTime()) to fill out the struct.

GetLocalTime() will give you the time and date specific to your time zone.

GetSystemTime() will give you the time and date in UTC.

The SYSTEMTIME struct has the following members:

wYear, wMonth, wDayOfWeek, wDay, wHour, wMinute, wSecond and wMilliseconds

You then need to just access the struct in the regular way


Actual example code:

#include <windows.h> // use to define SYSTEMTIME , GetLocalTime() and GetSystemTime()
#include <stdio.h> // For printf() (could otherwise use WinAPI equivalent)

int main(void) { // Or any other WinAPI entry point (e.g. WinMain/wmain)

    SYSTEMTIME t; // Declare SYSTEMTIME struct

    GetLocalTime(&t); // Fill out the struct so that it can be used

    // Use GetSystemTime(&t) to get UTC time 

    printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute:%d, Second: %d, Millisecond: %d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); // Return year, month, day, hour, minute, second and millisecond in that order

    return 0;
}

(Coded for simplicity and clarity, see the original answer for a better formatted method)

The output will be something like this:

Year: 2018, Month: 11, Day: 24, Hour: 12, Minute:28, Second: 1, Millisecond: 572

Useful References:

All the WinAPI documentation (most already listed above):

An extremely good beginners tutorial on this subject by Zetcode:

Simple operations with datetime on Codeproject:


1: As mentioned in the comments in Ori Osherov's answer ("Given that OP started with date +%F, they're almost certainly not using Windows. – melpomene Sep 9 at 22:17") the OP is not using Windows, however since this question has no platform specific tag (nor does it mention anywhere that the answer should be for that particular system), and is one of the top results when Googling "get time in c" both answers belong here, some users searching for an answer to this question may be on Windows and therefore will be useful to them.

405 method not allowed Web API

[HttpPost] is unnecessary!

[Route("")]
public void Post(ProductModel data)
{
    ...
}

How to gzip all files in all sub-directories into one compressed file in bash

@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU system, they can do this:

tar cvf - folderToCompress | gzip > compressFileName

To expand the archive:

zcat compressFileName | tar xvf -

Difference between $(window).load() and $(document).ready() functions

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
    $( document ).ready(function() {
        alert( "document loaded" );
    });

    $( window ).load(function() {
        alert( "window loaded" );
    });
    </script>
</head>
<body>
    <iframe src="http://stackoverflow.com"></iframe>
</body>
</html>

window.load will be triggered after all the iframe content is loaded

How to set div's height in css and html

<div style="height: 100px;"> </div>

OR

<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px;  }

reading from app.config file

This:

Console.WriteLine( "StartingMonthColumn is {0}", ConfigurationManager.AppSettings["StartingMonthColumn"]);

works fine for me.

Note that ConfigurationManager is in the System.Configuration namespace (so you'll likely want a using System.Configuration; statement), and that since what you read in has a string type you'll need to parse what you read in to use it as a number.

Also, be sure you set system.configuration.dll as a reference in your project or build script.

XSLT - How to select XML Attribute by Attribute?

Note: using // at the beginning of the xpath is a bit CPU intensitve -- it will search every node for a match. Using a more specific path, such as /root/DataSet will create a faster query.

Disposing WPF User Controls

You have to be careful using the destructor. This will get called on the GC Finalizer thread. In some cases the resources that your freeing may not like being released on a different thread from the one they were created on.

Sequence contains more than one element

FYI you can also get this error if EF Migrations tries to run with no Db configured, for example in a Test Project.

Chased this for hours before I figured out that it was erroring on a query, but, not because of the query but because it was when Migrations kicked in to try to create the Db.

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

the error can be due to one of several missing package. Below command will install several packages like g++, gcc, etc.

sudo apt-get install build-essential

Editing an item in a list<T>

class1 item = lst[index];
item.foo = bar;

Can not connect to local PostgreSQL

I had similar problem when trying to use postgresql with rails. Updating my Gemfile to use new version of gem pg solve this problem for me. (gem pg version 0.16.0 works). In the Gemfile use:

gem 'pg', '0.16.0'

then run the following to update the gem

bundle install --without production
bundle update
bundle install

Search an array for matching attribute

In this case i would use the ECMAscript 5 Array.filter. The following solution requires array.filter() that doesn't exist in all versions of IE.

Shims can be found here: MDN Array.filter or ES5-shim

var result = restaurants.filter(function (chain) {
    return chain.restaurant.food === "chicken";
})[0].restaurant.name;

How do I calculate the date six months from the current date using the datetime Python module?

So, here is an example of the dateutil.relativedelta which I found useful for iterating through the past year, skipping a month each time to the present date:

>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> today = datetime.datetime.today()
>>> month_count = 0
>>> while month_count < 12:
...  day = today - relativedelta(months=month_count)
...  print day
...  month_count += 1
... 
2010-07-07 10:51:45.187968
2010-06-07 10:51:45.187968
2010-05-07 10:51:45.187968
2010-04-07 10:51:45.187968
2010-03-07 10:51:45.187968
2010-02-07 10:51:45.187968
2010-01-07 10:51:45.187968
2009-12-07 10:51:45.187968
2009-11-07 10:51:45.187968
2009-10-07 10:51:45.187968
2009-09-07 10:51:45.187968
2009-08-07 10:51:45.187968

As with the other answers, you have to figure out what you actually mean by "6 months from now." If you mean "today's day of the month in the month six years in the future" then this would do:

datetime.datetime.now() + relativedelta(months=6)

How to make shadow on border-bottom?

The issue is shadow coming out the side of the containing div. In order to avoid this, the blur value must equal the absolute value of the spread value.

_x000D_
_x000D_
div {_x000D_
  -webkit-box-shadow: 0 4px 6px -6px #222;_x000D_
  -moz-box-shadow: 0 4px 6px -6px #222;_x000D_
  box-shadow: 0 4px 6px -6px #222;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

covered in depth here

subtract time from date - moment js

There is a simple function subtract which moment library gives us to subtract time from some time. Using it is also very simple.

moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time

//You can do this for days, years, months, hours, minutes, seconds
//You can also subtract multiple things simulatneously

//You can chain it like this.
moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time

//You can also use it as object literal
moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time

Hope this helps!

Node.js client for a socket.io server

Adding in example for solution given earlier. By using socket.io-client https://github.com/socketio/socket.io-client

Client Side:

//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {reconnect: true});

// Add a connect listener
socket.on('connect', function (socket) {
    console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');

Server Side :

//server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function (socket){
   console.log('connection');

  socket.on('CH01', function (from, msg) {
    console.log('MSG', from, ' saying ', msg);
  });

});

http.listen(3000, function () {
  console.log('listening on *:3000');
});

Run :

Open 2 console and run node server.js and node client.js

MVC ajax post to controller action method

try this:

/////// Controller post and get simple text value 
[HttpPost]
    public string Contact(string message)
    { 
        return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
    }

//// in the view add reference to the Javascript (jQuery) files

@section Scripts{

<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>  
}

/// then add the Post method as following:

<script type="text/javascript"> 

/// post and get text value
    
$("#send").on("click", function () {    
$.post('', { message: $('#msg').val() })  

//// empty post('') means post to the default controller, 
///we are not pacifying different action or controller
/// however we can define a url as following:
/// var url = "@(Url.Action("GetDataAction", "GetDataController"))"

         .done(function (response) {
             $("#myform").html(response);
        })
        .error(function () { alert('Error') })
        .success(function () { alert('OK') })
        return false;
    }); 

Now let's say you want to do it using $.Ajax and JSON:

// Post JSON data  add using System.Net;
    [HttpPost]
    public JsonResult JsonFullName(string fname, string lastname)
    {
        var data = "{ \"fname\" : \"" + fname  + " \" , \"lastname\" : \"" + lastname + "\" }";
//// you have to add the JsonRequestBehavior.AllowGet 
 //// otherwise it will throw an exception on run-time.
        return Json(data, JsonRequestBehavior.AllowGet);  
    }

Then, inside your view: add the event click on a an input of type button, or even a from submit: Just make sure your JSON data is well formatted.

  $("#jsonGetfullname").on("click", function () { 
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "@(Url.Action("JsonFullName", "Home"))",
            data: "{ \"fname\" : \"Mahmoud\" , \"lastname\" : \"Sayed\" }",
            dataType: "json",
            success: function (data) {
                var res = $.parseJSON(data);
                $("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
            }, 
            error: function (xhr, err) {
                alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
                alert("responseText: " + xhr.responseText);
            } 
        })
    });

How do I raise the same Exception with a custom message in Python?

This is the function I use to modify the exception message in Python 2.7 and 3.x while preserving the original traceback. It requires six

def reraise_modify(caught_exc, append_msg, prepend=False):
    """Append message to exception while preserving attributes.

    Preserves exception class, and exception traceback.

    Note:
        This function needs to be called inside an except because
        `sys.exc_info()` requires the exception context.

    Args:
        caught_exc(Exception): The caught exception object
        append_msg(str): The message to append to the caught exception
        prepend(bool): If True prepend the message to args instead of appending

    Returns:
        None

    Side Effects:
        Re-raises the exception with the preserved data / trace but
        modified message
    """
    ExceptClass = type(caught_exc)
    # Keep old traceback
    traceback = sys.exc_info()[2]
    if not caught_exc.args:
        # If no args, create our own tuple
        arg_list = [append_msg]
    else:
        # Take the last arg
        # If it is a string
        # append your message.
        # Otherwise append it to the
        # arg list(Not as pretty)
        arg_list = list(caught_exc.args[:-1])
        last_arg = caught_exc.args[-1]
        if isinstance(last_arg, str):
            if prepend:
                arg_list.append(append_msg + last_arg)
            else:
                arg_list.append(last_arg + append_msg)
        else:
            arg_list += [last_arg, append_msg]
    caught_exc.args = tuple(arg_list)
    six.reraise(ExceptClass,
                caught_exc,
                traceback)

Modifying local variable from inside lambda

I know that's an old question, but if you are comfortable with a workaround, considering the fact that the external variable should be final, you can simply do this:

final int[] ordinal = new int[1];
list.forEach(s -> {
    s.setOrdinal(ordinal[0]);
    ordinal[0]++;
});

Maybe not the most elegant, or even the most correct, but it will do.

How can I execute Python scripts using Anaconda's version of Python?

I know this is old, but none of the answers here is a real solution if you want to be able to double-click Python files and have the correct interpreter used without modifying your PYTHONPATH or PATH every time you want to use a different interpreter. Sure, from the command line, activate my-environment works, but OP specifically asked about double-clicking.

In this case, the correct thing to do is use the Python launcher for Windows. Then, all you have to do is add #! path\to\interpreter\python.exe to the top of your script. Unfortunately, although the launcher comes standard with Python 3.3+, it is not included with Anaconda (see Python & Windows: Where is the python launcher?), and the simplest thing to do is to install it separately from here.

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I ran into this before, as others said: just upgrade jetty plugin

if you are using maven

go to jetty plugin in pom.xml and update it to

<plugin>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>9.3.0.v20150612</version>
    <configuration>
        <scanIntervalSeconds>3</scanIntervalSeconds>
        <httpConnector>
            <port>${jetty.port}</port>
            <idleTimeout>60000</idleTimeout>
        </httpConnector>
        <stopKey>foo</stopKey>
        <stopPort>${jetty.stop.port}</stopPort>
    </configuration>
</plugin>

hope this help you

How to validate phone number in laravel 5.2?

Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
        return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
    });

Validator::replacer('phone', function($message, $attribute, $rule, $parameters) {
        return str_replace(':attribute',$attribute, ':attribute is invalid phone number');
    });

Usage

Insert this code in the app/Providers/AppServiceProvider.php to be booted up with your application.

This rule validates the telephone number against the given pattern above that i found after
long search it matches the most common mobile or telephone numbers in a lot of countries
This will allow you to use the phone validation rule anywhere in your application, so your form validation could be:

 'phone' => 'required|numeric|phone' 

How do I declare and initialize an array in Java?

Type[] variableName = new Type[capacity];

Type[] variableName = {comma-delimited values};



Type variableName[] = new Type[capacity]; 

Type variableName[] = {comma-delimited values};

is also valid, but I prefer the brackets after the type, because it's easier to see that the variable's type is actually an array.

how to run python files in windows command prompt?

You have to install Python and add it to PATH on Windows. After that you can try:

python `C:/pathToFolder/prog.py`

or go to the files directory and execute:

python prog.py

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

break x if ((int)strcmp(y, "hello")) == 0

On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!

Style disabled button with CSS

consider the following solution

.disable-button{ 
  pointer-events: none; 
  background-color: #edf1f2;
}

How to check task status in Celery?

Apart from above Programmatic approach Using Flower Task status can be easily seen.

Real-time monitoring using Celery Events. Flower is a web based tool for monitoring and administrating Celery clusters.

  1. Task progress and history
  2. Ability to show task details (arguments, start time, runtime, and more)
  3. Graphs and statistics

Official Document: Flower - Celery monitoring tool

Installation:

$ pip install flower

Usage:

http://localhost:5555

How can I show data using a modal when clicking a table row (using bootstrap)?

One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.

I am just going to show as a static example which you can accommodate in your real world.

On each of your <tr>'s add a data attribute for id (i.e. data-id) with the corresponding id value and specify a data-target, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal to make this a trigger for modal.

  <tr data-toggle="modal" data-id="1" data-target="#orderModal">
            <td>1</td>
            <td>24234234</td>
            <td>A</td>
  </tr>
  <tr data-toggle="modal" data-id="2" data-target="#orderModal">
            <td>2</td>
            <td>24234234</td>
            <td>A</td>
        </tr>
  <tr data-toggle="modal" data-id="3" data-target="#orderModal">
            <td>3</td>
            <td>24234234</td>
            <td>A</td>
  </tr>

And now in the javascript just set up the modal just once and event listen to its events so you can do your work.

$(function(){
    $('#orderModal').modal({
        keyboard: true,
        backdrop: "static",
        show:false,

    }).on('show', function(){ //subscribe to show method
          var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow  + '</b>'))
    });
});

Demo

Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.

Alternative ways here:

Demo2 or Demo3

How can I delete a service in Windows?

Use the SC command, like this (you need to be on a command prompt to execute the commands in this post):

SC STOP shortservicename
SC DELETE shortservicename

Note: You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". Note to PowerShell users: sc is aliased to set-content. So sc delete service will actually create a file called delete with the content service. To do this in Powershell, use sc.exe delete service instead


If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:

SC QUERY state= all >"C:\Service List.txt"

For a more concise list, execute this command:

SC QUERY state= all | FIND "_NAME"

The short service name will be listed just above the display name, like this:

SERVICE_NAME: MyService
DISPLAY_NAME: My Special Service

And thus to delete that service:

SC STOP MyService
SC DELETE MyService

How to add column to numpy array

I add a new column with ones to a matrix array in this way:

Z = append([[1 for _ in range(0,len(Z))]], Z.T,0).T

Maybe it is not that efficient?

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

Placeholder in UITextView

Sorry to add another answer, But I just pulled something like this off and this created the closest-to-UITextField kind of placeholder.

Hope this helps someone.

-(void)textViewDidChange:(UITextView *)textView{
    if(textView.textColor == [UIColor lightGrayColor]){
        textView.textColor  = [UIColor blackColor]; // look at the comment section in this answer
        textView.text       = [textView.text substringToIndex: 0];// look at the comment section in this answer
    }else if(textView.text.length == 0){
        textView.text       = @"This is some placeholder text.";
        textView.textColor  = [UIColor lightGrayColor];
        textView.selectedRange = NSMakeRange(0, 0);
    }
}

-(void)textViewDidChangeSelection:(UITextView *)textView{
    if(textView.textColor == [UIColor lightGrayColor] && (textView.selectedRange.location != 0 || textView.selectedRange.length != 0)){
        textView.selectedRange = NSMakeRange(0, 0);
    }
}

Changing the CommandTimeout in SQL Management studio

Changing Command Execute Timeout in Management Studio:

Click on Tools -> Options

Select Query Execution from tree on left side and enter command timeout in "Execute Timeout" control.

Changing Command Timeout in Server:

In the object browser tree right click on the server which give you timeout and select "Properties" from context menu.

Now in "Server Properties -....." dialog click on "Connections" page in "Select a Page" list (on left side). On the right side you will get property

Remote query timeout (in seconds, 0 = no timeout):
[up/down control]

you can set the value in up/down control.

Check if starting characters of a string are alphabetical in T-SQL

select * from my_table where my_field Like '[a-z][a-z]%'

How to solve a pair of nonlinear equations using Python?

An alternative to fsolve is root:

import numpy as np
from scipy.optimize import root    

def your_funcs(X):

    x, y = X
    # all RHS have to be 0
    f = [x + y**2 - 4,
         np.exp(x) + x * y - 3]

    return f

sol = root(your_funcs, [1.0, 1.0])
print(sol.x)

This will print

[0.62034452 1.83838393]

If you then check

print(your_funcs(sol.x))

you obtain

[4.4508396968012676e-11, -1.0512035686360832e-11]

confirming that the solution is correct.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

Inside of VBS you can access parameters with

Wscript.Arguments(0)
Wscript.Arguments(1)

and so on. The number of parameter:

Wscript.Arguments.Count

add item to dropdown list in html using javascript

Try this

<script type="text/javascript">
    function AddItem()
    {
        // Create an Option object       
        var opt = document.createElement("option");        

        // Assign text and value to Option object
        opt.text = "New Value";
        opt.value = "New Value";

        // Add an Option object to Drop Down List Box
        document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
    }
<script />

The Value will append to the drop down list.

How should you diagnose the error SEHException - External component has thrown an exception

Yes. This error is a structured exception that wasn't mapped into a .NET error. It's probably your DataGrid mapping throwing a native exception that was uncaught.

You can tell what exception is occurring by looking at the ExternalException.ErrorCode property. I'd check your stack trace, and if it's tied to the DevExpress grid, report the problem to them.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

I disagree with the accepted answer here by Óscar López. That answer is inaccurate!

It is NOT @JoinColumn which indicates that this entity is the owner of the relationship. Instead, it is the @ManyToOne annotation which does this (in his example).

The relationship annotations such as @ManyToOne, @OneToMany and @ManyToMany tell JPA/Hibernate to create a mapping. By default, this is done through a seperate Join Table.


@JoinColumn

The purpose of @JoinColumn is to create a join column if one does not already exist. If it does, then this annotation can be used to name the join column.


MappedBy

The purpose of the MappedBy parameter is to instruct JPA: Do NOT create another join table as the relationship is already being mapped by the opposite entity of this relationship.



Remember: MappedBy is a property of the relationship annotations whose purpose is to generate a mechanism to relate two entities which by default they do by creating a join table. MappedBy halts that process in one direction.

The entity not using MappedBy is said to be the owner of the relationship because the mechanics of the mapping are dictated within its class through the use of one of the three mapping annotations against the foreign key field. This not only specifies the nature of the mapping but also instructs the creation of a join table. Furthermore, the option to suppress the join table also exists by applying @JoinColumn annotation over the foreign key which keeps it inside the table of the owner entity instead.

So in summary: @JoinColumn either creates a new join column or renames an existing one; whilst the MappedBy parameter works collaboratively with the relationship annotations of the other (child) class in order to create a mapping either through a join table or by creating a foreign key column in the associated table of the owner entity.

To illustrate how MapppedBy works, consider the code below. If MappedBy parameter were to be deleted, then Hibernate would actually create TWO join tables! Why? Because there is a symmetry in many-to-many relationships and Hibernate has no rationale for selecting one direction over the other.

We therefore use MappedBy to tell Hibernate, we have chosen the other entity to dictate the mapping of the relationship between the two entities.

@Entity
public class Driver {
    @ManyToMany(mappedBy = "drivers")
    private List<Cars> cars;
}

@Entity
public class Cars {
    @ManyToMany
    private List<Drivers> drivers;
}

Adding @JoinColumn(name = "driverID") in the owner class (see below), will prevent the creation of a join table and instead, create a driverID foreign key column in the Cars table to construct a mapping:

@Entity
public class Driver {
    @ManyToMany(mappedBy = "drivers")
    private List<Cars> cars;
}

@Entity
public class Cars {
    @ManyToMany
    @JoinColumn(name = "driverID")
    private List<Drivers> drivers;
}

is there something like isset of php in javascript/jQuery?

If you want to check if a property exists: hasOwnProperty is the way to go

And since most objects are properties of some other object (eventually leading to the window object) this can work well for checking if values have been declared.

SQL Server - INNER JOIN WITH DISTINCT

Try this:

select distinct a.FirstName, a.LastName, v.District
from AddTbl a 
  inner join ValTbl v
  on a.LastName = v.LastName
order by a.FirstName;

Or this (it does the same, but the syntax is different):

select distinct a.FirstName, a.LastName, v.District
from AddTbl a, ValTbl v
where a.LastName = v.LastName
order by a.FirstName;

Dynamically load JS inside JS

To author my plugin I needed to load external scripts and styles inside a JS file, all of which were predefined. To achieve this, I did the following:

    this.loadRequiredFiles = function (callback) {
        var scripts = ['xx.js', 'yy.js'];
        var styles = ['zz.css'];
        var filesloaded = 0;
        var filestoload = scripts.length + styles.length;
        for (var i = 0; i < scripts.length; i++) {
            log('Loading script ' + scripts[i]);
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = scripts[i];
            script.onload = function () {
                log('Loaded script');
                log(this);
                filesloaded++;  // (This means increment, i.e. add one)
                finishLoad();
            };
            document.head.appendChild(script);
        }
        for (var i = 0; i < styles.length; i++) {
            log('Loading style ' + styles[i]);
            var style = document.createElement('link');
            style.rel = 'stylesheet';
            style.href = styles[i];
            style.type = 'text/css';
            style.onload = function () {
                log('Loaded style');
                log(this);
                filesloaded++;
                finishLoad();
            };
            document.head.appendChild(style);
        }
        function finishLoad() {
            if (filesloaded === filestoload) {
                callback();
            }
        }
    };

More of the script in context:

function myPlugin() {

    var opts = {
        verbose: false
    };                          ///< The options required to run this function
    var self = this;            ///< An alias to 'this' in case we're in jQuery                         ///< Constants required for this function to work

    this.getOptions = function() {
        return opts;
    };

    this.setOptions = function(options) {
        for (var x in options) {
            opts[x] = options[x];
        }
    };

    /**
     * @brief Load the required files for this plugin
     * @param {Function} callback A callback function to run when all files have been loaded
     */
    this.loadRequiredFiles = function (callback) {
        var scripts = ['xx.js', 'yy.js'];
        var styles = ['zz.css'];
        var filesloaded = 0;
        var filestoload = scripts.length + styles.length;
        for (var i = 0; i < scripts.length; i++) {
            log('Loading script ' + scripts[i]);
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = scripts[i];
            script.onload = function () {
                log('Loaded script');
                log(this);
                filesloaded++;
                finishLoad();
            };
            document.head.appendChild(script);
        }
        for (var i = 0; i < styles.length; i++) {
            log('Loading style ' + styles[i]);
            var style = document.createElement('link');
            style.rel = 'stylesheet';
            style.href = styles[i];
            style.type = 'text/css';
            style.onload = function () {
                log('Loaded style');
                log(this);
                filesloaded++;
                finishLoad();
            };
            document.head.appendChild(style);
        }
        function finishLoad() {
            if (filesloaded === filestoload) {
                callback();
            }
        }
    };

    /**
     * @brief Enable user-controlled logging within this function
     * @param {String} msg The message to log
     * @param {Boolean} force True to log message even if user has set logging to false
     */
    function log(msg, force) {
        if (opts.verbose || force) {
            console.log(msg);
        }
    }

    /**
     * @brief Initialise this function
     */
    this.init = function() {
        self.loadRequiredFiles(self.afterLoadRequiredFiles);
    };

    this.afterLoadRequiredFiles = function () {
        // Do stuff
    };

}

Android: TextView: Remove spacing and padding on top and bottom

Simple method worked:

setSingleLine();
setIncludeFontPadding(false);

If it not worked, then try to add this above that code:

setLineSpacing(0f,0f);
// and set padding and margin to 0

If you need multi line, maybe you'll need to calculate exactly the height of padding top and bottom via temp single line TextView (before and after remove padding) , then apply decrease height result with negative padding or some Ghost Layout with translate Y. Lol

CSS checkbox input styling

Although CSS does provide a way for you to do the style specific to the checkbox type or another type, there are going to be problems with browsers that do not support this.

I think your only option in this case is going to be to apply classes to your checkboxes.

just add the class="checkbox" to your checkboxes.

Then create that style in your css code.

One thing you could do is this:

main.css

input[type="checkbox"] { /* css code here */ }

ie.css

.checkbox{ /* css code here for ie */ }

Then use the IE specific css include:

<!--[if lt IE 7]>
   <link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->

You will still need to add the class for it to work in IE, and it will not work in other non-IE browsers that do not support IE. But it will make your website forward-thinking with css code and as IE gets support, you will be able to remove the ie specific css code and also the css classes from the checkboxes.

Differences between Emacs and Vim

VI is always available and will run on the most crippled, single user mode, broken graphics, no keymap, slow link machine - so it's worth knowing how to edit simple files in it just for sysadmin tasks.

Emacs is a complete user interface in an editor. The idea is that you fire up Emacs when you start the machine and never leave it. It's possible to have thousands of sessions present.

Whether learning the capabilities of Emacs are worth it compared to using a GUI editor/IDE and using something like python/awk/etc for extra tasks is up to you.

Error when trying vagrant up

With me I got an error when run vagrant up is (I used Macbook pro, Mac OS: 10.12.1):

An error occurred while downloading the remote file. The error message, if any, is reproduced below. Please fix this error and try again. Couldn't open file...

I tried to delete the Vagrantfile in my folder and run:

vagrant init hashicorp/precise64

then:

vagrant up

It can solved my problem. Hope this can help for someone who face the same problem.

String.Format not work in TypeScript

I am using TypeScript version 3.6 and I can do like this:

let templateStr = 'This is an {0} for {1} purpose';

const finalStr = templateStr.format('example', 'format'); // This is an example for format purpose

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

If this is related to docker, try stopping the erroneous container and starting a new container using docker run command from the same image.

finding the type of an element using jQuery

The following will return true if the element is an input:

$("#elementId").is("input") 

or you can use the following to get the name of the tag:

$("#elementId").get(0).tagName

When is layoutSubviews called?

Some of the points in BadPirate's answer are only partially true:

  1. For addSubView point

    addSubview causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target.

    It depends on the view's (target view) autoresize mask. If it has autoresize mask ON, layoutSubview will be called on each addSubview. If it has no autoresize mask then layoutSubview will be called only when the view's (target View) frame size changes.

    Example: if you created UIView programmatically (it has no autoresize mask by default), LayoutSubview will be called only when UIView frame changes not on every addSubview.

    It is through this technique that the performance of the application also increases.

  2. For the device rotation point

    Rotating a device only calls layoutSubview on the parent view (the responding viewController's primary view)

    This can be true only when your VC is in the VC hierarchy (root at window.rootViewController), well this is most common case. In iOS 5, if you create a VC, but it is not added into any another VC, then this VC would not get any noticed when device rotate. Therefore its view would not get noticed by calling layoutSubviews.

Best ways to teach a beginner to program?

once you've taught them how to program, they might want to learn how to develop software.. for that I think Greg Wilson's Software Carpentry course is great.. it also uses Python as the student's language.

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Encountered the same error in different use case.

Use Case: In chrome when tried to call Spring REST end point in angular.

enter image description here

Solution: Add @CrossOrigin("*") annotation on top of respective Controller Class.

enter image description here

Can Android do peer-to-peer ad-hoc networking?

I don't think it provides a multi-hop wireless packet routing environment. However you can try to integrate a simple routing mechanism. Just check out Wi-Share to get an idea how it can be done.

DynamoDB vs MongoDB NoSQL

I know this is old, but it still comes up when you search for the comparison. We were using Mongo, have moved almost entirely to Dynamo, which is our first choice now. Not because it has more features, it doesn't. Mongo has a better query language, you can index within a structure, there's lots of little things. The superiority of Dynamo is in what the OP stated in his comment: it's easy. You don't have to take care of any servers. When you start to set up a Mongo sharded solution, it gets complicated. You can go to one of the hosting companies, but that's not cheap either. With Dynamo, if you need more throughput, you just click a button. You can write scripts to scale automatically. When it's time to upgrade Dynamo, it's done for you. That is all a lot of precious stress and time not spent. If you don't have dedicated ops people, Dynamo is excellent.

So we are now going on Dynamo by default. Mongo maybe, if the data structure is complicated enough to warrant it, but then we'd probably go back to a SQL database. Dynamo is obtuse, you really need to think about how you're going to build it, and likely you'll use Redis in Elasticcache to make it work for complex stuff. But it sure is nice to not have to take care of it. You code. That's it.

Get the current first responder without using a private API

A common way of manipulating the first responder is to use nil targeted actions. This is a way of sending an arbitrary message to the responder chain (starting with the first responder), and continuing down the chain until someone responds to the message (has implemented a method matching the selector).

For the case of dismissing the keyboard, this is the most effective way that will work no matter which window or view is first responder:

[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];

This should be more effective than even [self.view.window endEditing:YES].

(Thanks to BigZaphod for reminding me of the concept)

Execute a shell script in current shell with sudo permission

What you are trying to do is impossible; your current shell is running under your regular user ID (i.e. without root the access sudo would give you), and there is no way to grant it root access. What sudo does is create a new *sub*process that runs as root. The subprocess could be just a regular program (e.g. sudo cp ... runs the cp program in a root process) or it could be a root subshell, but it cannot be the current shell.

(It's actually even more impossible than that, because the sudo command itself is executed as a subprocess of the current shell -- meaning that in a sense it's already too late for it to do anything in the "current shell", because that's not where it executes.)

What is java pojo class, java bean, normal class?

  1. Normal Class: A Java class

  2. Java Beans:

    • All properties private (use getters/setters)
    • A public no-argument constructor
    • Implements Serializable.
  3. Pojo: Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to

    • Extend prespecified classes
    • Implement prespecified interface
    • Contain prespecified annotations

How to download and save an image in Android

I have just came from solving this problem on and I would like to share the complete code that can download, save to the sdcard (and hide the filename) and retrieve the images and finally it checks if the image is already there. The url comes from the database so the filename can be uniquely easily using id.

first download images

   private class GetImages extends AsyncTask<Object, Object, Object> {
    private String requestUrl, imagename_;
    private ImageView view;
    private Bitmap bitmap ; 
      private FileOutputStream fos;
    private GetImages(String requestUrl, ImageView view, String _imagename_) {
        this.requestUrl = requestUrl;
        this.view = view;
        this.imagename_ = _imagename_ ;
    }

    @Override
    protected Object doInBackground(Object... objects) {
        try {
            URL url = new URL(requestUrl);
            URLConnection conn = url.openConnection();
            bitmap = BitmapFactory.decodeStream(conn.getInputStream());
        } catch (Exception ex) {
        }
        return null;
    }

    @Override
    protected void onPostExecute(Object o) { 
        if(!ImageStorage.checkifImageExists(imagename_))
        { 
                view.setImageBitmap(bitmap);
                ImageStorage.saveToSdCard(bitmap, imagename_); 
            }  
        }  
   }

Then create a class for saving and retrieving the files

  public class ImageStorage {


public static String saveToSdCard(Bitmap bitmap, String filename) {

    String stored = null;

    File sdcard = Environment.getExternalStorageDirectory() ; 

    File folder = new File(sdcard.getAbsoluteFile(), ".your_specific_directory");//the dot makes this directory hidden to the user
    folder.mkdir(); 
    File file = new File(folder.getAbsoluteFile(), filename + ".jpg") ;
    if (file.exists())
        return stored ;

    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
        stored = "success";
    } catch (Exception e) {
        e.printStackTrace();
    }
     return stored;
   }

public static File getImage(String imagename) {

        File mediaImage = null;
        try {
            String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root);
            if (!myDir.exists())
                return null;

            mediaImage = new File(myDir.getPath() + "/.your_specific_directory/"+imagename);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return mediaImage;
    }
public static boolean checkifImageExists(String imagename)
{
    Bitmap b = null ;
    File file = ImageStorage.getImage("/"+imagename+".jpg");
    String path = file.getAbsolutePath();

    if (path != null)
        b = BitmapFactory.decodeFile(path); 

    if(b == null ||  b.equals(""))
    {
        return false ;
    }
    return true ;
}
  }

Then To access the images first check if it is already there if not then download

          if(ImageStorage.checkifImageExists(imagename))
            {
                File file = ImageStorage.getImage("/"+imagename+".jpg"); 
                String path = file.getAbsolutePath(); 
                if (path != null){
                    b = BitmapFactory.decodeFile(path);
                    imageView.setImageBitmap(b);
                }  
            } else { 
                new GetImages(imgurl, imageView, imagename).execute() ; 
            }

How to Deep clone in javascript

The Underscore.js contrib library library has a function called snapshot that deep clones an object

snippet from the source:

snapshot: function(obj) {
  if(obj == null || typeof(obj) != 'object') {
    return obj;
  }

  var temp = new obj.constructor();

  for(var key in obj) {
    if (obj.hasOwnProperty(key)) {
      temp[key] = _.snapshot(obj[key]);
    }
  }

  return temp;
}

once the library is linked to your project, invoke the function simply using

_.snapshot(object);

Error in plot.window(...) : need finite 'xlim' values

The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA) values. Here's an example:

> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf

In your example this means that in your line plot(costs,pseudor2,type="l"), costs is completely NA. You have to figure out why this is, but that's the explanation of your error.


From comments:

Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.

stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x))

How can I convert a VBScript to an executable (EXE) file?

There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is not a compiled language. The process of converting source code into native executable code is called "compilation", and it's not supported by scripting languages like VBScript.

Certainly you can add your script to a self-extracting archive using something like WinZip, but all that will do is compress it. It's doubtful that the file size will shrink noticeably, and since it's a plain-text file to begin with, it's really not necessary to compress it at all. The only purpose of a self-extracting archive is that decompression software (like WinZip) is not required on the end user's computer to be able to extract or "decompress" the file. If it isn't compressed in the first place, this is a moot point.

Alternatively, as you mentioned, there are ways to wrap VBScript code files in a standalone executable file, but these are just wrappers that automatically execute the script (in its current, uncompiled state) when the user double-clicks on the .exe file. I suppose that can have its benefits, but it doesn't sound like what you're looking for.

In order to truly convert your VBScript into an executable file, you're going to have to rewrite it in another language that can be compiled. Visual Basic 6 (the latest version of VB, before the .NET Framework was introduced) is extremely similar in syntax to VBScript, but does support compiling to native code. If you move your VBScript code to VB 6, you can compile it into a native executable. Running the .exe file will require that the user has the VB 6 Run-time libraries installed, but they come built into most versions of Windows that are found now in the wild.

Alternatively, you could go ahead and make the jump to Visual Basic .NET, which remains somewhat similar in syntax to VB 6 and VBScript (although it won't be anywhere near a cut-and-paste migration). VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. You mentioned going this route in your question (porting your current script in to VB Express 2008, which uses VB.NET), but that you were getting a lot of errors. That's what I mean about it being far from a cut-and-paste migration. There are some huge differences between VB 6/VBScript and VB.NET, despite some superficial syntactical similarities. If you want help migrating over your VBScript, you could post a question here on Stack Overflow. Ultimately, this is probably the best way to do what you want, but I can't promise you that it will be simple.

Run command on the Ansible host

From the Ansible documentation:

Delegation This isn’t actually rolling update specific but comes up frequently in those cases.

If you want to perform a task on one host with reference to other hosts, use the ‘delegate_to’ keyword on a task. This is ideal for placing nodes in a load balanced pool, or removing them. It is also very useful for controlling outage windows. Be aware that it does not make sense to delegate all tasks, debug, add_host, include, etc always get executed on the controller. Using this with the ‘serial’ keyword to control the number of hosts executing at one time is also a good idea:

---

- hosts: webservers
  serial: 5

  tasks:

  - name: take out of load balancer pool
    command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
    delegate_to: 127.0.0.1

  - name: actual steps would go here
    yum:
      name: acme-web-stack
      state: latest

  - name: add back to load balancer pool
    command: /usr/bin/add_back_to_pool {{ inventory_hostname }}
    delegate_to: 127.0.0.1

These commands will run on 127.0.0.1, which is the machine running Ansible. There is also a shorthand syntax that you can use on a per-task basis: ‘local_action’. Here is the same playbook as above, but using the shorthand syntax for delegating to 127.0.0.1:

---

# ...

  tasks:

  - name: take out of load balancer pool
    local_action: command /usr/bin/take_out_of_pool {{ inventory_hostname }}

# ...

  - name: add back to load balancer pool
    local_action: command /usr/bin/add_back_to_pool {{ inventory_hostname }}

A common pattern is to use a local action to call ‘rsync’ to recursively copy files to the managed servers. Here is an example:

---
# ...
  tasks:

  - name: recursively copy files from management server to target
    local_action: command rsync -a /path/to/files {{ inventory_hostname }}:/path/to/target/

Note that you must have passphrase-less SSH keys or an ssh-agent configured for this to work, otherwise rsync will need to ask for a passphrase.

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

Looping over arrays, printing both index and value

users=("kamal" "jamal" "rahim" "karim" "sadia")
index=()
t=-1

for i in ${users[@]}; do
  t=$(( t + 1 ))
  if [ $t -eq 0 ]; then
    for j in ${!users[@]}; do
      index[$j]=$j
    done
  fi
  echo "${index[$t]} is $i"
done

Javascript | Set all values of an array

Found this while working with Epicycles - clearly works - where 'p' is invisible to my eyes.

/** Convert a set of picture points to a set of Cartesian coordinates */
function toCartesian(points, scale) {
  const x_max = Math.max(...points.map(p=>p[0])),
  y_max = Math.max(...points.map(p=>p[1])),
  x_min = Math.min(...points.map(p=>p[0])),
  y_min = Math.min(...points.map(p=>p[1])),
  signed_x_max = Math.floor((x_max - x_min + 1) / 2),
  signed_y_max = Math.floor((y_max - y_min + 1) / 2);

  return points.map(p=>
  [ -scale * (signed_x_max - p[0] + x_min),
  scale * (signed_y_max - p[1] + y_min) ] );
}

Android ACTION_IMAGE_CAPTURE Intent

You can use this code

private Intent getCameraIntent() {

    PackageManager packageManager = mContext.getPackageManager();
    List<ApplicationInfo> list = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
    Intent main = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    List<ResolveInfo> launchables = packageManager.queryIntentActivities(main, 0);
    if (launchables.size() == 1)
        return packageManager.getLaunchIntentForPackage(launchables.get(0).activityInfo.packageName);
    else
        for (int n = 0; n < list.size(); n++) {
            if ((list.get(n).flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
                Log.d("TAG", "Installed Applications  : " + list.get(n).loadLabel(packageManager).toString());
                Log.d("TAG", "package name  : " + list.get(n).packageName);
                String defaultCameraPackage = list.get(n).packageName;


                if (launchables.size() > 1)
                    for (int i = 0; i < launchables.size(); i++) {
                        if (defaultCameraPackage.equals(launchables.get(i).activityInfo.packageName)) {
                            return packageManager.getLaunchIntentForPackage(defaultCameraPackage);
                        }
                    }
            }
        }
    return null;
}

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

spring data jpa @query and pageable

I had the same issue - without Pageable method works fine.
When added as method parameter - doesn't work.

After playing with DB console and native query support came up to decision that method works like it should. However, only for upper case letters.
Logic of my application was that all names of entity starts from upper case letters.

Playing a little bit with it. And discover that IgnoreCase at method name do the "magic" and here is working solution:

public interface EmployeeRepository 
                            extends PagingAndSortingRepository<Employee, Integer> {

    Page<Employee> findAllByNameIgnoreCaseStartsWith(String name, Pageable pageable);

}

Where entity looks like:

@Data
@Entity
@Table(name = "tblEmployees")
public class Employee {

    @Id
    @Column(name = "empID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotEmpty
    @Size(min = 2, max = 20)
    @Column(name = "empName", length = 25)
    private String name;

    @Column(name = "empActive")
    private Boolean active;

    @ManyToOne
    @JoinColumn(name = "emp_dpID")
    private Department department;
}

Convert row to column header for Pandas DataFrame,

This works (pandas v'0.19.2'):

df.rename(columns=df.iloc[0])

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

How do I make a C++ macro behave like a function?

Create a block using

 #define MACRO(...) do { ... } while(false)

Do not add a ; after the while(false)

Permutation of array

If you're using C++, you can use std::next_permutation from the <algorithm> header file:

int a[] = {3,4,6,2,1};
int size = sizeof(a)/sizeof(a[0]);
std::sort(a, a+size);
do {
  // print a's elements
} while(std::next_permutation(a, a+size));

Expansion of variables inside single quotes in a command in Bash

EDIT: (As per the comments in question:)

I've been looking into this since then. I was lucky enough that I had repo laying around. Still it's not clear to me whether you need to enclose your commands between single quotes by force. I looked into the repo syntax and I don't think you need to. You could used double quotes around your command, and then use whatever single and double quotes you need inside provided you escape double ones.

Remove by _id in MongoDB console

I've just bumped into this myself and this variation worked for me:

db.foo.remove({**_id**: new ObjectId("4f872685a64eed5a980ca536")})

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

Check if input is number or letter javascript

You could use the isNaN Function. It returns true if the data is not a number. That would be something like that:

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    if (isNaN(x)) // this is the code I need to change
    {
        alert("Must input numbers");
        return false;
    }
}

Note: isNan considers 10.2 as a valid number.

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

See the image for reference :- (Soruce :- Android Studio-Image Assets option and Android Office Site )

enter image description here

Java Equivalent of C# async/await?

No, there isn't any equivalent of async/await in Java - or even in C# before v5.

It's a fairly complex language feature to build a state machine behind the scenes.

There's relatively little language support for asynchrony/concurrency in Java, but the java.util.concurrent package contains a lot of useful classes around this. (Not quite equivalent to the Task Parallel Library, but the closest approximation to it.)

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

Windows recursive grep command-line

findstr can do recursive searches (/S) and supports some variant of regex syntax (/R).

C:\>findstr /?
Searches for strings in files.

FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
        [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
        strings [[drive:][path]filename[ ...]]

  /B         Matches pattern if at the beginning of a line.
  /E         Matches pattern if at the end of a line.
  /L         Uses search strings literally.
  /R         Uses search strings as regular expressions.
  /S         Searches for matching files in the current directory and all
             subdirectories.
  /I         Specifies that the search is not to be case-sensitive.
  /X         Prints lines that match exactly.
  /V         Prints only lines that do not contain a match.
  /N         Prints the line number before each line that matches.
  /M         Prints only the filename if a file contains a match.
  /O         Prints character offset before each matching line.
  /P         Skip files with non-printable characters.
  /OFF[LINE] Do not skip files with offline attribute set.
  /A:attr    Specifies color attribute with two hex digits. See "color /?"
  /F:file    Reads file list from the specified file(/ stands for console).
  /C:string  Uses specified string as a literal search string.
  /G:file    Gets search strings from the specified file(/ stands for console).
  /D:dir     Search a semicolon delimited list of directories
  strings    Text to be searched for.
  [drive:][path]filename
             Specifies a file or files to search.

Use spaces to separate multiple search strings unless the argument is prefixed
with /C.  For example, 'FINDSTR "hello there" x.y' searches for "hello" or
"there" in file x.y.  'FINDSTR /C:"hello there" x.y' searches for
"hello there" in file x.y.

Regular expression quick reference:
  .        Wildcard: any character
  *        Repeat: zero or more occurrences of previous character or class
  ^        Line position: beginning of line
  $        Line position: end of line
  [class]  Character class: any one character in set
  [^class] Inverse class: any one character not in set
  [x-y]    Range: any characters within the specified range
  \x       Escape: literal use of metacharacter x
  \<xyz    Word position: beginning of word
  xyz\>    Word position: end of word

For full information on FINDSTR regular expressions refer to the online Command
Reference.

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

go to config/environments/test.rb

Rails.application.routes.default_url_options[:host] = 'localhost:3000'