Programs & Examples On #Introspection

A capability of some object-oriented programming languages to determine the type of an object at runtime.

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

 

How do I look inside a Python object?

You can list the attributes of a object with dir() in the shell:

>>> dir(object())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Of course, there is also the inspect module: http://docs.python.org/library/inspect.html#module-inspect

Using isKindOfClass with Swift

The proper Swift operator is is:

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

Of course, if you also need to assign the view to a new constant, then the if let ... as? ... syntax is your boy, as Kevin mentioned. But if you don't need the value and only need to check the type, then you should use the is operator.

Get all object attributes in Python?

Use the built-in function dir().

How to get method parameter names?

Here is something I think will work for what you want, using a decorator.

class LogWrappedFunction(object):
    def __init__(self, function):
        self.function = function

    def logAndCall(self, *arguments, **namedArguments):
        print "Calling %s with arguments %s and named arguments %s" %\
                      (self.function.func_name, arguments, namedArguments)
        self.function.__call__(*arguments, **namedArguments)

def logwrap(function):
    return LogWrappedFunction(function).logAndCall

@logwrap
def doSomething(spam, eggs, foo, bar):
    print "Doing something totally awesome with %s and %s." % (spam, eggs)


doSomething("beans","rice", foo="wiggity", bar="wack")

Run it, it will yield the following output:

C:\scripts>python decoratorExample.py
Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
 'wiggity', 'bar': 'wack'}
Doing something totally awesome with beans and rice.

How can you print a variable name in python?

If you are trying to do this, it means you are doing something wrong. Consider using a dict instead.

def show_val(vals, name):
    print "Name:", name, "val:", vals[name]

vals = {'a': 1, 'b': 2}
show_val(vals, 'b')

Output:

Name: b val: 2

How to get the name of the current method from code

I think the best way to get the full name is:

 this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;

or try this

string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name);   

Finding what methods a Python object has

The problem with all methods indicated here is that you can't be sure that a method doesn't exist.

In Python you can intercept the dot calling through __getattr__ and __getattribute__, making it possible to create method "at runtime"

Example:

class MoreMethod(object):
    def some_method(self, x):
        return x
    def __getattr__(self, *args):
        return lambda x: x*2

If you execute it, you can call non-existing methods in the object dictionary...

>>> o = MoreMethod()
>>> o.some_method(5)
5
>>> dir(o)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method']
>>> o.i_dont_care_of_the_name(5)
10

And it's why you use the Easier to ask for forgiveness than permission paradigms in Python.

Getting the class name of an instance?

In Python 2,

type(instance).__name__ != instance.__class__.__name__
# if class A is defined like
class A():
   ...

type(instance) == instance.__class__
# if class A is defined like
class A(object):
  ...

Example:

>>> class aclass(object):
...   pass
...
>>> a = aclass()
>>> type(a)
<class '__main__.aclass'>
>>> a.__class__
<class '__main__.aclass'>
>>>
>>> type(a).__name__
'aclass'
>>>
>>> a.__class__.__name__
'aclass'
>>>


>>> class bclass():
...   pass
...
>>> b = bclass()
>>>
>>> type(b)
<type 'instance'>
>>> b.__class__
<class __main__.bclass at 0xb765047c>
>>> type(b).__name__
'instance'
>>>
>>> b.__class__.__name__
'bclass'
>>>

Is there a built-in function to print all the current properties and values of an object?

You can use the "dir()" function to do this.

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder
, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>

Another useful feature is help.

>>> help(sys)
Help on built-in module sys:

NAME
    sys

FILE
    (built-in)

MODULE DOCS
    http://www.python.org/doc/current/lib/module-sys.html

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known

How do I access properties of a javascript object if I don't know the names?

Old versions of JavaScript (< ES5) require using a for..in loop:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    // do something with key
  }
}

ES5 introduces Object.keys and Array#forEach which makes this a little easier:

var data = { foo: 'bar', baz: 'quux' };

Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
  // do something with data[key]
});

ES2017 introduces Object.values and Object.entries.

Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]

Determine function name from within that function (without using traceback)

I recently tried to use the above answers to access the docstring of a function from the context of that function but as the above questions were only returning the name string it did not work.

Fortunately I found a simple solution. If like me, you want to refer to the function rather than simply get the string representing the name you can apply eval() to the string of the function name.

import sys
def foo():
    """foo docstring"""
    print(eval(sys._getframe().f_code.co_name).__doc__)

How to get the caller's method name in the called method?

Bit of an amalgamation of the stuff above. But here's my crack at it.

def print_caller_name(stack_size=3):
    def wrapper(fn):
        def inner(*args, **kwargs):
            import inspect
            stack = inspect.stack()

            modules = [(index, inspect.getmodule(stack[index][0]))
                       for index in reversed(range(1, stack_size))]
            module_name_lengths = [len(module.__name__)
                                   for _, module in modules]

            s = '{index:>5} : {module:^%i} : {name}' % (max(module_name_lengths) + 4)
            callers = ['',
                       s.format(index='level', module='module', name='name'),
                       '-' * 50]

            for index, module in modules:
                callers.append(s.format(index=index,
                                        module=module.__name__,
                                        name=stack[index][3]))

            callers.append(s.format(index=0,
                                    module=fn.__module__,
                                    name=fn.__name__))
            callers.append('')
            print('\n'.join(callers))

            fn(*args, **kwargs)
        return inner
    return wrapper

Use:

@print_caller_name(4)
def foo():
    return 'foobar'

def bar():
    return foo()

def baz():
    return bar()

def fizz():
    return baz()

fizz()

output is

level :             module             : name
--------------------------------------------------
    3 :              None              : fizz
    2 :              None              : baz
    1 :              None              : bar
    0 :            __main__            : foo

Ruby: kind_of? vs. instance_of? vs. is_a?

I also wouldn't call two many (is_a? and kind_of? are aliases of the same method), but if you want to see more possibilities, turn your attention to #class method:

A = Class.new
B = Class.new A

a, b = A.new, B.new
b.class < A # true - means that b.class is a subclass of A
a.class < B # false - means that a.class is not a subclass of A
# Another possibility: Use #ancestors
b.class.ancestors.include? A # true - means that b.class has A among its ancestors
a.class.ancestors.include? B # false - means that B is not an ancestor of a.class

Get model's fields in Django

I know this post is pretty old, but I just cared to tell anyone who is searching for the same thing that there is a public and official API to do this: get_fields() and get_field()

Usage:

fields = model._meta.get_fields()
my_field = model._meta.get_field('my_field')

https://docs.djangoproject.com/en/1.8/ref/models/meta/

JavaScript: Get image dimensions

if you have image file from your input form. you can use like this

let images = new Image();
images.onload = () => {
 console.log("Image Size", images.width, images.height)
}
images.onerror = () => result(true);

let fileReader = new FileReader();
fileReader.onload = () => images.src = fileReader.result;
fileReader.onerror = () => result(false);
if (fileTarget) {
   fileReader.readAsDataURL(fileTarget);
}

How to Sort Date in descending order From Arraylist Date in android?

Just add like this in case 1: like this

 case 0:
     list = DBAdpter.requestUserData(assosiatetoken);
     Collections.sort(list, byDate);
     for (int i = 0; i < list.size(); i++) {
         if (list.get(i).lastModifiedDate != null) {
             lv.setAdapter(new MyListAdapter(
                     getApplicationContext(), list));
         }
     }
     break;

and put this method at end of the your class

static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");

    public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = sdf.parse(ord1.lastModifiedDate);
            d2 = sdf.parse(ord2.lastModifiedDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return (d1.getTime() > d2.getTime() ? -1 : 1);     //descending
    //  return (d1.getTime() > d2.getTime() ? 1 : -1);     //ascending
    }
};

.autocomplete is not a function Error

This is embarrassing but it held me up for a while so I figured I would post it here.

I did not have jQuery UI installed, only classic jQuery, which does not include autocomplete (apparently). Adding the following tags enabled autocomplete via jQuery UI.

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

and

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

Of note, the HTML value autocomplete="off" for either the form or form block will prevent the brower from performing the method .autocomplete(), but will not block the jQuery UI function.

Can you have multiline HTML5 placeholder text in a <textarea>?

There is actual a hack which makes it possible to add multiline placeholders in Webkit browsers, Chrome used to work but in more recent versions they removed it:


First add the first line of your placeholder to the html5 as usual

<textarea id="text1" placeholder="Line 1" rows="10"></textarea>

then add the rest of the line by css:

#text1::-webkit-input-placeholder::after {
    display:block;
    content:"Line 2\A Line 3";
}

If you want to keep your lines at one place you can try the following. The downside of this is that other browsers than chrome, safari, webkit-etc. don't even show the first line:

<textarea id="text2" placeholder="." rows="10"></textarea>?

then add the rest of the line by css:

#text2::-webkit-input-placeholder{
    color:transparent;
}

#text2::-webkit-input-placeholder::before {
    color:#666;
    content:"Line 1\A Line 2\A Line 3\A";
}

Demo Fiddle

It would be very great, if s.o. could get a similar demo working on Firefox.

How to Execute SQL Server Stored Procedure in SQL Developer?

You need to do this:

    exec procName 
    @parameter_1_Name = 'parameter_1_Value', 
    @parameter_2_name = 'parameter_2_value',
    @parameter_z_name = 'parameter_z_value'

What is an .inc and why use it?

Note that You can configure Apache so that all files With .inc extension are forbidden to be retrieved by visiting URL directly.

see link:https://serverfault.com/questions/22577/how-to-deny-the-web-access-to-some-files

How do I loop through rows with a data reader in C#?

int count = reader.FieldCount;
while(reader.Read()) {
    for(int i = 0 ; i < count ; i++) {
        Console.WriteLine(reader.GetValue(i));
    }
}

Note; if you have multiple grids, then:

do {
    int count = reader.FieldCount;
    while(reader.Read()) {
        for(int i = 0 ; i < count ; i++) {
            Console.WriteLine(reader.GetValue(i));
        }
    }
} while (reader.NextResult())

UIImage resize (Scale proportion)

This change worked for me:

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

Method to Add new or update existing item in Dictionary

Could there be any problem if i replace Method-1 by Method-2?

No, just use map[key] = value. The two options are equivalent.


Regarding Dictionary<> vs. Hashtable: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, add: false); and the add parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

So you have to exclude conflict dependencies. Try this:

<exclusions>
  <exclusion> 
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
  </exclusion>
  <exclusion> 
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
  </exclusion>
</exclusions> 

This solved same problem with slf4j and Dozer.

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

What's the difference between a mock & stub?

Foreword

There are several definitions of objects, that are not real. The general term is test double. This term encompasses: dummy, fake, stub, mock.

Reference

According to Martin Fowler's article:

  • Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
  • Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
  • Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
  • Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

Style

Mocks vs Stubs = Behavioral testing vs State testing

Principle

According to the principle of Test only one thing per test, there may be several stubs in one test, but generally there is only one mock.

Lifecycle

Test lifecycle with stubs:

  1. Setup - Prepare object that is being tested and its stubs collaborators.
  2. Exercise - Test the functionality.
  3. Verify state - Use asserts to check object's state.
  4. Teardown - Clean up resources.

Test lifecycle with mocks:

  1. Setup data - Prepare object that is being tested.
  2. Setup expectations - Prepare expectations in mock that is being used by primary object.
  3. Exercise - Test the functionality.
  4. Verify expectations - Verify that correct methods has been invoked in mock.
  5. Verify state - Use asserts to check object's state.
  6. Teardown - Clean up resources.

Summary

Both mocks and stubs testing give an answer for the question: What is the result?

Testing with mocks are also interested in: How the result has been achieved?

What's the fastest way to do a bulk insert into Postgres?

UNNEST function with arrays can be used along with multirow VALUES syntax. I'm think that this method is slower than using COPY but it is useful to me in work with psycopg and python (python list passed to cursor.execute becomes pg ARRAY):

INSERT INTO tablename (fieldname1, fieldname2, fieldname3)
VALUES (
    UNNEST(ARRAY[1, 2, 3]), 
    UNNEST(ARRAY[100, 200, 300]), 
    UNNEST(ARRAY['a', 'b', 'c'])
);

without VALUES using subselect with additional existance check:

INSERT INTO tablename (fieldname1, fieldname2, fieldname3)
SELECT * FROM (
    SELECT UNNEST(ARRAY[1, 2, 3]), 
           UNNEST(ARRAY[100, 200, 300]), 
           UNNEST(ARRAY['a', 'b', 'c'])
) AS temptable
WHERE NOT EXISTS (
    SELECT 1 FROM tablename tt
    WHERE tt.fieldname1=temptable.fieldname1
);

the same syntax to bulk updates:

UPDATE tablename
SET fieldname1=temptable.data
FROM (
    SELECT UNNEST(ARRAY[1,2]) AS id,
           UNNEST(ARRAY['a', 'b']) AS data
) AS temptable
WHERE tablename.id=temptable.id;

case-insensitive matching in xpath?

XPath 2 has a lower-case (and upper-case) string function. That's not quite the same as case-insensitive, but hopefully it will be close enough:

//CD[lower-case(@title)='empire burlesque']

If you are using XPath 1, there is a hack using translate.

How to print Two-Dimensional Array like table

ALL OF YOU PLEASE LOOT AT IT I Am amazed it need little IQ just get length by arr[0].length and problem solved

   for (int i = 0; i < test.length; i++) {
        for (int j = 0; j < test[0].length; j++) {

        System.out.print(test[i][j]);
    }
        System.out.println();
    }

How to print a int64_t type in C

With C99 the %j length modifier can also be used with the printf family of functions to print values of type int64_t and uint64_t:

#include <stdio.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
    int64_t  a = 1LL << 63;
    uint64_t b = 1ULL << 63;

    printf("a=%jd (0x%jx)\n", a, a);
    printf("b=%ju (0x%jx)\n", b, b);

    return 0;
}

Compiling this code with gcc -Wall -pedantic -std=c99 produces no warnings, and the program prints the expected output:

a=-9223372036854775808 (0x8000000000000000)
b=9223372036854775808 (0x8000000000000000)

This is according to printf(3) on my Linux system (the man page specifically says that j is used to indicate a conversion to an intmax_t or uintmax_t; in my stdint.h, both int64_t and intmax_t are typedef'd in exactly the same way, and similarly for uint64_t). I'm not sure if this is perfectly portable to other systems.

Best way to store date/time in mongodb

The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.

> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }

The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

If you need to, you can easily convert Date objects to and from Unix timestamps1), using the getTime() method and Date(milliseconds) constructor, respectively.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

Removing double quotes from variables in batch file creates problems with CMD environment

All the answers are complete. But Wanted to add one thing,

set FirstName=%~1

set LastName=%~2

This line should have worked, you needed a small change.

set "FirstName=%~1"

set "LastName=%~2"

Include the complete assignment within quotes. It will remove quotes without an issue. This is a prefered way of assignment which fixes unwanted issues with quotes in arguments.

How to get terminal's Character Encoding

To my knowledge, no.

Circumstantial indications from $LC_CTYPE, locale and such might seem alluring, but these are completely separated from the encoding the terminal application (actually an emulator) happens to be using when displaying characters on the screen.

They only way to detect encoding for sure is to output something only present in the encoding, e.g. ä, take a screenshot, analyze that image and check if the output character is correct.

So no, it's not possible, sadly.

How to resolve cURL Error (7): couldn't connect to host?

In PHP, If your network under proxy. You should set the proxy URL and port

curl_setopt($ch, CURLOPT_PROXY, "http://url.com"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number

This is solves my problem

How to implement a binary tree?

This implementation supports insert, find and delete operations without destroy the structure of the tree. This is not a banlanced tree.

# Class for construct the nodes of the tree. (Subtrees)
class Node:
def __init__(self, key, parent_node = None):
    self.left = None
    self.right = None
    self.key = key
    if parent_node == None:
        self.parent = self
    else:
        self.parent = parent_node

# Class with the  structure of the tree. 
# This Tree is not balanced.
class Tree:
def __init__(self):
    self.root = None

# Insert a single element
def insert(self, x):
    if(self.root == None):
        self.root = Node(x)
    else:
        self._insert(x, self.root)

def _insert(self, x, node):
    if(x < node.key):
        if(node.left == None):
            node.left = Node(x, node)
        else:
            self._insert(x, node.left)
    else:
        if(node.right == None):
            node.right = Node(x, node)
        else:
            self._insert(x, node.right)

# Given a element, return a node in the tree with key x. 
def find(self, x):
    if(self.root == None):
        return None
    else:
        return self._find(x, self.root)
def _find(self, x, node):
    if(x == node.key):
        return node
    elif(x < node.key):
        if(node.left == None):
            return None
        else:
            return self._find(x, node.left)
    elif(x > node.key):
        if(node.right == None):
            return None
        else:
            return self._find(x, node.right)

# Given a node, return the node in the tree with the next largest element.
def next(self, node):
    if node.right != None:
        return self._left_descendant(node.right)
    else:
        return self._right_ancestor(node)

def _left_descendant(self, node):
    if node.left == None:
        return node
    else:
        return self._left_descendant(node.left)

def _right_ancestor(self, node):
    if node.key <= node.parent.key:
        return node.parent
    else:
        return self._right_ancestor(node.parent)

# Delete an element of the tree
def delete(self, x):
    node = self.find(x)
    if node == None:
        print(x, "isn't in the tree")
    else:
        if node.right == None:
            if node.left == None:
                if node.key < node.parent.key:
                    node.parent.left = None
                    del node # Clean garbage
                else:
                    node.parent.right = None
                    del Node # Clean garbage
            else:
                node.key = node.left.key
                node.left = None
        else:
            x = self.next(node)
            node.key = x.key
            x = None


# tests
t = Tree()
t.insert(5)
t.insert(8)
t.insert(3)
t.insert(4)
t.insert(6)
t.insert(2)

t.delete(8)
t.delete(5)

t.insert(9)
t.insert(1)

t.delete(2)
t.delete(100)

# Remember: Find method return the node object. 
# To return a number use t.find(nº).key
# But it will cause an error if the number is not in the tree.
print(t.find(5)) 
print(t.find(8))
print(t.find(4))
print(t.find(6))
print(t.find(9))

Gradient text color

The way this effect works is very simple. The element is given a background which is the gradient. It goes from one color to another depending on the colors and color-stop percentages given for it.

For example, in rainbow text sample (note that I've converted the gradient into the standard syntax):

  • The gradient starts at color #f22 at 0% (that is the left edge of the element). First color is always assumed to start at 0% even though the percentage is not mentioned explicitly.
  • Between 0% to 14.25%, the color changes from #f22 to #f2f gradually. The percenatge is set at 14.25 because there are seven color changes and we are looking for equal splits.
  • At 14.25% (of the container's size), the color will exactly be #f2f as per the gradient specified.
  • Similarly the colors change from one to another depending on the bands specified by color stop percentages. Each band should be a step of 14.25%.

So, we end up getting a gradient like in the below snippet. Now this alone would mean the background applies to the entire element and not just the text.

_x000D_
_x000D_
.rainbow {_x000D_
  background-image: linear-gradient(to right, #f22, #f2f 14.25%, #22f 28.5%, #2ff 42.75%, #2f2 57%, #2f2 71.25%, #ff2 85.5%, #f22);_x000D_
  color: transparent;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>
_x000D_
_x000D_
_x000D_

Since, the gradient needs to be applied only to the text and not to the element on the whole, we need to instruct the browser to clip the background from the areas outside the text. This is done by setting background-clip: text.

(Note that the background-clip: text is an experimental property and is not supported widely.)


Now if you want the text to have a simple 3 color gradient (that is, say from red - orange - brown), we just need to change the linear-gradient specification as follows:

  • First parameter is the direction of the gradient. If the color should be red at left side and brown at the right side then use the direction as to right. If it should be red at right and brown at left then give the direction as to left.
  • Next step is to define the colors of the gradient. Since our gradient should start as red on the left side, just specify red as the first color (percentage is assumed to be 0%).
  • Now, since we have two color changes (red - orange and orange - brown), the percentages must be set as 100 / 2 for equal splits. If equal splits are not required, we can assign the percentages as we wish.
  • So at 50% the color should be orange and then the final color would be brown. The position of the final color is always assumed to be at 100%.

Thus the gradient's specification should read as follows:

background-image: linear-gradient(to right, red, orange 50%, brown).

If we form the gradients using the above mentioned method and apply them to the element, we can get the required effect.

_x000D_
_x000D_
.red-orange-brown {_x000D_
  background-image: linear-gradient(to right, red, orange 50%, brown);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}_x000D_
.green-yellowgreen-yellow-gold {_x000D_
  background-image: linear-gradient(to right, green, yellowgreen 33%, yellow 66%, gold);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<span class="red-orange-brown">Red to Orange to Brown</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<span class="green-yellowgreen-yellow-gold">Green to Yellow-green to Yellow to Gold</span>
_x000D_
_x000D_
_x000D_

How to check sbt version?

run sbt console then type sbtVersion to check sbt version, and scalaVersion for scala version

T-SQL: Deleting all duplicate rows but keeping one

Example query:

DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)

Here fields are column on which you want to group the duplicate rows.

How to add a “readonly” attribute to an <input>?

jQuery <1.9

$('#inputId').attr('readonly', true);

jQuery 1.9+

$('#inputId').prop('readonly', true);

Read more about difference between prop and attr

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

Dynamically update values of a chartjs chart

I think the easiest way is to write a function to update your chart including the chart.update()method. Check out this simple example I wrote in jsfiddle for a Bar Chart.

_x000D_
_x000D_
//value for x-axis_x000D_
var emotions = ["calm", "happy", "angry", "disgust"];_x000D_
_x000D_
//colours for each bar_x000D_
var colouarray = ['red', 'green', 'yellow', 'blue'];_x000D_
_x000D_
//Let's initialData[] be the initial data set_x000D_
var initialData = [0.1, 0.4, 0.3, 0.6];_x000D_
_x000D_
//Let's updatedDataSet[] be the array to hold the upadted data set with every update call_x000D_
var updatedDataSet;_x000D_
_x000D_
/*Creating the bar chart*/_x000D_
var ctx = document.getElementById("barChart");_x000D_
var barChart = new Chart(ctx, {_x000D_
  type: 'bar',_x000D_
  data: {_x000D_
    labels: emotions,_x000D_
    datasets: [{_x000D_
      backgroundColor: colouarray,_x000D_
      label: 'Prediction',_x000D_
      data: initialData_x000D_
    }]_x000D_
  },_x000D_
  options: {_x000D_
    scales: {_x000D_
      yAxes: [{_x000D_
        ticks: {_x000D_
          beginAtZero: true,_x000D_
          min: 0,_x000D_
          max: 1,_x000D_
          stepSize: 0.5,_x000D_
        }_x000D_
      }]_x000D_
    }_x000D_
  }_x000D_
});_x000D_
_x000D_
/*Function to update the bar chart*/_x000D_
function updateBarGraph(chart, label, color, data) {_x000D_
  chart.data.datasets.pop();_x000D_
  chart.data.datasets.push({_x000D_
    label: label,_x000D_
    backgroundColor: color,_x000D_
    data: data_x000D_
  });_x000D_
  chart.update();_x000D_
}_x000D_
_x000D_
/*Updating the bar chart with updated data in every second. */_x000D_
setInterval(function() {_x000D_
  updatedDataSet = [Math.random(), Math.random(), Math.random(), Math.random()];_x000D_
  updateBarGraph(barChart, 'Prediction', colouarray, updatedDataSet);_x000D_
}, 1000);
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>_x000D_
_x000D_
<body>_x000D_
    <div>_x000D_
      <h1>Update Bar Chart</h1>_x000D_
      <canvas id="barChart" width="800" height="450"></canvas>_x000D_
    </div>_x000D_
    <script src="barchart.js"></script>_x000D_
  </body>_x000D_
  _x000D_
</head>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Hope this helps.

How can I check for "undefined" in JavaScript?

Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/

(Note that the use of var for in tests make a difference when in a scoped wrapper)

Code for reference:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

And results:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

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

Let me make it simple.
You can use @JoinColumn on either sides irrespective of mapping.

Let's divide this into three cases.
1) Uni-directional mapping from Branch to Company.
2) Bi-direction mapping from Company to Branch.
3) Only Uni-directional mapping from Company to Branch.

So any use-case will fall under this three categories. So let me explain how to use @JoinColumn and mappedBy.
1) Uni-directional mapping from Branch to Company.
Use JoinColumn in Branch table.
2) Bi-direction mapping from Company to Branch.
Use mappedBy in Company table as describe by @Mykhaylo Adamovych's answer.
3)Uni-directional mapping from Company to Branch.
Just use @JoinColumn in Company table.

@Entity
public class Company {

@OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY)
@JoinColumn(name="courseId")
private List<Branch> branches;
...
}

This says that in based on the foreign key "courseId" mapping in branches table, get me list of all branches. NOTE: you can't fetch company from branch in this case, only uni-directional mapping exist from company to branch.

apache and httpd running but I can't see my website

There are several possibilities.

  • firewall, iptables configuration
  • apache listen address / port

More information is needed about your configuration. What distro are you using? Can you connect via 127.0.0.1?

If the issue is with the firewall/iptables, you can add the following lines to /etc/sysconfig/iptables:

-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

(Second line is only needed for https)

Make sure this is above any lines that would globally restrict access, like the following:

-A INPUT -j REJECT --reject-with icmp-host-prohibited

Tested on CentOS 6.3

And finally

service iptables restart

Best way to convert strings to symbols in hash

Would something like the following work?

new_hash = Hash.new
my_hash.each { |k, v| new_hash[k.to_sym] = v }

It'll copy the hash, but you won't care about that most of the time. There's probably a way to do it without copying all the data.

Write Array to Excel Range

when you want to write a 1D Array in a Excel sheet you have to transpose it and you don't have to create a 2D array with 1 column ([n, 1]) as I read above! Here is a example of code :

 wSheet.Cells(RowIndex, colIndex).Resize(RowsCount, ).Value = _excel.Application.transpose(My1DArray)

Have a good day, Gilles

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

myControl.Left = (this.ClientSize.Width - myControl.Width) / 2 ;
myControl.Top = (this.ClientSize.Height - myControl.Height) / 2;

Parse error: Syntax error, unexpected end of file in my PHP code

I developed a plugin and installed it on a Wordpress site running on Nginx and it was fine. I only had this error when I switched to Apache, turned out the web server was not accepting the <?, so I just replaced the <? tags to <?php then it worked.

What does it mean to "program to an interface"?

It sounds like you understand how interfaces work but are unsure of when to use them and what advantages they offer. Here are a few examples of when an interface would make sense:

// if I want to add search capabilities to my application and support multiple search
// engines such as Google, Yahoo, Live, etc.

interface ISearchProvider
{
    string Search(string keywords);
}

then I could create GoogleSearchProvider, YahooSearchProvider, LiveSearchProvider, etc.

// if I want to support multiple downloads using different protocols
// HTTP, HTTPS, FTP, FTPS, etc.
interface IUrlDownload
{
    void Download(string url)
}

// how about an image loader for different kinds of images JPG, GIF, PNG, etc.
interface IImageLoader
{
    Bitmap LoadImage(string filename)
}

then create JpegImageLoader, GifImageLoader, PngImageLoader, etc.

Most add-ins and plugin systems work off interfaces.

Another popular use is for the Repository pattern. Say I want to load a list of zip codes from different sources

interface IZipCodeRepository
{
    IList<ZipCode> GetZipCodes(string state);
}

then I could create an XMLZipCodeRepository, SQLZipCodeRepository, CSVZipCodeRepository, etc. For my web applications, I often create XML repositories early on so I can get something up and running before the SQL Database is ready. Once the database is ready I write an SQLRepository to replace the XML version. The rest of my code remains unchanged since it runs solely off of interfaces.

Methods can accept interfaces such as:

PrintZipCodes(IZipCodeRepository zipCodeRepository, string state)
{
    foreach (ZipCode zipCode in zipCodeRepository.GetZipCodes(state))
    {
        Console.WriteLine(zipCode.ToString());
    }
}

jQuery equivalent to Prototype array.last()

See these test cases http://jsperf.com/last-item-method The most effective way is throug .pop method (in V8), but loses the last element of the array

Create a .csv file with values from a Python list

For those looking for less complicated solution. I actually find this one more simplisitic solution that will do similar job:

import pandas as pd
a = ['a','b','c'] 
df = pd.DataFrame({'a': a})
df= df.set_index('a').T
df.to_csv('list_a.csv', index=False)

Hope this helps as well.

iCheck check if checkbox is checked

$('input').on('ifChanged', function(event) {
             if($(".checkbox").is(":checked")) {
                $value = $(this).val();
             }

             else if($(".checkbox").is(":not(:checked)")) {
                $value= $(this).val();
             }
        });

How to run JUnit test cases from the command line

With JUnit 4.12 the following didn't work for me:

java -cp .:/usr/share/java/junit.jar org.junit.runner.JUnitCore [test class name]

Apparently, from JUnit 4.11 onwards you should also include hamcrest-core.jar in your classpath:

java -cp .:/usr/share/java/junit.jar:/usr/share/java/hamcrest-core.jar org.junit.runner.JUnitCore [test class name]

Node.js Web Application examples/tutorials

Update

Dav Glass from Yahoo has given a talk at YuiConf2010 in November which is now available in Video from.

He shows to great extend how one can use YUI3 to render out widgets on the server side an make them work with GET requests when JS is disabled, or just make them work normally when it's active.

He also shows examples of how to use server side DOM to apply style sheets before rendering and other cool stuff.

The demos can be found on his GitHub Account.

The part that's missing IMO to make this really awesome, is some kind of underlying storage of the widget state. So that one can visit the page without JavaScript and everything works as expected, then they turn JS on and now the widget have the same state as before but work without page reloading, then throw in some saving to the server + WebSockets to sync between multiple open browser.... and the next generation of unobtrusive and gracefully degrading ARIA's is born.

Original Answer

Well go ahead and built it yourself then.

Seriously, 90% of all WebApps out there work fine with a REST approach, of course you could do magical things like superior user tracking, tracking of downloads in real time, checking which parts of videos are being watched etc.

One problem is scalability, as soon as you have more then 1 Node process, many (but not all) of the benefits of having the data stored between requests go away, so you have to make sure that clients always hit the same process. And even then, bigger things will yet again need a database layer.

Node.js isn't the solution to everything, I'm sure people will build really great stuff in the future, but that needs some time, right now many are just porting stuff over to Node to get things going.

What (IMHO) makes Node.js so great, is the fact that it streamlines the Development process, you have to write less code, it works perfectly with JSON, you loose all that context switching.

I mainly did gaming experiments so far, but I can for sure say that there will be many cool multi player (or even MMO) things in the future, that use both HTML5 and Node.js.

Node.js is still gaining traction, it's not even near to the RoR Hype some years ago (just take a look at the Node.js tag here on SO, hardly 4-5 questions a day).

Rome (or RoR) wasn't built over night, and neither will Node.js be.

Node.js has all the potential it needs, but people are still trying things out, so I'd suggest you to join them :)

C# Iterating through an enum? (Indexing a System.Array)

Ancient question, but 3Dave's answer supplied the easiest approach. I needed a little helper method to generate a Sql script to decode an enum value in the database for debugging. It worked great:

    public static string EnumToCheater<T>() {
        var sql = "";
        foreach (var enumValue in Enum.GetValues(typeof(T)))
            sql += $@"when {(int) enumValue} then '{enumValue}' ";
        return $@"case ?? {sql}else '??' end,";
    }

I have it in a static method, so usage is:

var cheater = MyStaticClass.EnumToCheater<MyEnum>()

LINQ query to find if items in a list are contained in another list

bool doesL1ContainsL2 = l1.Intersect(l2).Count() == l2.Count;

L1 and L2 are both List<T>

How to delete selected text in the vi editor

Do it the vi way.

To delete 5 lines press: 5dd ( 5 delete )

To select ( actually copy them to the clipboard ) you type: 10yy

It is a bit hard to grasp, but very handy to learn when using those remote terminals

Be aware of the learning curves for some editors:


(source: calver at unix.rulez.org)

The executable was signed with invalid entitlements

This is because your device, on which you are running your application is not selected with your provisioning profile.

So just go through Certificates, Identifiers & Profiles select your iOS Provisioning Profiles click on edit then select your Device

enter image description here

Switch statement for string matching in JavaScript

Another option is to use input field of a regexp match result:

str = 'XYZ test';
switch (str) {
  case (str.match(/^xyz/) || {}).input:
    console.log("Matched a string that starts with 'xyz'");
    break;
  case (str.match(/test/) || {}).input:
    console.log("Matched the 'test' substring");        
    break;
  default:
    console.log("Didn't match");
    break;
}

What is the difference between user and kernel modes in operating systems?

These are two different modes in which your computer can operate. Prior to this, when computers were like a big room, if something crashes – it halts the whole computer. So computer architects decide to change it. Modern microprocessors implement in hardware at least 2 different states.

User mode:

  • mode where all user programs execute. It does not have access to RAM and hardware. The reason for this is because if all programs ran in kernel mode, they would be able to overwrite each other’s memory. If it needs to access any of these features – it makes a call to the underlying API. Each process started by windows except of system process runs in user mode.

Kernel mode:

  • mode where all kernel programs execute (different drivers). It has access to every resource and underlying hardware. Any CPU instruction can be executed and every memory address can be accessed. This mode is reserved for drivers which operate on the lowest level

How the switch occurs.

The switch from user mode to kernel mode is not done automatically by CPU. CPU is interrupted by interrupts (timers, keyboard, I/O). When interrupt occurs, CPU stops executing the current running program, switch to kernel mode, executes interrupt handler. This handler saves the state of CPU, performs its operations, restore the state and returns to user mode.

http://en.wikibooks.org/wiki/Windows_Programming/User_Mode_vs_Kernel_Mode

http://tldp.org/HOWTO/KernelAnalysis-HOWTO-3.html

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

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

How do I limit the number of returned items?

I am a bit lazy, so I like simple things:

let users = await Users.find({}, null, {limit: 50});

How to copy a string of std::string type in C++?

strcpy example:

#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]="Sample string" ;
  char str2[40] ;
  strcpy (str2,str1) ;
  printf ("str1: %s\n",str1) ;
  return 0 ;
}

Output: str1: Sample string

Your case:

A simple = operator should do the job.

string str1="Sample string" ;
string str2 = str1 ;

Simple CSS Animation Loop – Fading In & Out "Loading" Text

To make more than one element fade in/out sequentially such as 5 elements fade each 4s,

1- make unique animation for each element with animation-duration equal to [ 4s (duration for each element) * 5 (number of elements) ] = 20s

animation-name: anim1 , anim2, anim3 ... 
animation-duration : 20s, 20s, 20s ... 

2- get animation keyframe for each element.

100% (keyframes percentage) / 5 (elements) = 20% (frame for each element)

3- define starting and ending point for each animation:

each animation has 20% frame length and @keyframes percentage always starts from 0%, so first animation will start from 0% and end in his frame(20%), and each next animation will starts from previous animation ending point and end when it reach his frame (+20% ),

@keyframes animation1 { 0% {}, 20% {}}
@keyframes animation2 { 20% {}, 40% {}}
@keyframes animation3 { 40% {}, 60% {}}
and so on

now we need to make each animation fade in from 0 to 1 opacity and fade out from 1 to 0,

so we will add another 2 points (steps) for each animation after starting and before ending point to handle the full opacity(1)

enter image description here

http://codepen.io/El-Oz/pen/WwPPZQ

.slide1 {
    animation: fadeInOut1 24s ease reverse forwards infinite
}

.slide2 {
    animation: fadeInOut2 24s ease reverse forwards infinite
}

.slide3 {
    animation: fadeInOut3 24s ease reverse forwards infinite
}

.slide4 {
    animation: fadeInOut4 24s ease reverse forwards infinite
}

.slide5 {
    animation: fadeInOut5 24s ease reverse forwards infinite
}

.slide6 {
    animation: fadeInOut6 24s ease reverse forwards infinite
}

@keyframes fadeInOut1 {
    0% { opacity: 0 }
    1% { opacity: 1 }
    14% {opacity: 1 }
    16% { opacity: 0 }
}

@keyframes fadeInOut2 {
    0% { opacity: 0 }
    14% {opacity: 0 }
    16% { opacity: 1 }
    30% { opacity: 1 }
    33% { opacity: 0 }
}

@keyframes fadeInOut3 {
    0% { opacity: 0 }
    30% {opacity: 0 }
    33% {opacity: 1 }
    46% { opacity: 1 }
    48% { opacity: 0 }
}

@keyframes fadeInOut4 {
    0% { opacity: 0 }
    46% { opacity: 0 }
    48% { opacity: 1 }
    64% { opacity: 1 }
    65% { opacity: 0 }
}

@keyframes fadeInOut5 {
    0% { opacity: 0 }
    64% { opacity: 0 }
    66% { opacity: 1 }
    80% { opacity: 1 }
    83% { opacity: 0 }
}

@keyframes fadeInOut6 {
    80% { opacity: 0 }
    83% { opacity: 1 }
    99% { opacity: 1 }
    100% { opacity: 0 }
}

jquery find closest previous sibling with class

You can follow this code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $(".add").on("click", function () {
            var v = $(this).closest(".division").find("input[name='roll']").val();
            alert(v);
        });
    });
</script>
<?php

for ($i = 1; $i <= 5; $i++) {
    echo'<div class = "division">'
        . '<form method="POST" action="">'
        . '<p><input type="number" name="roll" placeholder="Enter Roll"></p>'
        . '<p><input type="button" class="add" name = "submit" value = "Click"></p>'
        . '</form></div>';
}
?>

You can get idea from this.

How to update Ruby with Homebrew?

To upgrade Ruby with rbenv: Per the rbenv README

  • Update first: brew upgrade rbenv ruby-build
  • See list of Ruby versions: versions available: rbenv install -l
  • Install: rbenv install <selected version>

When should I use Memcache instead of Memcached?

Memcached client library was just recently released as stable. It is being used by digg ( was developed for digg by Andrei Zmievski, now no longer with digg) and implements much more of the memcached protocol than the older memcache client. The most important features that memcached has are:

  1. Cas tokens. This made my life much easier and is an easy preventive system for stale data. Whenever you pull something from the cache, you can receive with it a cas token (a double number). You can than use that token to save your updated object. If no one else updated the value while your thread was running, the swap will succeed. Otherwise a newer cas token was created and you are forced to reload the data and save it again with the new token.
  2. Read through callbacks are the best thing since sliced bread. It has simplified much of my code.
  3. getDelayed() is a nice feature that can reduce the time your script has to wait for the results to come back from the server.
  4. While the memcached server is supposed to be very stable, it is not the fastest. You can use binary protocol instead of ASCII with the newer client.
  5. Whenever you save complex data into memcached the client used to always do serialization of the value (which is slow), but now with memcached client you have the option of using igbinary. So far I haven't had the chance to test how much of a performance gain this can be.

All of this points were enough for me to switch to the newest client, and can tell you that it works like a charm. There is that external dependency on the libmemcached library, but have managed to install it nonetheless on Ubuntu and Mac OSX, so no problems there so far.

If you decide to update to the newer library, I suggest you update to the latest server version as well as it has some nice features as well. You will need to install libevent for it to compile, but on Ubuntu it wasn't much trouble.

I haven't seen any frameworks pick up the new memcached client thus far (although I don't keep track of them), but I presume Zend will get on board shortly.

UPDATE

Zend Framework 2 has an adapter for Memcached which can be found here

WHERE clause on SQL Server "Text" data type

Another option would be:

SELECT * FROM [Village] WHERE PATINDEX('foo', [CastleType]) <> 0

Sorting std::map using value

Another solution would be the usage of std::make_move_iterator to build a new vector (C++11 )

    int main(){

      std::map<std::string, int> map;
       //Populate map

      std::vector<std::pair<std::string, int>> v {std::make_move_iterator(begin(map)),
                                      std::make_move_iterator(end(map))};
       // Create a vector with the map parameters

       sort(begin(v), end(v),
             [](auto p1, auto p2){return p1.second > p2.second;});
       // Using sort + lambda function to return an ordered vector 
       // in respect to the int value that is now the 2nd parameter 
       // of our newly created vector v
  }

Getting Class type from String

String clsName = "Ex";  // use fully qualified name
Class cls = Class.forName(clsName);
Object clsInstance = (Object) cls.newInstance();

Check the Java Tutorial trail on Reflection at http://java.sun.com/docs/books/tutorial/reflect/TOC.html for further details.

javascript - Create Simple Dynamic Array

var arr = [];
for(var i=1; i<=mynumber; i++) {
   arr.push(i.toString());
}

How do I add more members to my ENUM-type column in MySQL?

FYI: A useful simulation tool - phpMyAdmin with Wampserver 3.0.6 - Preview SQL: I use 'Preview SQL' to see the SQL code that would be generated before you save the column with the change to ENUM. Preview SQL

Above you see that I have entered 'Ford','Toyota' into the ENUM but I am getting syntax ENUM(0) which is generating syntax error Query error 1064#

I then copy and paste and alter the SQL and run it through SQL with a positive result.

SQL changed

This is a quickfix that I use often and can also be used on existing ENUM values that need to be altered. Thought this might be useful.

Create table using Javascript

_x000D_
_x000D_
var div = document.createElement('div');
            div.setAttribute("id", "tbl");
            document.body.appendChild(div)
                document.getElementById("tbl").innerHTML = "<table border = '1'>" +
              '<tr>' +
                '<th>Header 1</th>' +
                '<th>Header 2</th> ' +
                '<th>Header 3</th>' +
              '</tr>' +
              '<tr>' +
                '<td>Data 1</td>' +
                '<td>Data 2</td>' +
                '<td>Data 3</td>' +
              '</tr>' +
              '<tr>' +
                '<td>Data 1</td>' +
                '<td>Data 2</td>' +
                '<td>Data 3</td>' +
              '</tr>' +
              '<tr>' +
                '<td>Data 1</td>' +
                '<td>Data 2</td>' +
                '<td>Data 3</td>' +
              '</tr>' 
_x000D_
_x000D_
_x000D_

Setting an image button in CSS - image:active

This is what worked for me.

<!DOCTYPE html> 
<form action="desired Link">
  <button>  <img src="desired image URL"/>
  </button>
</form>
<style> 

</style>

What does "&" at the end of a linux command mean?

I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C). Now a program can use SIG_IGN to ignore all signals or SIG_DFL to restore the default action.

Now if you do $ command & then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.

Simple JavaScript problem: onClick confirm not preventing default action

Using a simple link for an action such as removing a record looks dangerous to me : what if a crawler is trying to index your pages ? It will ignore any javascript and follow every link, probably not a good thing.

You'd better use a form with method="POST".

And then you will have an event "OnSubmit" to do exactly what you want...

How can I set the default value for an HTML <select> element?

I came across this question, but the accepted and highly upvoted answer didn't work for me. It turns out that if you are using React, then setting selected doesn't work.

Instead you have to set a value in the <select> tag directly as shown below:

<select value="B">
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>

Read more about why here on the React page.

What is @ModelAttribute in Spring MVC?

So I will try to explain it in simpler way. Let's have:

public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }
}

As described in the Spring MVC documentation - the @ModelAttribute annotation can be used on methods or on method arguments. And of course we can have both use at the same time in one controller.

1.Method annotation

@ModelAttribute(“cities”)
 public List<String> checkOptions(){
 return new Arrays.asList(new[]{“Sofia”,”Pleven","Ruse”});//and so on
}

Purpose of such method is to add attribute in the model. So in our case cities key will have the list new Arras.asList(new[]{“Sofia”,”Pleven","Ruse”}) as value in the Model (you can think of Model as map(key:value)). @ModelAttribute methods in a controller are invoked before @RequestMapping methods, within the same controller.

Here we want to add to the Model common information which will be used in the form to display to the user. For example it can be used to fill a HTML select:

enter image description here

2.Method argument

public String findPerson(@ModelAttriute(value="person") Person person) {
    //..Some logic with person
    return "person.jsp";
}

An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. So in this case we expect that we have in the Model person object as key and we want to get its value and put it to the method argument Person person. If such does not exists or (sometimes you misspell the (value="persson")) then Spring will not find it in the Model and will create empty Person object using its defaults. Then will take the request parameters and try to data bind them in the Person object using their names.

name="Dmitrij"&countries=Lesoto&sponsor.organization="SilkRoad"&authorizedFunds=&authorizedHours=&

So we have name and it will be bind to Person.name using setName(String name). So in

//..Some logic with person

we have access to this filled name with value "Dimitrij".

Of course Spring can bind more complex objects like Lists, Maps, List of Sets of Maps and so on but behind the scene it makes the data binding magic.

  1. We can have at the same time model annotated method and request method handler with @ModelAttribute in the arguments. Then we have to union the rules.

  2. Of course we have tons of different situations - @ModelAttribute methods can also be defined in an @ControllerAdvice and so on...

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

I thought you could avoid it by just passing the --no-sign-request param, like so:

aws --region us-west-2 --no-sign-request --endpoint-url=http://192.168.99.100:4572 \
 s3 mb s3://mytestbucket

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

I had added another project to my workspace and was trying to reference an activity from it in the manifest file, and I was getting this error. The problem is I was referencing the library incorrectly. This is how I fixed the problem:

  • Right click on project
  • Select Properties
  • Click on Android on left menu
  • Click on Add
  • Please select a Library Project

The jar went into Android Dependencies folder and this error was fixed.

How to get value of selected radio button?

var rates = document.getElementById('rates').value;

The rates element is a div, so it won't have a value. This is probably where the undefined is coming from.

The checked property will tell you whether the element is selected:

if (document.getElementById('r1').checked) {
  rate_value = document.getElementById('r1').value;
}

How to fix a Div to top of page with CSS only

You can simply make the top div fixed:

#top { position: fixed; top: 20px; left: 20px; }

“tag already exists in the remote" error after recreating the git tag

In Windows SourceTree, untick Push all tags to remotes.

enter image description here

Open mvc view in new window from controller

You can use Tommy's method in forms as well:

@using (Html.BeginForm("Action", "Controller", FormMethod.Get, new { target = "_blank" }))
{
//code
}

C++ Boost: undefined reference to boost::system::generic_category()

I searched for a solution as well, and none of the answers I encountered solved the error, Until I found the answer of "ViRuSTriNiTy" to this thread: Undefined reference to 'boost::system::generic_category()'?

according to that answer, try to add these lines to your cmake file:

find_package(Boost 1.55.0 REQUIRED COMPONENTS system filesystem)
include_directories(... ${Boost_INCLUDE_DIRS})
link_directories(... ${Boost_LIBRARY_DIRS})
target_link_libraries(... ${Boost_LIBRARIES})

CSS list-style-image size

I'm using:

_x000D_
_x000D_
li {_x000D_
 margin: 0;_x000D_
 padding: 36px 0 36px 84px;_x000D_
 list-style: none;_x000D_
 background-image: url("../../images/checked_red.svg");_x000D_
 background-repeat: no-repeat;_x000D_
 background-position: left center;_x000D_
 background-size: 40px;_x000D_
}
_x000D_
_x000D_
_x000D_

where background-size set the background image size.

Why doesn't catching Exception catch RuntimeException?

I faced similar scenario. It was happening because classA's initilization was dependent on classB's initialization. When classB's static block faced runtime exception, classB was not initialized. Because of this, classB did not throw any exception and classA's initialization failed too.

class A{//this class will never be initialized because class B won't intialize
  static{
    try{
      classB.someStaticMethod();
    }catch(Exception e){
      sysout("This comment will never be printed");
    }
 }
}

class B{//this class will never be initialized
 static{
    int i = 1/0;//throw run time exception 
 }

 public static void someStaticMethod(){}
}

And yes...catching Exception will catch run time exceptions as well.

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

Following was working for me. hope this helps you

<add name="getconn" connectionString="Data Source=servername;Initial Catalog=DBName;Persist Security Info=True;User ID=sa;Password=***" />

Efficiently updating database using SQLAlchemy ORM

Withough testing, I'd try:

for c in session.query(Stuff).all():
     c.foo = c.foo+1
session.commit()

(IIRC, commit() works without flush()).

I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of queries. I assume that iterating over the query object is less efficient than iterating over a list generated by the all() method of the query object.

[Please note comment below - this did not speed things up at all].

How to fix committing to the wrong Git branch?

For multiple commits on the wrong branch

If, for you, it is just about 1 commit, then there are plenty of other easier resetting solutions available. For me, I had about 10 commits that I'd accidentally created on master branch instead of, let's call it target, and I did not want to lose the commit history.

What you could do, and what saved me was using this answer as a reference, using a 4 step process, which is -

  1. Create a new temporary branch temp from master
  2. Merge temp into the branch originally intended for commits, i.e. target
  3. Undo commits on master
  4. Delete the temporary branch temp.

Here are the above steps in details -

  1. Create a new branch from the master (where I had accidentally committed a lot of changes)

    git checkout -b temp
    

    Note: -b flag is used to create a new branch
    Just to verify if we got this right, I'd do a quick git branch to make sure we are on the temp branch and a git log to check if we got the commits right.

  2. Merge the temporary branch into the branch originally intended for the commits, i.e. target.
    First, switch to the original branch i.e. target (You might need to git fetch if you haven't)

    git checkout target
    

    Note: Not using -b flag
    Now, let's merge the temporary branch into the branch we have currently checkout out target

    git merge temp
    

    You might have to take care of some conflicts here, if there are. You can push (I would) or move on to the next steps, after successfully merging.

  3. Undo the accidental commits on master using this answer as reference, first switch to the master

    git checkout master
    

    then undo it all the way back to match the remote using the command below (or to particular commit, using appropriate command, if you want)

    git reset --hard origin/master
    

    Again, I'd do a git log before and after just to make sure that the intended changes took effect.

  4. Erasing the evidence, that is deleting the temporary branch. For this, first you need to checkout the branch that the temp was merged into, i.e. target (If you stay on master and execute the command below, you might get a error: The branch 'temp' is not fully merged), so let's

    git checkout target
    

    and then delete the proof of this mishap

    git branch -d temp
    

There you go.

AngularJS : How to watch service variables?

A wee bit ugly, but I've added registration of scope variables to my service for a toggle:

myApp.service('myService', function() {
    var self = this;
    self.value = false;
    self.c2 = function(){};
    self.callback = function(){
        self.value = !self.value; 
       self.c2();
    };

    self.on = function(){
        return self.value;
    };

    self.register = function(obj, key){ 
        self.c2 = function(){
            obj[key] = self.value; 
            obj.$apply();
        } 
    };

    return this;
});

And then in the controller:

function MyCtrl($scope, myService) {
    $scope.name = 'Superhero';
    $scope.myVar = false;
    myService.register($scope, 'myVar');
}

C++ style cast from unsigned char * to const char *

Hope it help. :)

const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;

Use basic authentication with jQuery and Ajax

Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.

$.ajaxSetup({
  headers: {
    'Authorization': "Basic XXXXX"
  }
});

increase font size of hyperlink text html

you can add class in anchor tag also like below

.a_class {font-size: 100px} 

SQL Error: ORA-12899: value too large for column

example : 1 and 2 table is available

1 table delete entry and select nor 2 table records and insert to no 1 table . when delete time no 1 table dont have second table records example emp id not available means this errors appeared

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

you can also copy the gradlew.bat into you root folder and copy the gradlew-wrapper into gradlew folder.

that's work for me.

How to use private Github repo as npm dependency

I wasn't able to make the accepted answer work in a Docker container.

What worked for me was to set the Personal Access Token from github in a file .nextrc

ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n  login $GITHUB_READ_TOKEN" > ~/.netrc 
RUN npm install --only=production --force \
  && npm cache clean --force
RUN rm ~/.netrc

in package.json

"my-lib": "github:username/repo",

How to reverse an animation on mouse out after hover

Try this:

@keyframe in {
from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
@keyframe out {
from {
    transform: rotate(360deg);
  }
  to {
    transform: rotate(0deg);
  }
}

supported in Firefox 5+, IE 10+, Chrome, Safari 4+, Opera 12+

Create a global variable in TypeScript

This is how I have fixed it:

Steps:

  1. Declared a global namespace, for e.g. custom.d.ts as below :
declare global {
    namespace NodeJS {
        interface Global {
            Config: {}
        }
    }
}
export default global;
  1. Map the above created a file into "tsconfig.json" as below:
"typeRoots": ["src/types/custom.d.ts" ]
  1. Get the above created global variable in any of the files as below:
console.log(global.config)

Note:

  1. typescript version: "3.0.1".

  2. In my case, the requirement was to set the global variable before boots up the application and the variable should access throughout the dependent objects so that we can get the required config properties.

Hope this helps!

Thank you

C++ getters/setters coding style

Even though the name is immutable, you may still want to have the option of computing it rather than storing it in a field. (I realize this is unlikely for "name", but let's aim for the general case.) For that reason, even constant fields are best wrapped inside of getters:

class Foo {
    public:
        const std::string& getName() const {return name_;}
    private:
        const std::string& name_;
};

Note that if you were to change getName() to return a computed value, it couldn't return const ref. That's ok, because it won't require any changes to the callers (modulo recompilation.)

How to provide a mysql database connection in single file in nodejs

I think that you should use a connection pool instead of share a single connection. A connection pool would provide a much better performance, as you can check here.

As stated in the library documentation, it occurs because the MySQL protocol is sequential (this means that you need multiple connections to execute queries in parallel).

Connection Pool Docs

How to update cursor limit for ORA-01000: maximum open cursors exceed

you can update the setting under init.ora in oraclexe\app\oracle\product\11.2.0\server\config\scripts

Avoiding "resource is out of sync with the filesystem"

A little hint. The message often appears during rename operation. The quick workaround for me is pressing Ctrl-Y (redo shortcut) after message confirmation. It works only if the renaming affects a single file.

iterating and filtering two lists using java 8

If you stream the first list and use a filter based on contains within the second...

list1.stream()
    .filter(item -> !list2.contains(item))

The next question is what code you'll add to the end of this streaming operation to further process the results... over to you.

Also, list.contains is quite slow, so you would be better with sets.

But then if you're using sets, you might find some easier operations to handle this, like removeAll

Set list1 = ...;
Set list2 = ...;
Set target = new Set();
target.addAll(list1);
target.removeAll(list2);

Given we don't know how you're going to use this, it's not really possible to advise which approach to take.

How do I get multiple subplots in matplotlib?

You might be interested in the fact that as of matplotlib version 2.1 the second code from the question works fine as well.

From the change log:

Figure class now has subplots method The Figure class now has a subplots() method which behaves the same as pyplot.subplots() but on an existing figure.

Example:

import matplotlib.pyplot as plt

fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)

plt.show()

Customize UITableView header section

You can try this:

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];
    /* Create custom view to display section header... */
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];
    [label setFont:[UIFont boldSystemFontOfSize:12]];
     NSString *string =[list objectAtIndex:section];
    /* Section header is in 0th index... */
    [label setText:string];
    [view addSubview:label];
    [view setBackgroundColor:[UIColor colorWithRed:166/255.0 green:177/255.0 blue:186/255.0 alpha:1.0]]; //your background color...
    return view;
}

In Java, how do you determine if a thread is running?

Use Thread.currentThread().isAlive() to see if the thread is alive[output should be true] which means thread is still running the code inside the run() method or use Thread.currentThread.getState() method to get the exact state of the thread.

Return HTML from ASP.NET Web API

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

Combining "LIKE" and "IN" for SQL Server

No, MSSQL doesn't allow such queries. You should use col LIKE '...' OR col LIKE '...' etc.

Is there a way to get the XPath in Google Chrome?

As of the latest update for chrome you can now click any element in the element inspector and copy the XPath to clipboard.

Easiest way to compare arrays in C#

Use Enumerable.SequenceEqual in LINQ.

int[] arr1 = new int[] { 1,2,3};
int[] arr2 = new int[] { 3,2,1 };

Console.WriteLine(arr1.SequenceEqual(arr2)); // false
Console.WriteLine(arr1.Reverse().SequenceEqual(arr2)); // true

PostgreSQL, checking date relative to "today"

I think this will do it:

SELECT * FROM MyTable WHERE mydate > now()::date - 365;

Convert a String representation of a Dictionary to a dictionary?

Use json. the ast library consumes a lot of memory and and slower. I have a process that needs to read a text file of 156Mb. Ast with 5 minutes delay for the conversion dictionary json and 1 minutes using 60% less memory!

C# Creating and using Functions

The reason why you have the error is because your add function is defined after your using it in main if you were to create a function prototype before main up above it with public int Add(int x, int y); or you could just copy and paste your entire Add function above main cause main is where the compiler starts execution so doesn't it make sense to declare and define a function before you use it hope that helps. :D

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

This is probably not a solution to your problem, but a suggestion just in case (I know I ran into a similar problem before but not with a .NET application).

If you are on a 64-bit machine, there are 2 regsvr32.exe files; One is in \Windows\System32 and the other one is in \Windows\SysWOW64.

You cannot register 64-bit COM-objects with the 32-bit version, but you can do it vice versa. I'd try registering your DLL with both regsvr32.exe files explicitly (i.e. typing "C:\Windows\System32\regsvr32.exe /i mydll.dll" and then "C:\Windows\SysWOW64\regsvr32.exe /i mydll.dll") and seeing if that helps...

jquery data selector

You can also use a simple filtering function without any plugins. This is not exactly what you want but the result is the same:

$('a').data("user", {name: {first:"Tom",last:"Smith"},username: "tomsmith"});

$('a').filter(function() {
    return $(this).data('user') && $(this).data('user').name.first === "Tom";
});

Sort array of objects by object fields

reference answer of Demodave to eating multi key

 function array_sort_by(array $arr, $keys){

    if(!is_array($keys))
        $keyList = explode(',', $keys);
    $keyList = array_keys(array_flip($keyList)); // array_unique 
    $keyList = array_reverse($keyList);

    $result = &$arr;
    foreach ($keyList as $key) {
        if(array_key_exists($key, $arr))
            $result = usort($result, function($a, $b) use ($key) { return strcmp($a->{$key}, $b->{$key}); });
    }
    return $result;
}

How to parse JSON boolean value?

A boolean is not an integer; 1 and 0 are not boolean values in Java. You'll need to convert them explicitly:

boolean multipleContacts = (1 == jsonObject.getInt("MultipleContacts"));

or serialize the ints as booleans from the start.

Java 8: Difference between two LocalDateTime in multiple units

TL;DR

Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());

and then use the methods period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart().


Expanded answer

I'll answer the original question, i.e. how to get the time difference between two LocalDateTimes in years, months, days, hours & minutes, such that the "sum" (see note below) of all the values for the different units equals the total temporal difference, and such that the value in each unit is smaller than the next bigger unit—i.e. minutes < 60, hours < 24, and so on.

Given two LocalDateTimes start and end, e.g.

LocalDateTime start = LocalDateTime.of(2019, 11, 29, 17, 15);
LocalDateTime end = LocalDateTime.of(2020, 11, 30, 18, 44);

we can represent the absolute timespan between the two with a Duration—perhaps using Duration.between(start, end). But the biggest unit we can extract out of a Duration is days (as a temporal unit equivalent to 24h)—see the note below for an explanation. To use larger units (months, years) we can represent this Duration with a pair of (Period, Duration), where the Period measures the difference up to a precision of days and the Duration represents the remainder:

Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());

Now we can simply use the methods defined on Period and Duration to extract the individual units:

System.out.printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds",
        period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(),
        duration.toMinutesPart(), duration.toSecondsPart());
1 years, 0 months, 1 days, 1 hours, 29 minutes, 0 seconds

or, using the default format:

System.out.println(period + " + " + duration);
P1Y1D + PT1H29M

Note on years, months & days

Note that, in java.time's conception, "units" like "month" or "year" don't represent a fixed, absolute temporal value—they're date- and calendar-dependent, as the following example illustrates:

LocalDateTime
        start1 = LocalDateTime.of(2020, 1, 1, 0, 0),
        end1 = LocalDateTime.of(2021, 1, 1, 0, 0),
        start2 = LocalDateTime.of(2021, 1, 1, 0, 0),
        end2 = LocalDateTime.of(2022, 1, 1, 0, 0);
System.out.println(Period.between(start1.toLocalDate(), end1.toLocalDate()));
System.out.println(Duration.between(start1, end1).toDays());
System.out.println(Period.between(start2.toLocalDate(), end2.toLocalDate()));
System.out.println(Duration.between(start2, end2).toDays());
P1Y
366
P1Y
365

Android Studio emulator does not come with Play Store for API 23

Go to http://opengapps.org/ and download the pico version of your platform and android version. Unzip the downloaded folder to get
1. GmsCore.apk
2. GoogleServicesFramework.apk
3. GoogleLoginService.apk
4. Phonesky.apk

Then, locate your emulator.exe. You will probably find it in
C:\Users\<YOUR_USER_NAME>\AppData\Local\Android\sdk\tools

Run the command:
emulator -avd <YOUR_EMULATOR'S_NAME> -netdelay none -netspeed full -no-boot-anim -writable-system

Note: Use -writable-system to start your emulator with writable system image.

Then,
adb root
adb remount
adb push <PATH_TO GmsCore.apk> /system/priv-app
adb push <PATH_TO GoogleServicesFramework.apk> /system/priv-app
adb push <PATH_TO GoogleLoginService.apk> /system/priv-app
adb push <PATH_TO Phonesky.apk> /system/priv-app

Then, reboot the emulator
adb shell stop
adb shell start

To verify run,
adb shell pm list packages and you will find com.google.android.gms package for google

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.

I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.

What is the use of hashCode in Java?

The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal.

By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.

This answer is from the java SE 8 official tutorial documentation

Popup window in PHP?

if (isset($_POST['Register']))
    {
        $ErrorArrays = array (); //Empty array for input errors 

        $Input_Username = $_POST['Username'];
        $Input_Password = $_POST['Password'];
        $Input_Confirm = $_POST['ConfirmPass'];
        $Input_Email = $_POST['Email'];

        if (empty($Input_Username))
        {
            $ErrorArrays[] = "Username Is Empty";
        }
        if (empty($Input_Password))
        {
            $ErrorArrays[] = "Password Is Empty";
        }
        if ($Input_Password !== $Input_Confirm)
        {
            $ErrorArrays[] = "Passwords Do Not Match!";
        }
        if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
        {
            $ErrorArrays[] = "Incorrect Email Formatting";
        }

        if (count($ErrorArrays) == 0)
        {
            // No Errors
        }
        else
        {
            foreach ($ErrorArrays AS $Errors)
            {
                echo "<font color='red'><b>".$Errors."</font></b><br>";
            }
        }
    }

?>

    <form method="POST"> 
        Username: <input type='text' name='Username'> <br>
        Password: <input type='password' name='Password'><br>
        Confirm Password: <input type='password' name='ConfirmPass'><br>
        Email: <input type='text' name='Email'> <br><br>

        <input type='submit' name='Register' value='Register'>


    </form> 

This is a very basic PHP Form validation. This could be put in a try block, but for basic reference, I see this fit following our conversation in the comment box.

What this script will do, is process each of the post elements, and act accordingly, for example:

    if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
        {
            $ErrorArrays[] = "Incorrect Email Formatting";
        }

This will check:

if $Input_Email is not a valid email. If this is not a valid E-mail, then a message will get added to a empty array.

Further down the script, you will see:

    if (count($ErrorArrays) == 0)
    {
        // No Errors
    }
    else
    {
        foreach ($ErrorArrays AS $Errors)
        {
            echo "<font color='red'><b>".$Errors."</font></b><br>";
        }
    }

Basically. if the array count is not 0, errors have been found. Then the script will print out the errors.

Remember, this is a reference based on our conversation in the comment box, and should be used as such.

SQL Server dynamic PIVOT query?

Dynamic SQL PIVOT:

create table temp
(
    date datetime,
    category varchar(3),
    amount money
)

insert into temp values ('1/1/2012', 'ABC', 1000.00)
insert into temp values ('2/1/2012', 'DEF', 500.00)
insert into temp values ('2/1/2012', 'GHI', 800.00)
insert into temp values ('2/10/2012', 'DEF', 700.00)
insert into temp values ('3/1/2012', 'ABC', 1100.00)


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.category) 
            FROM temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT date, ' + @cols + ' from 
            (
                select date
                    , amount
                    , category
                from temp
           ) x
            pivot 
            (
                 max(amount)
                for category in (' + @cols + ')
            ) p '


execute(@query)

drop table temp

Results:

Date                        ABC         DEF    GHI
2012-01-01 00:00:00.000     1000.00     NULL    NULL
2012-02-01 00:00:00.000     NULL        500.00  800.00
2012-02-10 00:00:00.000     NULL        700.00  NULL
2012-03-01 00:00:00.000     1100.00     NULL    NULL

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

I know this ticket is old, but I just ran into this issue and I thought I would post what was happening to me and how I resolved it:

In my service I was calling there was a call to another web service. Like a goof, I forgot to make sure that the DNS settings were correct when I published the web service, thus my web service, when published, was trying to call from api.myproductionserver.local, rather than api.myproductionserver.com. It was the backend web service that was causing the timeout.

Anyways, I thought I would pass this along.

What is the most elegant way to check if all values in a boolean array are true?

I can't believe there's no BitSet solution.

A BitSet is an abstraction over a set of bits so we don't have to use boolean[] for more advanced interactions anymore, because it already contains most of the needed methods. It's also pretty fast in batch operations since it internally uses long values to store the bits and doesn't therefore check every bit separately like we do with boolean[].

BitSet myBitSet = new BitSet(10);
// fills the bitset with ten true values
myBitSet.set(0, 10);

For your particular case, I'd use cardinality():

if (myBitSet.cardinality() == myBitSet.size()) {
    // do something, there are no false bits in the bitset
}

Another alternative is using Guava:

return Booleans.contains(myArray, true);

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

Preventing console window from closing on Visual Studio C/C++ Console application

In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to "Console (/SUBSYSTEM:CONSOLE)" under Configuration Properties.

  1. Go to "View" then select "Property Manager"
  2. Right click on the project/solution and select "Property". This opens a Test property page
  3. Navigate to the linker then select "System"
  4. Click on "SubSystem" and a drop down appears
  5. Choose "Console (/SUBSYSTEM:CONSOLE)"
  6. Apply and save
  7. The next time you run your code with "CTRL +F5", you should see the output.

Calculate correlation with cor(), only for numerical columns

if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:

set.seed(10)

x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]

cor(x)

Error in cor(x) : 'x' must be numeric

but

cor(x[sapply(x, is.numeric)])

             V1         V2          V3          V4          V5          V6          V7
V1   1.00000000  0.3025766 -0.22473884 -0.72468776  0.18890578  0.14466161  0.05325308
V2   0.30257657  1.0000000 -0.27871430 -0.29075170  0.16095258  0.10538468 -0.15008158
V3  -0.22473884 -0.2787143  1.00000000 -0.22644156  0.07276013 -0.35725182 -0.05859479
V4  -0.72468776 -0.2907517 -0.22644156  1.00000000 -0.19305921  0.16948333 -0.01025698
V5   0.18890578  0.1609526  0.07276013 -0.19305921  1.00000000  0.07339531 -0.31837954
V6   0.14466161  0.1053847 -0.35725182  0.16948333  0.07339531  1.00000000  0.02514081
V7   0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954  0.02514081  1.00000000
V8   0.44705527  0.1698571  0.39970105 -0.42461411  0.63951574  0.23065830 -0.28967977
V9   0.21006372 -0.4418132 -0.18623823 -0.25272860  0.15921890  0.36182579 -0.18437981
V10  0.02326108  0.4618036 -0.25205899 -0.05117037  0.02408278  0.47630138 -0.38592733
              V8           V9         V10
V1   0.447055266  0.210063724  0.02326108
V2   0.169857120 -0.441813231  0.46180357
V3   0.399701054 -0.186238233 -0.25205899
V4  -0.424614107 -0.252728595 -0.05117037
V5   0.639515737  0.159218895  0.02408278
V6   0.230658298  0.361825786  0.47630138
V7  -0.289679766 -0.184379813 -0.38592733
V8   1.000000000  0.001023392  0.11436143
V9   0.001023392  1.000000000  0.15301699
V10  0.114361431  0.153016985  1.00000000

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

This happened to me because I was using:

app.datasource.url=jdbc:mysql://localhost/test

When I replaced url by jdbc-url then it worked:

app.datasource.jdbc-url=jdbc:mysql://localhost/test

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Your Event.hbm.xml says:

<set name="attendees" cascade="all">
    <key column="attendeeId" />
    <one-to-many class="Attendee" />
</set>

In plain english, this means that the column Attendee.attendeeId is the foreign key for the association attendees and points to the primary key of Event.

When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.

Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.

Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event-end as inverse.

How do I put two increment statements in a C++ 'for' loop?

Try not to do it!

From http://www.research.att.com/~bs/JSF-AV-rules.pdf:

AV Rule 199
The increment expression in a for loop will perform no action other than to change a single loop parameter to the next value for the loop.

Rationale: Readability.

Make an image width 100% of parent div, but not bigger than its own width

If the image is smaller than parent...

.img_100 {
  width: 100%;
}

Getting DOM elements by classname

I think the accepted way is better, but I guess this might work as well

function getElementByClass(&$parentNode, $tagName, $className, $offset = 0) {
    $response = false;

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    $tagCount = 0;
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            if ($tagCount == $offset) {
                $response = $temp;
                break;
            }

            $tagCount++;
        }

    }

    return $response;
}

Converting an int or String to a char array on Arduino

  1. To convert and append an integer, use operator += (or member function concat):

    String stringOne = "A long integer: ";
    stringOne += 123456789;
    
  2. To get the string as type char[], use toCharArray():

    char charBuf[50];
    stringOne.toCharArray(charBuf, 50)
    

In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.

Overhead

The cost of bringing in String (it is not included if not used anywhere in the sketch), is approximately 1212 bytes program memory (flash) and 48 bytes RAM.

This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.

Split a string by another string in C#

The easiest way is to use String.Replace:

string myString = "THExxQUICKxxBROWNxxFOX";
mystring = mystring.Replace("xx", ", ");

Or more simply:

string myString = "THExxQUICKxxBROWNxxFOX".Replace("xx", ", ");

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

You can easily define such function and use it then:

ifnull <- function(x,y) {
  if(is.na(x)==TRUE) 
    return (y)
  else 
    return (x);
}

or same minified version:

ifnull <- function(x,y) {if(is.na(x)==TRUE) return (y) else return (x);}

Maven version with a property

If you have a parent project you can set the version in the parent pom and in the children you can reference sibling libs with the ${project.version} or ${version} properties.

If you want to avoid to repeat the version of the parent in each children: you can do this:

<modelVersion>4.0.0</modelVersion>
<groupId>company</groupId>
<artifactId>build.parent</artifactId>
<version>${my.version}</version>
<packaging>pom</packaging>

<properties>
<my.version>1.1.2-SNAPSHOT</my.version>
</properties>

And then in your children pom you have to do:

    <parent>
      <artifactId>build.parent</artifactId>
      <groupId>company</groupId>
      <relativePath>../build.parent/pom.xml</relativePath>
      <version>${my.version}</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>company</groupId>
    <artifactId>artifact</artifactId>
    <packaging>eclipse-plugin</packaging>

    <dependencies>
        <dependency> 
           <groupId>company</groupId>
           <artifactId>otherartifact</artifactId>   
           <version>${my.version}</version>
or
           <version>${project.version}</version>
        </dependency>
    </dependencies>

hth

How to add browse file button to Windows Form using C#

These links explain it with examples

http://dotnetperls.com/openfiledialog

http://www.geekpedia.com/tutorial67_Using-OpenFileDialog-to-open-files.html

private void button1_Click(object sender, EventArgs e)
{
    int size = -1;
    DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
    if (result == DialogResult.OK) // Test result.
    {
       string file = openFileDialog1.FileName;
       try
       {
          string text = File.ReadAllText(file);
          size = text.Length;
       }
       catch (IOException)
       {
       }
    }
    Console.WriteLine(size); // <-- Shows file size in debugging mode.
    Console.WriteLine(result); // <-- For debugging use.
}

How do I enable saving of filled-in fields on a PDF form?

When you use Acrobat 8, or 9, select "enable usage rights" from the Advanced menu. This adds about 20 kb to the pdf.

The other possibility is to use CutePDF Pro, add a submit button and have the XFDF data submitted to your self as an email or to a web server. The XFDF data can then reload the original PDF with your data.

How to sum data.frame column values?

To sum values in data.frame you first need to extract them as a vector.

There are several way to do it:

# $ operatior
x <- people$Weight
x
# [1] 65 70 64

Or using [, ] similar to matrix:

x <- people[, 'Weight']
x
# [1] 65 70 64

Once you have the vector you can use any vector-to-scalar function to aggregate the result:

sum(people[, 'Weight'])
# [1] 199

If you have NA values in your data, you should specify na.rm parameter:

sum(people[, 'Weight'], na.rm = TRUE)

How do I draw a grid onto a plot in Python?

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

How to add,set and get Header in request of HttpClient?

On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

You have something like this:

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
    .setParameter("q", "httpclient")
    .setParameter("btnG", "Google Search")
    .setParameter("aq", "f")
    .setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

How can I determine whether a specific file is open in Windows?

There is a program "OpenFiles", seems to be part of windows 7. Seems that it can do what you want. It can list files opened by remote users (through file share) and, after calling "openfiles /Local on" and a system restart, it should be able to show files opened locally. The latter is said to have performance penalties.

sqlite copy data from one table to another

I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:

create table destination_old as select * from destination;

drop table destination;

create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;

It's safe because you have a copy of destination before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.

Using the pattern above you end up with two country fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old and perhaps using coalesce to retrieve the values from destination_old if the country field in source is null. So for example:

create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;

What is object slicing?

"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away.

For example,

class A {
   int foo;
};

class B : public A {
   int bar;
};

So an object of type B has two data members, foo and bar.

Then if you were to write this:

B b;

A a = b;

Then the information in b about member bar is lost in a.

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

How to restart a single container with docker-compose

Restart container

If you want to just restart your container:

docker-compose restart servicename

Think of this command as "just restart the container by its name", which is equivalent to docker restart command.

Note caveats:

  1. If you changed ENV variables they won't updated in container. You need to stop it and start again. Or, using single command docker-compose up will detect changes and recreate container.

  2. As many others mentioned, if you changed docker-compose.yml file itself, simple restart won't apply those changes.

  3. If you copy your code inside container at the build stage (in Dockerfile using ADD or COPY commands), every time the code changes you have to rebuild the container (docker-compose build).

Correlation to your code

docker-compose restart should work perfectly fine, if your code gets path mapped into the container by volume directive in docker-compose.yml like so:

services:

  servicename:
    volumes:
      - .:/code

But I'd recommend to use live code reloading, which is probably provided by your framework of choice in DEBUG mode (alternatively, you can search for auto-reload packages in your language of choice). Adding this should eliminate the need to restart container every time after your code changes, instead reloading the process inside.

What is the height of Navigation Bar in iOS 7?

There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.

Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/

Align printf output in Java

A simple solution that springs to mind is to have a String block of spaces:

String indent = "                  "; // 20 spaces.

When printing out a string, compute the actual indent and add it to the end:

String output = "Newspaper";
output += indent.substring(0, indent.length - output.length);

This will mediate the number of spaces to the string, and put them all in the same column.

How to create multiple page app using react

(Make sure to install react-router using npm!)

To use react-router, you do the following:

  1. Create a file with routes defined using Route, IndexRoute components

  2. Inject the Router (with 'r'!) component as the top-level component for your app, passing the routes defined in the routes file and a type of history (hashHistory, browserHistory)

  3. Add {this.props.children} to make sure new pages will be rendered there
  4. Use the Link component to change pages

Step 1 routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';

/**
 * Import all page components here
 */
import App from './components/App';
import MainPage from './components/MainPage';
import SomePage from './components/SomePage';
import SomeOtherPage from './components/SomeOtherPage';

/**
 * All routes go here.
 * Don't forget to import the components above after adding new route.
 */
export default (
  <Route path="/" component={App}>
    <IndexRoute component={MainPage} />
    <Route path="/some/where" component={SomePage} />
    <Route path="/some/otherpage" component={SomeOtherPage} />
  </Route>
);

Step 2 entry point (where you do your DOM injection)

// You can choose your kind of history here (e.g. browserHistory)
import { Router, hashHistory as history } from 'react-router';
// Your routes.js file
import routes from './routes';

ReactDOM.render(
  <Router routes={routes} history={history} />,
  document.getElementById('your-app')
);

Step 3 The App component (props.children)

In the render for your App component, add {this.props.children}:

render() {
  return (
    <div>
      <header>
        This is my website!
      </header>

      <main>
        {this.props.children}
      </main>

      <footer>
        Your copyright message
      </footer>
    </div>
  );
}

Step 4 Use Link for navigation

Anywhere in your component render function's return JSX value, use the Link component:

import { Link } from 'react-router';
(...)
<Link to="/some/where">Click me</Link>

How to install JDK 11 under Ubuntu?

I came here looking for the answer and since no one put the command for the oracle Java 11 but only openjava 11 I figured out how to do it on Ubuntu, the syntax is as following:

sudo add-apt-repository ppa:linuxuprising/java
sudo apt update
sudo apt install oracle-java11-installer

Why in C++ do we use DWORD rather than unsigned int?

DWORD is not a C++ type, it's defined in <windows.h>.

The reason is that DWORD has a specific range and format Windows functions rely on, so if you require that specific range use that type. (Or as they say "When in Rome, do as the Romans do.") For you, that happens to correspond to unsigned int, but that might not always be the case. To be safe, use DWORD when a DWORD is expected, regardless of what it may actually be.

For example, if they ever changed the range or format of unsigned int they could use a different type to underly DWORD to keep the same requirements, and all code using DWORD would be none-the-wiser. (Likewise, they could decide DWORD needs to be unsigned long long, change it, and all code using DWORD would be none-the-wiser.)


Also note unsigned int does not necessary have the range 0 to 4,294,967,295. See here.

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

It seems like it exists a bug in jQuery reported here : http://bugs.jquery.com/ticket/13183 that breaks the Fancybox script.

Also check https://github.com/fancyapps/fancyBox/issues/485 for further reference.

As a workaround, rollback to jQuery v1.8.3 while either the jQuery bug is fixed or Fancybox is patched.


UPDATE (Jan 16, 2013): Fancybox v2.1.4 has been released and now it works fine with jQuery v1.9.0.

For fancybox v1.3.4- you still need to rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.


UPDATE (Jan 17, 2013): Workaround for users of Fancybox v1.3.4 :

Patch the fancybox js file to make it work with jQuery v1.9.0 as follow :

  1. Open the jquery.fancybox-1.3.4.js file (full version, not pack version) with a text/html editor.
  2. Find around the line 29 where it says :

    isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
    

    and replace it by (EDITED March 19, 2013: more accurate filter):

    isIE6 = navigator.userAgent.match(/msie [6]/i) && !window.XMLHttpRequest,
    

    UPDATE (March 19, 2013): Also replace $.browser.msie by navigator.userAgent.match(/msie [6]/i) around line 615 (and/or replace all $.browser.msie instances, if any), thanks joofow ... that's it!

Or download the already patched version from HERE (UPDATED March 19, 2013 ... thanks fairylee for pointing out the extra closing bracket)

NOTE: this is an unofficial patch and is unsupported by Fancybox's author, however it works as is. You may use it at your own risk ;)

Optionally, you may rather rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.

Regex matching beginning AND end strings

\bdbo\..*fn

I was looking through a ton of java code for a specific library: car.csclh.server.isr.businesslogic.TypePlatform (although I only knew car and Platform at the time). Unfortunately, none of the other suggestions here worked for me, so I figured I'd post this.

Here's the regex I used to find it:

\bcar\..*Platform

How do I call paint event?

I found the Invalidate() creating too much of flickering. Here's my situation. A custom control I am developing draws its whole contents via handling the Paint event.

this.Paint += this.OnPaint;

This handler calls a custom routine that does the actual painting.

private void OnPaint(object sender, PaintEventArgs e)
{
    this.DrawFrame(e.Graphics);
}

To simulate scrolling I want to repaint my control every time the cursor moves while the left mouse button is pressed. My first choice was using the Invalidate() like the following.

private void RedrawFrame()
{
    var r = new Rectangle(
        0, 0, this.Width, this.Height);

    this.Invalidate(r);
    this.Update();
}

The control scrolls OK but flickers far beyond any comfortable level. So I decided, instead of repainting the control, to call my custom DrawFrame() method directly after handling the MouseMove event. That produced a smooth scrolling with no flickering.

private void RedrawFrame()
{
    var g = Graphics.FromHwnd(this.Handle);
    this.DrawFrame(g);
}

This approach may not be applicable to all situations, but so far it suits me well.

Close/kill the session when the browser or tab is closed

Not perfect but best solution for now :

var spcKey = false;
var hover = true;
var contextMenu = false;

function spc(e) {
    return ((e.altKey || e.ctrlKey || e.keyCode == 91 || e.keyCode==87) && e.keyCode!=82 && e.keyCode!=116);
}

$(document).hover(function () {
    hover = true;
    contextMenu = false;
    spcKey = false;
}, function () {
    hover = false;
}).keydown(function (e) {
    if (spc(e) == false) {
        hover = true;
        spcKey = false;
    }
    else {
        spcKey = true;
    }
}).keyup(function (e) {
    if (spc(e)) {
        spcKey = false;
    }
}).contextmenu(function (e) {
    contextMenu = true;
}).click(function () {
    hover = true;
    contextMenu = false;
});

window.addEventListener('focus', function () {
    spcKey = false;
});
window.addEventListener('blur', function () {
    hover = false;
});

window.onbeforeunload = function (e) {
    if ((hover == false || spcKey == true) && contextMenu==false) {
        window.setTimeout(goToLoginPage, 100);
        $.ajax({
            url: "/Account/Logoff",
            type: 'post',
            data: $("#logoutForm").serialize(),
        });
        return "Oturumunuz kapatildi.";
    }
    return;
};

function goToLoginPage() {
    hover = true;
    spcKey = false;
    contextMenu = false;
    location.href = "/Account/Login";
}

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

Is either GET or POST more secure than the other?

The notion of security is meaningless unless you define what it is that you want to be secure against.

If you want to be secure against stored browser history, some types of logging, and people looking at your URLs, then POST is more secure.

If you want to be secure against somebody sniffing your network activity, then there's no difference.

Set default value of javascript object attributes

I came here looking for a solution because the header matched my problem description but it isn't what i was looking for but i got a solution to my problem(I wanted to have a default value for an attribute which would be dynamic something like date).

let Blog = {
title  : String,
image  : String,
body   : String,
created: {type: Date, default: Date.now}
}

The above code was the solution for which i finally settled.

CakePHP select default value in SELECT input

The best answer to this could be

Don't use selct for this job use input instead

like this

echo  $this->Form->input('field_name', array(
          'type' => 'select',
            'options' => $options_arr, 
            'label' => 'label here',
            'value' => $id,  // default value
            'escape' => false,  // prevent HTML being automatically escaped
            'error' => false,
            'class' => 'form-control' // custom class you want to enter
        ));

Hope it helps.

Explicitly calling return in a function or not

I think of return as a trick. As a general rule, the value of the last expression evaluated in a function becomes the function's value -- and this general pattern is found in many places. All of the following evaluate to 3:

local({
1
2
3
})

eval(expression({
1
2
3
}))

(function() {
1
2
3
})()

What return does is not really returning a value (this is done with or without it) but "breaking out" of the function in an irregular way. In that sense, it is the closest equivalent of GOTO statement in R (there are also break and next). I use return very rarely and never at the end of a function.

 if(a) {
   return(a)
 } else {
   return(b)
 }

... this can be rewritten as if(a) a else b which is much better readable and less curly-bracketish. No need for return at all here. My prototypical case of use of "return" would be something like ...

ugly <- function(species, x, y){
   if(length(species)>1) stop("First argument is too long.")
   if(species=="Mickey Mouse") return("You're kidding!")
   ### do some calculations 
   if(grepl("mouse", species)) {
      ## do some more calculations
      if(species=="Dormouse") return(paste0("You're sleeping until", x+y))
      ## do some more calculations
      return(paste0("You're a mouse and will be eating for ", x^y, " more minutes."))
      }
   ## some more ugly conditions
   # ...
   ### finally
   return("The end")
   }

Generally, the need for many return's suggests that the problem is either ugly or badly structured.

[EDIT]

return doesn't really need a function to work: you can use it to break out of a set of expressions to be evaluated.

getout <- TRUE 
# if getout==TRUE then the value of EXP, LOC, and FUN will be "OUTTA HERE"
# .... if getout==FALSE then it will be `3` for all these variables    

EXP <- eval(expression({
   1
   2
   if(getout) return("OUTTA HERE")
   3
   }))

LOC <- local({
   1
   2
   if(getout) return("OUTTA HERE")
   3
   })

FUN <- (function(){
   1
   2
   if(getout) return("OUTTA HERE")
   3
   })()

identical(EXP,LOC)
identical(EXP,FUN)

How to pass data in the ajax DELETE request other than headers

deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
    $.ajax({
        url: urlCall,
        type: 'DELETE',
        data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
        success: callback || $.noop,
        error: errorCallback || $.noop
    });
}

Note: the use of headers was introduced in JQuery 1.5.:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

how to convert from int to char*?

I think you can use a sprintf :

int number = 33;
char* numberstring[(((sizeof number) * CHAR_BIT) + 2)/3 + 2];
sprintf(numberstring, "%d", number);

Java - get pixel array from image

I was just playing around with this same subject, which is the fastest way to access the pixels. I currently know of two ways for doing this:

  1. Using BufferedImage's getRGB() method as described in @tskuzzy's answer.
  2. By accessing the pixels array directly using:

    byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
    

If you are working with large images and performance is an issue, the first method is absolutely not the way to go. The getRGB() method combines the alpha, red, green and blue values into one int and then returns the result, which in most cases you'll do the reverse to get these values back.

The second method will return the red, green and blue values directly for each pixel, and if there is an alpha channel it will add the alpha value. Using this method is harder in terms of calculating indices, but is much faster than the first approach.

In my application I was able to reduce the time of processing the pixels by more than 90% by just switching from the first approach to the second!

Here is a comparison I've setup to compare the two approaches:

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import javax.imageio.ImageIO;

public class PerformanceTest {

   public static void main(String[] args) throws IOException {

      BufferedImage hugeImage = ImageIO.read(PerformanceTest.class.getResource("12000X12000.jpg"));

      System.out.println("Testing convertTo2DUsingGetRGB:");
      for (int i = 0; i < 10; i++) {
         long startTime = System.nanoTime();
         int[][] result = convertTo2DUsingGetRGB(hugeImage);
         long endTime = System.nanoTime();
         System.out.println(String.format("%-2d: %s", (i + 1), toString(endTime - startTime)));
      }

      System.out.println("");

      System.out.println("Testing convertTo2DWithoutUsingGetRGB:");
      for (int i = 0; i < 10; i++) {
         long startTime = System.nanoTime();
         int[][] result = convertTo2DWithoutUsingGetRGB(hugeImage);
         long endTime = System.nanoTime();
         System.out.println(String.format("%-2d: %s", (i + 1), toString(endTime - startTime)));
      }
   }

   private static int[][] convertTo2DUsingGetRGB(BufferedImage image) {
      int width = image.getWidth();
      int height = image.getHeight();
      int[][] result = new int[height][width];

      for (int row = 0; row < height; row++) {
         for (int col = 0; col < width; col++) {
            result[row][col] = image.getRGB(col, row);
         }
      }

      return result;
   }

   private static int[][] convertTo2DWithoutUsingGetRGB(BufferedImage image) {

      final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
      final int width = image.getWidth();
      final int height = image.getHeight();
      final boolean hasAlphaChannel = image.getAlphaRaster() != null;

      int[][] result = new int[height][width];
      if (hasAlphaChannel) {
         final int pixelLength = 4;
         for (int pixel = 0, row = 0, col = 0; pixel + 3 < pixels.length; pixel += pixelLength) {
            int argb = 0;
            argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
            argb += ((int) pixels[pixel + 1] & 0xff); // blue
            argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
            argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
            result[row][col] = argb;
            col++;
            if (col == width) {
               col = 0;
               row++;
            }
         }
      } else {
         final int pixelLength = 3;
         for (int pixel = 0, row = 0, col = 0; pixel + 2 < pixels.length; pixel += pixelLength) {
            int argb = 0;
            argb += -16777216; // 255 alpha
            argb += ((int) pixels[pixel] & 0xff); // blue
            argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
            argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
            result[row][col] = argb;
            col++;
            if (col == width) {
               col = 0;
               row++;
            }
         }
      }

      return result;
   }

   private static String toString(long nanoSecs) {
      int minutes    = (int) (nanoSecs / 60000000000.0);
      int seconds    = (int) (nanoSecs / 1000000000.0)  - (minutes * 60);
      int millisecs  = (int) ( ((nanoSecs / 1000000000.0) - (seconds + minutes * 60)) * 1000);


      if (minutes == 0 && seconds == 0)
         return millisecs + "ms";
      else if (minutes == 0 && millisecs == 0)
         return seconds + "s";
      else if (seconds == 0 && millisecs == 0)
         return minutes + "min";
      else if (minutes == 0)
         return seconds + "s " + millisecs + "ms";
      else if (seconds == 0)
         return minutes + "min " + millisecs + "ms";
      else if (millisecs == 0)
         return minutes + "min " + seconds + "s";

      return minutes + "min " + seconds + "s " + millisecs + "ms";
   }
}

Can you guess the output? ;)

Testing convertTo2DUsingGetRGB:
1 : 16s 911ms
2 : 16s 730ms
3 : 16s 512ms
4 : 16s 476ms
5 : 16s 503ms
6 : 16s 683ms
7 : 16s 477ms
8 : 16s 373ms
9 : 16s 367ms
10: 16s 446ms

Testing convertTo2DWithoutUsingGetRGB:
1 : 1s 487ms
2 : 1s 940ms
3 : 1s 785ms
4 : 1s 848ms
5 : 1s 624ms
6 : 2s 13ms
7 : 1s 968ms
8 : 1s 864ms
9 : 1s 673ms
10: 2s 86ms

BUILD SUCCESSFUL (total time: 3 minutes 10 seconds)

What's the fastest way to delete a large folder in Windows?

Try Shift + Delete. Did 24.000 files in 2 minutes for me.

How to obtain image size using standard Python class (without using external library)?

Here's a python 3 script that returns a tuple containing an image height and width for .png, .gif and .jpeg without using any external libraries (ie what Kurt McKee referenced above). Should be relatively easy to transfer it to Python 2.

import struct
import imghdr

def get_image_size(fname):
    '''Determine the image type of fhandle and return its size.
    from draco'''
    with open(fname, 'rb') as fhandle:
        head = fhandle.read(24)
        if len(head) != 24:
            return
        if imghdr.what(fname) == 'png':
            check = struct.unpack('>i', head[4:8])[0]
            if check != 0x0d0a1a0a:
                return
            width, height = struct.unpack('>ii', head[16:24])
        elif imghdr.what(fname) == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        elif imghdr.what(fname) == 'jpeg':
            try:
                fhandle.seek(0) # Read 0xff next
                size = 2
                ftype = 0
                while not 0xc0 <= ftype <= 0xcf:
                    fhandle.seek(size, 1)
                    byte = fhandle.read(1)
                    while ord(byte) == 0xff:
                        byte = fhandle.read(1)
                    ftype = ord(byte)
                    size = struct.unpack('>H', fhandle.read(2))[0] - 2
                # We are at a SOFn block
                fhandle.seek(1, 1)  # Skip `precision' byte.
                height, width = struct.unpack('>HH', fhandle.read(4))
            except Exception: #IGNORE:W0703
                return
        else:
            return
        return width, height

How to change FontSize By JavaScript?

span.style.fontSize = "25px";

use this

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

I have same problem and I fixed this issue by following steps:

  • Operating system : ubuntu 12.04
  • lamp installed
  • suppose your directory to save output file is : /var/www/csv/

Execute following command on terminal and edit this file using gedit editor to add your directory to output file.

sudo gedit /etc/apparmor.d/usr.sbin.mysqld

  • now file would be opened in editor please add your directory there

    /var/www/csv/* rw,

  • likewise I have added in my file, as following given image :

enter image description here

Execute next command to restart services :

sudo /etc/init.d/apparmor restart

For example I execute following query into phpmyadmin query builder to output data in csv file

SELECT colName1, colName2,colName3
INTO OUTFILE '/var/www/csv/OUTFILE.csv'
FIELDS TERMINATED BY ','
FROM tableName;

It successfully done and write all rows with selected columns into OUTPUT.csv file...

How can I trigger a Bootstrap modal programmatically?

HTML

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

JS

$('button').click(function(){
$('#myModal').modal('show');
});

DEMO JSFIDDLE

How can I switch my signed in user in Visual Studio 2013?

Start Visual Studio Tools -> Import and Export Settings -> Export selected environment settings You need to be really quick to navigate the menu before Licensing pop-up appears, (this step is optional: worst case scenario you would have to restore all the settings manually). Once in "Import and Export Settings" dialogue you can relax.

Exit Visual Studio.

From the command prompt run: devenv /resetuserdata for the particular Visual Studio version.

Safest way is to right-click on the shortcut -> Properties -> Shortcut -> Target -> copy. Final command should look something like:

"C:\Program Files (x86)\Microsoft Visual Studio NN.N\Common7\IDE\devenv.exe" /resetuserdata

Go through log-in and initial settings.

Tools -> Import and Export Settings -> Import selected environment settings to restore your original settings.

This worked when the error:

We were unable to establish the connection because it is configured for user email@address but you attempted to connect using user email@address. To connect as a different user perform a switch user operation. To connect with the configured identity just attempt the last operation again.

...has both instances of email@address identical.

What do *args and **kwargs mean?

Notice the cool thing in S.Lott's comment - you can also call functions with *mylist and **mydict to unpack positional and keyword arguments:

def foo(a, b, c, d):
  print a, b, c, d

l = [0, 1]
d = {"d":3, "c":2}

foo(*l, **d)

Will print: 0 1 2 3

Time complexity of Euclid's Algorithm

There's a great look at this on the wikipedia article.

It even has a nice plot of complexity for value pairs.

It is not O(a%b).

It is known (see article) that it will never take more steps than five times the number of digits in the smaller number. So the max number of steps grows as the number of digits (ln b). The cost of each step also grows as the number of digits, so the complexity is bound by O(ln^2 b) where b is the smaller number. That's an upper limit, and the actual time is usually less.

Incrementing a variable inside a Bash loop

while read -r country _; do
  if [[ $country = 'US' ]]; then
    ((USCOUNTER++))
    echo "US counter $USCOUNTER"
  fi
done < "$FILE"

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

read.table wants to return a data.frame, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE ) to fill in the blanks.

e.g.

read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
#        V1       V2       V3
#1 Element1 Element2         
#2 Element5 Element6 Element7

A note on whether or not to set header = FALSE... read.table tries to automatically determine if you have a header row thus:

header is set to TRUE if and only if the first row contains one fewer field than the number of columns

Unrecognized SSL message, plaintext connection? Exception

Adding this as an answer as it might help someone later.

I had to force jvm to use the IPv4 stack to resolve the error. My application used to work within company network, but while connecting from home it gave the same exception. No proxy involved. Added the jvm argument -Djava.net.preferIPv4Stack=true and all the https requests were behaving normally.

How to remove trailing whitespaces with sed?

To only strip whitespaces (in my case spaces and tabs) from lines with at least one non-whitespace character (this way empty indented lines are not touched):

sed -i -r 's/([^ \t]+)[ \t]+$/\1/' "$file"

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

Try this

SELECT t1.*
FROM 
 some_table t1,
  (SELECT relevant_field
  FROM some_table
  GROUP BY relevant_field
  HAVING COUNT (*) > 1) t2
WHERE
 t1.relevant_field = t2.relevant_field;

Is there a way to perform "if" in python's lambda

Lambdas in Python are fairly restrictive with regard to what you're allowed to use. Specifically, you can't have any keywords (except for operators like and, not, or, etc) in their body.

So, there's no way you could use a lambda for your example (because you can't use raise), but if you're willing to concede on that… You could use:

f = lambda x: x == 2 and x or None

Run JavaScript when an element loses focus

onblur is the opposite of onfocus.

Clear form fields with jQuery

Simple but works like a charm.

$("#form").trigger('reset'); //jquery
document.getElementById("myform").reset(); //native JS

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

I've been strugglin with this problem for hours till found this post. Just like @ligi said, some people have two SDK folders (Android Studio, which is bundled and Eclipse). The problem is that it doesn't matter if you downloaded the Google Play Services library on both SDK folders, your ANDROID_HOME enviroment variable must be pointing to the SDK folder used by the Android Studio.

SDK Folder A  (Used on Eclipse)
SDK Folder B  (Used on AS)

ANDROID_HOME=<path to SDK Folder B>

After change the path of this variable the error was gone.

How to post data in PHP using file_get_contents?

Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.


There's an example given in the PHP manual, at this page : HTTP context options (quoting) :

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents -- nothing more ;-)


As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...

What is System, out, println in System.out.println() in Java

System is a final class from the java.lang package.

out is a class variable of type PrintStream declared in the System class.

println is a method of the PrintStream class.

How do I create a MessageBox in C#?

Also you can use a MessageBox with OKCancel options, but it requires many codes. The if block is for OK, the else block is for Cancel. Here is the code:

if (MessageBox.Show("Are you sure you want to do this?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
    MessageBox.Show("You pressed OK!");
}
else
{
    MessageBox.Show("You pressed Cancel!");
}

You can also use a MessageBox with YesNo options:

if (MessageBox.Show("Are you sure want to doing this?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    MessageBox.Show("You are pressed Yes!");
}
else
{
    MessageBox.Show("You are pressed No!");
}

VIM Disable Automatic Newline At End Of File

I think I've found a better solution than the accepted answer. The alternative solutions weren't working for me and I didn't want to have to work in binary mode all the time. Fortunately this seems to get the job done and I haven't encountered any nasty side-effects yet: preserve missing end-of-line at end of text files. I just added the whole thing to my ~/.vimrc.

How to compare DateTime in C#?

If you have two DateTime that looks the same, but Compare or Equals doesn't return what you expect, this is how to compare them.

Here an example with 1-millisecond precision:

bool areSame = (date1 - date2) > TimeSpan.FromMilliseconds(1d);

Tool to monitor HTTP, TCP, etc. Web Service traffic

JMeter's built-in proxy may be used to record all HTTP request/response information.

Firefox "Live HTTP headers" plugin may be used to see what is happening on the browser side when sending/receiving request.

Firefox "Tamper data" plugin may be useful when you need to intercept and modify request.

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

I hit the same shared memory realm does not exist symptom (on Windows) but for a different reason. I had just installed Oracle (XE) and after some troubleshooting, established that my installation was corrupt due to the presence of an ORACLE_HOME environment property at the time I installed it.

If this is TLDR, skip to 'So to resolve:'!

My initial symptom was:

Message 850 not found; No message file for product=NETWORK, facility=NL

Apparently the Windows install reads the ORACLE_HOME from the registry and doesn't need (and certainly in my case shouldn't have...) an environment property.

Remove it, as follows:

  1. Edit the system environment settings (Windows key and start typing 'env' and you should see this option come up.
  2. Delete any User and System Environment Variables called ORACLE_HOME, if present. (make a note of their values, mainly out of interest, but may be of use if you want to put them back for some reason!)
  3. Restart your machine. Don't muck around with just a log off - restart your machine. The Windows Oracle install uses Windows services by default and your installation is currently very bad - it needs a restart.

Following the restart I was then able to get error messages other than 'No message file...' and could start looking at what the issue was. Setting the ORACLE_SID to XE and connecting @XE I got as far as the errors in this page, namely the following symptoms:

ORA-01034: ORACLE not available
ORA-27101: shared memory realm does not exist

Another symptom was: When launching the 'Get started' page it failed to connect, giving a not found error (if I recall correctly), despite the Windows listener & XE services being started. As noted in another answer, this could be due to the windows services not being started. In my case those services were started, so something else was misconfigured.

At this point, I figured maybe my install had just gone so badly wrong due to the presence of my bad ORACLE_HOME environment property that I should reinstall. (Previous reinstalls hadn't helped, but those had all been before I noticed the ORACLE_HOME system environment property (probably set up by me a year ago!).

So to resolve:

  1. Close any app looking at the Oraclexe install directory (editors/explorer/cmd prompts)
  2. A quick trip to Add/Remove programs and uninstall OracleXe
  3. Double-check you have no ORACLE_HOME environment property set anywhere, remember - Windows will use registry entries to get it.
  4. Restart (take no chances - we're in this for the long term!)
  5. Did you make sure there was no ORACLE_HOME property?
  6. Run the Oracle installer again (as local admin account if applicable)
  7. You should be able to rejoice in a working install. I did, at least!

Getting absolute URLs using ASP.NET Core

After RC2 and 1.0 you no longer need to inject an IHttpContextAccessor to you extension class. It is immediately available in the IUrlHelper through the urlhelper.ActionContext.HttpContext.Request. You would then create an extension class following the same idea, but simpler since there will be no injection involved.

public static string AbsoluteAction(
    this IUrlHelper url,
    string actionName, 
    string controllerName, 
    object routeValues = null)
{
    string scheme = url.ActionContext.HttpContext.Request.Scheme;
    return url.Action(actionName, controllerName, routeValues, scheme);
}

Leaving the details on how to build it injecting the accesor in case they are useful to someone. You might also just be interested in the absolute url of the current request, in which case take a look at the end of the answer.


You could modify your extension class to use the IHttpContextAccessor interface to get the HttpContext. Once you have the context, then you can get the HttpRequest instance from HttpContext.Request and use its properties Scheme, Host, Protocol etc as in:

string scheme = HttpContextAccessor.HttpContext.Request.Scheme;

For example, you could require your class to be configured with an HttpContextAccessor:

public static class UrlHelperExtensions
{        
    private static IHttpContextAccessor HttpContextAccessor;
    public static void Configure(IHttpContextAccessor httpContextAccessor)
    {           
        HttpContextAccessor = httpContextAccessor;  
    }

    public static string AbsoluteAction(
        this IUrlHelper url,
        string actionName, 
        string controllerName, 
        object routeValues = null)
    {
        string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
        return url.Action(actionName, controllerName, routeValues, scheme);
    }

    ....
}

Which is something you can do on your Startup class (Startup.cs file):

public void Configure(IApplicationBuilder app)
{
    ...

    var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
    UrlHelperExtensions.Configure(httpContextAccessor);

    ...
}

You could probably come up with different ways of getting the IHttpContextAccessor in your extension class, but if you want to keep your methods as extension methods in the end you will need to inject the IHttpContextAccessor into your static class. (Otherwise you will need the IHttpContext as an argument on each call)


Just getting the absoluteUri of the current request

If you just want to get the absolute uri of the current request, you can use the extension methods GetDisplayUrl or GetEncodedUrl from the UriHelper class. (Which is different from the UrLHelper)

GetDisplayUrl. Returns the combined components of the request URL in a fully un-escaped form (except for the QueryString) suitable only for display. This format should not be used in HTTP headers or other HTTP operations.

GetEncodedUrl. Returns the combined components of the request URL in a fully escaped form suitable for use in HTTP headers and other HTTP operations.

In order to use them:

  • Include the namespace Microsoft.AspNet.Http.Extensions.
  • Get the HttpContext instance. It is already available in some classes (like razor views), but in others you might need to inject an IHttpContextAccessor as explained above.
  • Then just use them as in this.Context.Request.GetDisplayUrl()

An alternative to those methods would be manually crafting yourself the absolute uri using the values in the HttpContext.Request object (Similar to what the RequireHttpsAttribute does):

var absoluteUri = string.Concat(
                        request.Scheme,
                        "://",
                        request.Host.ToUriComponent(),
                        request.PathBase.ToUriComponent(),
                        request.Path.ToUriComponent(),
                        request.QueryString.ToUriComponent());

How to change facebook login button with my custom image

Found a site on google explaining some changes, according to the author of the page fb does not allow custom buttons. Heres the website.

Unfortunately, it’s against Facebook’s developer policies, which state:

You must not circumvent our intended limitations on core Facebook features.

The Facebook Connect button is intended to be rendered in FBML, which means it’s only meant to look the way Facebook lets it.

How to link to a <div> on another page?

Create an anchor:

<a name="anchor" id="anchor"></a> 

then link to it:

<a href="http://server/page.html#anchor">Link text</a>

How to clear the cache of nginx?

You can also bypass/re-cache on a file by file basis using

proxy_cache_bypass $http_secret_header;

and as a bonus you can return this header to see if you got it from the cache (will return 'HIT') or from the content server (will return 'BYPASS').

add_header X-Cache-Status $upstream_cache_status;

to expire/refresh the cached file, use curl or any rest client to make a request to the cached page.

curl http://abcdomain.com/mypage.html -s -I -H "secret-header:true"

this will return a fresh copy of the item and it will also replace what's in cache.

How do I compile a Visual Studio project from the command-line?

I know of two ways to do it.

Method 1
The first method (which I prefer) is to use msbuild:

msbuild project.sln /Flags...

Method 2
You can also run:

vcexpress project.sln /build /Flags...

The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.

Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).

So, the end result might be:

os.system("msbuild project.sln /p:Configuration=Debug")

You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).

What are the specific differences between .msi and setup.exe file?

An MSI is a Windows Installer database. Windows Installer (a service installed with Windows) uses this to install software on your system (i.e. copy files, set registry values, etc...).

A setup.exe may either be a bootstrapper or a non-msi installer. A non-msi installer will extract the installation resources from itself and manage their installation directly. A bootstrapper will contain an MSI instead of individual files. In this case, the setup.exe will call Windows Installer to install the MSI.

Some reasons you might want to use a setup.exe:

  • Windows Installer only allows one MSI to be installing at a time. This means that it is difficult to have an MSI install other MSIs (e.g. dependencies like the .NET framework or C++ runtime). Since a setup.exe is not an MSI, it can be used to install several MSIs in sequence.
  • You might want more precise control over how the installation is managed. An MSI has very specific rules about how it manages the installations, including installing, upgrading, and uninstalling. A setup.exe gives complete control over the software configuration process. This should only be done if you really need the extra control since it is a lot of work, and it can be tricky to get it right.

How to change the color of an image on hover

Ideally you should use a transparent PNG with the circle in white and the background of the image transparent. Then you can set the background-color of the .fb-icon to blue on hover. So you're CSS would be:

fb-icon{
    background:none;
}

fb-icon:hover{
    background:#0000ff;
}

Additionally, if you don't want to use PNG's you can also use a sprite and alter the background position. A sprite is one large image with a collection of smaller images which can be used as a background image by changing the background position. So for eg, if your original circle image with the white background is 100px X 100px, you can increase the height of the image to 100px X 200px, so that the top half is the original image with the white background, while the lower half is the new image with the blue background. Then you set setup your CSS as:

fb-icon{
    background:url('path/to/image/image.png') no-repeat 0 0;
}

fb-icon:hover{
    background:url('path/to/image/image.png') no-repeat 0 -100px;
}

PHP: how can I get file creation date?

Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.

It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.

Multiline for WPF TextBox

Also, if, like me, you add controls directly in XAML (not using the editor), you might get frustrated that it won't stretch to the available height, even after setting those two properties.

To make the TextBox stretch, set the Height="Auto".

UPDATE:

In retrospect, I think this must have been necessary thanks to a default style for TextBoxes specifying the height to some standard for the application somewhere in the App resources. It may be worthwhile checking this if this helped you.

How to open Console window in Eclipse?

Window > Perspective > Reset Perspective

When should I use cross apply over inner join?

Cross apply works well with an XML field as well. If you wish to select node values in combination with other fields.

For example, if you have a table containing some xml

<root>
    <subnode1>
       <some_node value="1" />
       <some_node value="2" />
       <some_node value="3" />
       <some_node value="4" />
    </subnode1>
</root>

Using the query

SELECT
       id as [xt_id]
      ,xmlfield.value('(/root/@attribute)[1]', 'varchar(50)') root_attribute_value
  ,node_attribute_value = [some_node].value('@value', 'int')
  ,lt.lt_name   
FROM dbo.table_with_xml xt
CROSS APPLY xmlfield.nodes('/root/subnode1/some_node') as g ([some_node])
LEFT OUTER JOIN dbo.lookup_table lt
ON [some_node].value('@value', 'int') = lt.lt_id

Will return a result

xt_id root_attribute_value node_attribute_value lt_name
----------------------------------------------------------------------
1     test1            1                    Benefits
1     test1            4                    FINRPTCOMPANY

How to load a model from an HDF5 file in Keras?

load_weights only sets the weights of your network. You still need to define its architecture before calling load_weights:

def create_model():
   model = Sequential()
   model.add(Dense(64, input_dim=14, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5)) 
   model.add(Dense(64, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5))
   model.add(Dense(2, init='uniform'))
   model.add(Activation('softmax'))
   return model

def train():
   model = create_model()
   sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
   model.compile(loss='binary_crossentropy', optimizer=sgd)

   checkpointer = ModelCheckpoint(filepath="/tmp/weights.hdf5", verbose=1, save_best_only=True)
   model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose=2, callbacks=[checkpointer])

def load_trained_model(weights_path):
   model = create_model()
   model.load_weights(weights_path)

Injection of autowired dependencies failed;

public class Organization {

    @Id
    @Column(name="org_id")
    @GeneratedValue
    private int id;

    @Column(name="org_name")
    private String name;

    @Column(name="org_office_address1")
    private String address1;

    @Column(name="org_office_addres2")
    private String address2;

    @Column(name="city")
    private String city;

    @Column(name="state")
    private String state;

    @Column(name="country")
    private String country;

    @JsonIgnore
    @OneToOne
    @JoinColumn(name="pkg_id")
    private int pkgId;

    public int getPkgId() {
        return pkgId;
    }

    public void setPkgId(int pkgId) {
        this.pkgId = pkgId;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Column(name="pincode")
    private String pincode;

    @OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);

    @Column(name="status")
    private String status = "ACTIVE";

    @Column(name="project_id")
    private int redmineProjectId;

    public int getRedmineProjectId() {
        return redmineProjectId;
    }

    public void setRedmineProjectId(int redmineProjectId) {
        this.redmineProjectId = redmineProjectId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Set<OrganizationBranch> getOrganizationBranch() {
        return organizationBranch;
    }

    public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
        this.organizationBranch = organizationBranch;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }
}

You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired

How to specify legend position in matplotlib in graph coordinates

In addition to @ImportanceOfBeingErnest's post, I use the following line to add a legend at an absolute position in a plot.

plt.legend(bbox_to_anchor=(1.0,1.0),\
    bbox_transform=plt.gcf().transFigure)

For unknown reasons, bbox_transform=fig.transFigure does not work with me.

Quickest way to convert a base 10 number to any base in .NET?

Very late to the party on this one, but I wrote the following helper class recently for a project at work. It was designed to convert short strings into numbers and back again (a simplistic perfect hash function), however it will also perform number conversion between arbitrary bases. The Base10ToString method implementation answers the question that was originally posted.

The shouldSupportRoundTripping flag passed to the class constructor is needed to prevent the loss of leading digits from the number string during conversion to base-10 and back again (crucial, given my requirements!). Most of the time the loss of leading 0s from the number string probably won't be an issue.

Anyway, here's the code:

using System;
using System.Collections.Generic;
using System.Linq;

namespace StackOverflow
{
    /// <summary>
    /// Contains methods used to convert numbers between base-10 and another numbering system.
    /// </summary>
    /// <remarks>
    /// <para>
    /// This conversion class makes use of a set of characters that represent the digits used by the target
    /// numbering system. For example, binary would use the digits 0 and 1, whereas hex would use the digits
    /// 0 through 9 plus A through F. The digits do not have to be numerals.
    /// </para>
    /// <para>
    /// The first digit in the sequence has special significance. If the number passed to the
    /// <see cref="StringToBase10"/> method has leading digits that match the first digit, then those leading
    /// digits will effectively be 'lost' during conversion. Much of the time this won't matter. For example,
    /// "0F" hex will be converted to 15 decimal, but when converted back to hex it will become simply "F",
    /// losing the leading "0". However, if the set of digits was A through Z, and the number "ABC" was
    /// converted to base-10 and back again, then the leading "A" would be lost. The <see cref="System.Boolean"/>
    /// flag passed to the constructor allows 'round-tripping' behaviour to be supported, which will prevent
    /// leading digits from being lost during conversion.
    /// </para>
    /// <para>
    /// Note that numeric overflow is probable when using longer strings and larger digit sets.
    /// </para>
    /// </remarks>
    public class Base10Converter
    {
        const char NullDigit = '\0';

        public Base10Converter(string digits, bool shouldSupportRoundTripping = false)
            : this(digits.ToCharArray(), shouldSupportRoundTripping)
        {
        }

        public Base10Converter(IEnumerable<char> digits, bool shouldSupportRoundTripping = false)
        {
            if (digits == null)
            {
                throw new ArgumentNullException("digits");
            }

            if (digits.Count() == 0)
            {
                throw new ArgumentException(
                    message: "The sequence is empty.",
                    paramName: "digits"
                    );
            }

            if (!digits.Distinct().SequenceEqual(digits))
            {
                throw new ArgumentException(
                    message: "There are duplicate characters in the sequence.",
                    paramName: "digits"
                    );
            }

            if (shouldSupportRoundTripping)
            {
                digits = (new[] { NullDigit }).Concat(digits);
            }

            _digitToIndexMap =
                digits
                .Select((digit, index) => new { digit, index })
                .ToDictionary(keySelector: x => x.digit, elementSelector: x => x.index);

            _radix = _digitToIndexMap.Count;

            _indexToDigitMap =
                _digitToIndexMap
                .ToDictionary(keySelector: x => x.Value, elementSelector: x => x.Key);
        }

        readonly Dictionary<char, int> _digitToIndexMap;
        readonly Dictionary<int, char> _indexToDigitMap;
        readonly int _radix;

        public long StringToBase10(string number)
        {
            Func<char, int, long> selector =
                (c, i) =>
                {
                    int power = number.Length - i - 1;

                    int digitIndex;
                    if (!_digitToIndexMap.TryGetValue(c, out digitIndex))
                    {
                        throw new ArgumentException(
                            message: String.Format("Number contains an invalid digit '{0}' at position {1}.", c, i),
                            paramName: "number"
                            );
                    }

                    return Convert.ToInt64(digitIndex * Math.Pow(_radix, power));
                };

            return number.Select(selector).Sum();
        }

        public string Base10ToString(long number)
        {
            if (number < 0)
            {
                throw new ArgumentOutOfRangeException(
                    message: "Value cannot be negative.",
                    paramName: "number"
                    );
            }

            string text = string.Empty;

            long remainder;
            do
            {
                number = Math.DivRem(number, _radix, out remainder);

                char digit;
                if (!_indexToDigitMap.TryGetValue((int) remainder, out digit) || digit == NullDigit)
                {
                    throw new ArgumentException(
                        message: "Value cannot be converted given the set of digits used by this converter.",
                        paramName: "number"
                        );
                }

                text = digit + text;
            }
            while (number > 0);

            return text;
        }
    }
}

This can also be subclassed to derive custom number converters:

namespace StackOverflow
{
    public sealed class BinaryNumberConverter : Base10Converter
    {
        public BinaryNumberConverter()
            : base(digits: "01", shouldSupportRoundTripping: false)
        {
        }
    }

    public sealed class HexNumberConverter : Base10Converter
    {
        public HexNumberConverter()
            : base(digits: "0123456789ABCDEF", shouldSupportRoundTripping: false)
        {
        }
    }
}

And the code would be used like this:

using System.Diagnostics;

namespace StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            {
                var converter = new Base10Converter(
                    digits: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz",
                    shouldSupportRoundTripping: true
                    );

                long number = converter.StringToBase10("Atoz");
                string text = converter.Base10ToString(number);
                Debug.Assert(text == "Atoz");
            }

            {
                var converter = new HexNumberConverter();

                string text = converter.Base10ToString(255);
                long number = converter.StringToBase10(text);
                Debug.Assert(number == 255);
            }
        }
    }
}

Why is my Button text forced to ALL CAPS on Lollipop?

If you use appcompat-v7, you can subclass AppCompatButtonand setSupportAllCaps(false), then use this class for all your buttons.

/**
 * Light extension of {@link AppCompatButton} that overrides ALL CAPS transformation
 */
public class Button extends AppCompatButton {
    public Button(Context context, AttributeSet attrs) {
        super(context, attrs);
        setSupportAllCaps(false);
    }

    public Button(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setSupportAllCaps(false);
    }
}

See AppCompatButton#setSupportAllCaps(boolean) Android docs.

Sorting an array of objects by property values

If you have an ES6 compliant browser you can use:

The difference between ascending and descending sort order is the sign of the value returned by your compare function:

var ascending = homes.sort((a, b) => Number(a.price) - Number(b.price));
var descending = homes.sort((a, b) => Number(b.price) - Number(a.price));

Here's a working code snippet:

_x000D_
_x000D_
var homes = [{_x000D_
  "h_id": "3",_x000D_
  "city": "Dallas",_x000D_
  "state": "TX",_x000D_
  "zip": "75201",_x000D_
  "price": "162500"_x000D_
}, {_x000D_
  "h_id": "4",_x000D_
  "city": "Bevery Hills",_x000D_
  "state": "CA",_x000D_
  "zip": "90210",_x000D_
  "price": "319250"_x000D_
}, {_x000D_
  "h_id": "5",_x000D_
  "city": "New York",_x000D_
  "state": "NY",_x000D_
  "zip": "00010",_x000D_
  "price": "962500"_x000D_
}];_x000D_
_x000D_
homes.sort((a, b) => Number(a.price) - Number(b.price));_x000D_
console.log("ascending", homes);_x000D_
_x000D_
homes.sort((a, b) => Number(b.price) - Number(a.price));_x000D_
console.log("descending", homes);
_x000D_
_x000D_
_x000D_

How to call a JavaScript function within an HTML body

Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

Is there an easy way to convert jquery code to javascript?

I can see a reason, unrelated to the original post, to automatically compile jQuery code into standard JavaScript:

16k -- or whatever the gzipped, minified jQuery library is -- might be too much for your website that is intended for a mobile browser. The w3c is recommending that all HTTP requests for mobile websites should be a maximum of 20k.

w3c specs for mobile

So I enjoy coding in my nice, terse, chained jQuery. But now I need to optimize for mobile. Should I really go back and do the difficult, tedious work of rewriting all the helper functions I used in the jQuery library? Or is there some kind of convenient app that will help me recompile?

That would be very sweet. Sadly, I don't think such a thing exists.

Making a request to a RESTful API using python

So you want to pass data in body of a GET request, better would be to do it in POST call. You can achieve this by using both Requests.

Raw Request

GET http://ES_search_demo.com/document/record/_search?pretty=true HTTP/1.1
Host: ES_search_demo.com
Content-Length: 183
User-Agent: python-requests/2.9.0
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate

{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}

Sample call with Requests

import requests

def consumeGETRequestSync():
data = '{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = requests.get(url,data = data)
print "code:"+ str(response.status_code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "content:"+ str(response.text)

consumeGETRequestSync()