Programs & Examples On #Project folder

Create an array with random values

Shortest :-)

[...Array(40)].map(e=>~~(Math.random()*40))

How do you use the ? : (conditional) operator in JavaScript?

Hey mate just remember js works by evaluating to either true or false, right?

let's take a ternary operator :

questionAnswered ? "Awesome!" : "damn" ;

First, js checks whether questionAnswered is true or false.

if true ( ? ) you will get "Awesome!"

else ( : ) you will get "damn";

Hope this helps friend :)

How do I create HTML table using jQuery dynamically?

Here is a full example of what you are looking for:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $( document ).ready(function() {
            $("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
        });
    </script>
</head>

<body>
    <table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>

overlay a smaller image on a larger image python OpenCv

Here it is:

def put4ChannelImageOn4ChannelImage(back, fore, x, y):
    rows, cols, channels = fore.shape    
    trans_indices = fore[...,3] != 0 # Where not transparent
    overlay_copy = back[y:y+rows, x:x+cols] 
    overlay_copy[trans_indices] = fore[trans_indices]
    back[y:y+rows, x:x+cols] = overlay_copy

#test
background = np.zeros((1000, 1000, 4), np.uint8)
background[:] = (127, 127, 127, 1)
overlay = cv2.imread('imagee.png', cv2.IMREAD_UNCHANGED)
put4ChannelImageOn4ChannelImage(background, overlay, 5, 5)

Use jQuery to get the file input's selected filename without the path

Here is how I do it, it works pretty well.

In your HTML do:

<input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />

Then in your js file create a simple function:

function fileSelect(id, e){
    console.log(e.target.files[0].name);
}

If you're doing multiple files, you should also be able to get the list by looping over this:

e.target.files[0].name

Solving "adb server version doesn't match this client" error

For anyone still having this issue ( on windows ):

  1. Open task manager
  2. Go to processes and select the ADB.EXE
  3. Right-click on it and check the properties
  4. Most likely you will see a different path from where the adb.exe is running ( either HTC manager, Genymotion, etc )
  5. Kill the process
  6. Run ADB.exe from your android studio path ( in my case: C:\Users\%user%\AppData\Local\Android\sdk\platform-tools )

This solved the problem in my case.

Math constant PI value in C

The closest thing C does to "computing p" in a way that's directly visible to applications is acos(-1) or similar. This is almost always done with polynomial/rational approximations for the function being computed (either in C, or by the FPU microcode).

However, an interesting issue is that computing the trigonometric functions (sin, cos, and tan) requires reduction of their argument modulo 2p. Since 2p is not a diadic rational (and not even rational), it cannot be represented in any floating point type, and thus using any approximation of the value will result in catastrophic error accumulation for large arguments (e.g. if x is 1e12, and 2*M_PI differs from 2p by e, then fmod(x,2*M_PI) differs from the correct value of 2p by up to 1e12*e/p times the correct value of x mod 2p. That is to say, it's completely meaningless.

A correct implementation of C's standard math library simply has a gigantic very-high-precision representation of p hard coded in its source to deal with the issue of correct argument reduction (and uses some fancy tricks to make it not-quite-so-gigantic). This is how most/all C versions of the sin/cos/tan functions work. However, certain implementations (like glibc) are known to use assembly implementations on some cpus (like x86) and don't perform correct argument reduction, leading to completely nonsensical outputs. (Incidentally, the incorrect asm usually runs about the same speed as the correct C code for small arguments.)

Checking if a list is empty with LINQ

private bool NullTest<T>(T[] list, string attribute)

    {
        bool status = false;
        if (list != null)
        {
            int flag = 0;
            var property = GetProperty(list.FirstOrDefault(), attribute);
            foreach (T obj in list)
            {
                if (property.GetValue(obj, null) == null)
                    flag++;
            }
            status = flag == 0 ? true : false;
        }
        return status;
    }


public PropertyInfo GetProperty<T>(T obj, string str)

    {
        Expression<Func<T, string, PropertyInfo>> GetProperty = (TypeObj, Column) => TypeObj.GetType().GetProperty(TypeObj
            .GetType().GetProperties().ToList()
            .Find(property => property.Name
            .ToLower() == Column
            .ToLower()).Name.ToString());
        return GetProperty.Compile()(obj, str);
    }

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

'any' vs 'Object'

Bit old, but doesn't hurt to add some notes.

When you write something like this

let a: any;
let b: Object;
let c: {};
  • a has no interface, it can be anything, the compiler knows nothing about its members so no type checking is performed when accessing/assigning both to it and its members. Basically, you're telling the compiler to "back off, I know what I'm doing, so just trust me";
  • b has the Object interface, so ONLY the members defined in that interface are available for b. It's still JavaScript, so everything extends Object;
  • c extends Object, like anything else in TypeScript, but adds no members. Since type compatibility in TypeScript is based on structural subtyping, not nominal subtyping, c ends up being the same as b because they have the same interface: the Object interface.

And that's why

a.doSomething(); // Ok: the compiler trusts you on that
b.doSomething(); // Error: Object has no doSomething member
c.doSomething(); // Error: c neither has doSomething nor inherits it from Object

and why

a.toString(); // Ok: whatever, dude, have it your way
b.toString(); // Ok: toString is defined in Object
c.toString(); // Ok: c inherits toString from Object

So Object and {} are equivalents in TypeScript.

If you declare functions like these

function fa(param: any): void {}
function fb(param: Object): void {}

with the intention of accepting anything for param (maybe you're going to check types at run-time to decide what to do with it), remember that

  • inside fa, the compiler will let you do whatever you want with param;
  • inside fb, the compiler will only let you reference Object's members.

It is worth noting, though, that if param is supposed to accept multiple known types, a better approach is to declare it using union types, as in

function fc(param: string|number): void {}

Obviously, OO inheritance rules still apply, so if you want to accept instances of derived classes and treat them based on their base type, as in

interface IPerson {
    gender: string;
}

class Person implements IPerson {
    gender: string;
}

class Teacher extends Person {}

function func(person: IPerson): void {
    console.log(person.gender);
}

func(new Person());     // Ok
func(new Teacher());    // Ok
func({gender: 'male'}); // Ok
func({name: 'male'});   // Error: no gender..

the base type is the way to do it, not any. But that's OO, out of scope, I just wanted to clarify that any should only be used when you don't know whats coming, and for anything else you should annotate the correct type.

UPDATE:

Typescript 2.2 added an object type, which specifies that a value is a non-primitive: (i.e. not a number, string, boolean, symbol, undefined, or null).

Consider functions defined as:

function b(x: Object) {}
function c(x: {}) {}
function d(x: object) {}

x will have the same available properties within all of these functions, but it's a type error to call d with a primitive:

b("foo"); //Okay
c("foo"); //Okay
d("foo"); //Error: "foo" is a primitive

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

Shell calls to reverse (as mentioned above) are very good to debug these problems, but there are two critical conditions:

  • you must supply arguments that matches whatever arguments the view needs,
  • these arguments must match regexp patterns.

Yes, it's logical. Yes, it's also confusing because reverse will only throw the exception and won't give you any further hints.

An example of URL pattern:

url(r'^cookies/(?P<hostname>[^/]+)/(?P<url_id>\d+)/$', 'register_site.views.show_cookies', name='show_cookies'),

And then what happens in shell:

>>> from register_site.views import show_cookies
>>> reverse(show_cookies)
NoReverseMatch: Reverse for 'register_site.views.show_cookies' with arguments '()' and keyword arguments '{}' not found.

It doesn't work because I supplied no arguments.

>>> reverse('show_cookies', kwargs={'url_id':123,'hostname': 'aaa'})
'/cookies/aaa/123'

Now it worked, but...

>>> reverse('show_cookies', kwargs={'url_id':'x','hostname': 'www.dupa.com'})
NoReverseMatch: Reverse for 'show_cookies' with arguments '()' and keyword arguments '{'url_id': 'x', 'hostname': 'www.dupa.com'}' not found.

Now it didn't work because url_id didn't match the regexp (expected numeric, supplied string).

You can use reverse with both positional arguments and keyword arguments. The syntax is:

reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None)

As it comes to the url template tag, there's funny thing about it. Django documentation gives example of using quoted view name:

{% url 'news.views.year_archive' yearvar %}

So I used it in a similar way in my HTML template:

{% url 'show_cookies' hostname=u.hostname url_id=u.pk %}

But this didn't work for me. But the exception message gave me a hint of what could be wrong - note the double single quotes around view name:

Reverse for ''show_cookies'' with arguments...

It started to work when I removed the quotes:

{% url show_cookies hostname=u.hostname url_id=u.pk %}

And this is confusing.

Simulate a click on 'a' element using javascript/jquery

The code you've already tried:

document.getElementById("gift-close").click();

...should work as long as the element actually exists in the DOM at the time you run it. Some possible ways to ensure that include:

  1. Run your code from an onload handler for the window. http://jsfiddle.net/LKNYg/
  2. Run your code from a document ready handler if you're using jQuery. http://jsfiddle.net/LKNYg/1/
  3. Put the code in a script block that is after the element in the source html.

So:

$(document).ready(function() {
    document.getElementById("gift-close").click();
    // OR
    $("#gift-close")[0].click();
});

The listener supports no services

Check local_listener definition in your spfile or pfile. In my case, the problem was with pfile, I had moved the pfile from a similar environment and it had LISTENER_sid as LISTENER and not just LISTENER.

Get docker container id from container name

The simplest way I can think of is to parse the output of docker ps

Let's run the latest ubuntu image interactively and connect to it

docker run -it ubuntu /bin/bash

If you run docker ps in another terminal you can see something like

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
8fddbcbb101c        ubuntu:latest       "/bin/bash"         10 minutes ago      Up 10 minutes                           gloomy_pasteur

Unfortunately, parsing this format isn't easy since they uses spaces to manually align stuff

$ sudo docker ps | sed -e 's/ /@/g'
CONTAINER@ID@@@@@@@@IMAGE@@@@@@@@@@@@@@@COMMAND@@@@@@@@@@@@@CREATED@@@@@@@@@@@@@STATUS@@@@@@@@@@@@@@PORTS@@@@@@@@@@@@@@@NAMES
8fddbcbb101c@@@@@@@@ubuntu:latest@@@@@@@"/bin/bash"@@@@@@@@@13@minutes@ago@@@@@@Up@13@minutes@@@@@@@@@@@@@@@@@@@@@@@@@@@gloomy_pasteur@@@@@@

Here is a script that converts the output to JSON.

https://gist.github.com/mminer/a08566f13ef687c17b39

Actually, the output is a bit more convenient to work with than that. Every field is 20 characters wide. [['CONTAINER ID',0],['IMAGE',20],['COMMAND',40],['CREATED',60],['STATUS',80],['PORTS',100],['NAMES',120]]

Check if a Windows service exists and delete in PowerShell

Combining Dmitri & dcx's answers I made this:

function Confirm-WindowsServiceExists($name)
{   
    if (Get-Service $name -ErrorAction SilentlyContinue)
    {
        return $true
    }
    return $false
}

function Remove-WindowsServiceIfItExists($name)
{   
    $exists = Confirm-WindowsServiceExists $name
    if ($exists)
    {    
        sc.exe \\server delete $name
    }       
}

How to extract a single value from JSON response?

using json.loads will turn your data into a python dictionary.

Dictionaries values are accessed using ['key']

resp_str = {
  "name" : "ns1:timeSeriesResponseType",
  "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
  "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
  "value" : {
    "queryInfo" : {
      "creationTime" : 1349724919000,
      "queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
      "criteria" : {
        "locationParam" : "[ALL:103232434]",
        "variableParam" : "[00060, 00065]"
      },
      "note" : [ {
        "value" : "[ALL:103232434]",
        "title" : "filter:sites"
      }, {
        "value" : "[mode=LATEST, modifiedSince=null]",
        "title" : "filter:timeRange"
      }, {
        "value" : "sdas01",
        "title" : "server"
      } ]
    }
  },
  "nil" : false,
  "globalScope" : true,
  "typeSubstituted" : false
}

would translate into a python diction

resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000

Get value from a string after a special character

Assuming you have your hidden input in a jQuery object $myHidden, you then use JavaScript (not jQuery) to get the part after ?:

var myVal = $myHidden.val ();
var tmp = myVal.substr ( myVal.indexOf ( '?' ) + 1 ); // tmp now contains whatever is after ?

How do you change the value inside of a textfield flutter?

You can use the text editing controller to manipulate the value inside a textfield.

var textController = new TextEditingController();

Now, create a new textfield and set textController as the controller for the textfield as shown below.

 new TextField(controller: textController)

Now, create a RaisedButton anywhere in your code and set the desired text in the onPressed method of the RaisedButton.

new RaisedButton(
       onPressed: () {
          textController.text = "New text";
       }
    ),

Relationship between hashCode and equals method in Java

Have a look at Hashtables, Hashmaps, HashSets and so forth. They all store the hashed key as their keys. When invoking get(Object key) the hash of the parameter is generated and lookup in the given hashes.

When not overwriting hashCode() and the instance of the key has been changed (for example a simple string that doesn't matter at all), the hashCode() could result in 2 different hashcodes for the same object, resulting in not finding your given key in map.get().

Pure CSS scroll animation

And for webkit enabled browsers I've had good results with:

.myElement {
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth; // Added in from answer from Felix
    overflow-x: scroll;
}

This makes scrolling behave much more like the standard browser behavior - at least it works well on the iPhone we were testing on!

Hope that helps,

Ed

Initializing a dictionary in python with a key value and no corresponding values

You can initialize the values as empty strings and fill them in later as they are found.

dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

Is it possible to import modules from all files in a directory, using a wildcard?

If you are using webpack. This imports files automatically and exports as api namespace.

So no need to update on every file addition.

import camelCase from "lodash-es";
const requireModule = require.context("./", false, /\.js$/); // 
const api = {};

requireModule.keys().forEach(fileName => {
  if (fileName === "./index.js") return;
  const moduleName = camelCase(fileName.replace(/(\.\/|\.js)/g, ""));
  api[moduleName] = {
    ...requireModule(fileName).default
  };
});

export default api;

For Typescript users;

import { camelCase } from "lodash-es"
const requireModule = require.context("./folderName", false, /\.ts$/)

interface LooseObject {
  [key: string]: any
}

const api: LooseObject = {}

requireModule.keys().forEach(fileName => {
  if (fileName === "./index.ts") return
  const moduleName = camelCase(fileName.replace(/(\.\/|\.ts)/g, ""))
  api[moduleName] = {
    ...requireModule(fileName).default,
  }
})

export default api

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

About list

First a very important point, from which everything will follow (I hope).

In ordinary Python, list is not special in any way (except having cute syntax for constructing, which is mostly a historical accident). Once a list [3,2,6] is made, it is for all intents and purposes just an ordinary Python object, like a number 3, set {3,7}, or a function lambda x: x+5.

(Yes, it supports changing its elements, and it supports iteration, and many other things, but that's just what a type is: it supports some operations, while not supporting some others. int supports raising to a power, but that doesn't make it very special - it's just what an int is. lambda supports calling, but that doesn't make it very special - that's what lambda is for, after all:).

About and

and is not an operator (you can call it "operator", but you can call "for" an operator too:). Operators in Python are (implemented through) methods called on objects of some type, usually written as part of that type. There is no way for a method to hold an evaluation of some of its operands, but and can (and must) do that.

The consequence of that is that and cannot be overloaded, just like for cannot be overloaded. It is completely general, and communicates through a specified protocol. What you can do is customize your part of the protocol, but that doesn't mean you can alter the behavior of and completely. The protocol is:

Imagine Python interpreting "a and b" (this doesn't happen literally this way, but it helps understanding). When it comes to "and", it looks at the object it has just evaluated (a), and asks it: are you true? (NOT: are you True?) If you are an author of a's class, you can customize this answer. If a answers "no", and (skips b completely, it is not evaluated at all, and) says: a is my result (NOT: False is my result).

If a doesn't answer, and asks it: what is your length? (Again, you can customize this as an author of a's class). If a answers 0, and does the same as above - considers it false (NOT False), skips b, and gives a as result.

If a answers something other than 0 to the second question ("what is your length"), or it doesn't answer at all, or it answers "yes" to the first one ("are you true"), and evaluates b, and says: b is my result. Note that it does NOT ask b any questions.

The other way to say all of this is that a and b is almost the same as b if a else a, except a is evaluated only once.

Now sit for a few minutes with a pen and paper, and convince yourself that when {a,b} is a subset of {True,False}, it works exactly as you would expect of Boolean operators. But I hope I have convinced you it is much more general, and as you'll see, much more useful this way.

Putting those two together

Now I hope you understand your example 1. and doesn't care if mylist1 is a number, list, lambda or an object of a class Argmhbl. It just cares about mylist1's answer to the questions of the protocol. And of course, mylist1 answers 5 to the question about length, so and returns mylist2. And that's it. It has nothing to do with elements of mylist1 and mylist2 - they don't enter the picture anywhere.

Second example: & on list

On the other hand, & is an operator like any other, like + for example. It can be defined for a type by defining a special method on that class. int defines it as bitwise "and", and bool defines it as logical "and", but that's just one option: for example, sets and some other objects like dict keys views define it as a set intersection. list just doesn't define it, probably because Guido didn't think of any obvious way of defining it.

numpy

On the other leg:-D, numpy arrays are special, or at least they are trying to be. Of course, numpy.array is just a class, it cannot override and in any way, so it does the next best thing: when asked "are you true", numpy.array raises a ValueError, effectively saying "please rephrase the question, my view of truth doesn't fit into your model". (Note that the ValueError message doesn't speak about and - because numpy.array doesn't know who is asking it the question; it just speaks about truth.)

For &, it's completely different story. numpy.array can define it as it wishes, and it defines & consistently with other operators: pointwise. So you finally get what you want.

HTH,

What is the facade design pattern?

A facade is a class with a level of functionality that lies between a toolkit and a complete application, offering a simplified usage of the classes in a package or subsystem. The intent of the Facade pattern is to provide an interface that makes a subsystem easy to use. -- Extract from book Design Patterns in C#.

Removing a list of characters in string

Why not a simple loop?

for i in replace_list:
    string = string.replace(i, '')

Also, avoid naming lists 'list'. It overrides the built-in function list.

How do I pass JavaScript variables to PHP?

This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.

Just set a cookie with the data you want to pass to PHP using javascript in the browser.

Then, simply read this cookie on the PHP side.

Getting the last element of a split string array

You can access the array index directly:

var csv = 'zero,one,two,three'; csv.split(',')[0]; //result: zero csv.split(',')[3]; //result: three

Is it possible to use argsort in descending order?

You could create a copy of the array and then multiply each element with -1.
As an effect the before largest elements would become the smallest.
The indeces of the n smallest elements in the copy are the n greatest elements in the original.

Split varchar into separate columns in Oracle

With REGEXP_SUBSTR is as simple as:

SELECT REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 1) col_one,
       REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 2) col_two
FROM YOUR_TABLE t;

How can I create a table with borders in Android?

Here is a great way to solve this problem:

Create a rectangle drawable with rounded corners like this:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
    <stroke android:width="2dp"
            android:color="#888888"/> 

    <corners android:bottomRightRadius="6dp" 
             android:bottomLeftRadius="6dp" 
             android:topLeftRadius="6dp" 
             android:topRightRadius="6dp"/> 
</shape>

save it in the drawable folder with the name rounded_border.xml

Then create a relative layout that uses the rounded_border as a background like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="@drawable/rounded_border">
   <ListView 
       android:id="@+id/list_view"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"/>

</RelativeLayout>

save that in your layout folder and name it table_with_border.xml

then whenever you need such a table pull it into a view using the include syntax like this:

<include
        android:id="@+id/rounded_table"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/table_with_border" />

You will probably want to add some spacing around the edges - so just wrap the include in a LinearLayout and add some padding around the edges.

Simple and easy way to get a pretty border around a table.

MySQL: ALTER TABLE if column not exists

I used this approach (Without using stored procedure):

SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbl_name' AND COLUMN_NAME = 'column_name'

If it didnt return any rows then the column doesn't exists then alter the table:

ALTER TABLE tbl_name ADD COLUMN column_name TINYINT(1) NOT NULL DEFAULT 1

Hope this helps.

S3 limit to objects in a bucket

According to Amazon:

Write, read, and delete objects containing from 0 bytes to 5 terabytes of data each. The number of objects you can store is unlimited.

Source: http://aws.amazon.com/s3/details/ as of Sep 3, 2015.

Spring @Value is not resolving to value from property file

Problem is due to problem in my applicationContext.xml vs spring-servlet.xml - it was scoping issue between the beans.

pedjaradenkovic kindly pointed me to an existing resource: Spring @Value annotation in @Controller class not evaluating to value inside properties file and Spring 3.0.5 doesn't evaluate @Value annotation from properties

Adding click event for a button created dynamically using jQuery

Use a delegated event handler bound to the container:

$('#pg_menu_content').on('click', '#btn_a', function(){
    console.log(this.value);
});

That is, bind to an element that exists at the moment that the JS runs (I'm assuming #pg_menu_content exists when the page loads), and supply a selector in the second parameter to .on(). When a click occurs on #pg_menu_content element jQuery checks whether it applied to a child of that element which matches the #btn_a selector.

Either that or bind a standard (non-delegated) click handler after creating the button.

Either way, within the click handler this will refer to the button in question, so this.value will give you its value.

How to check if type of a variable is string?

>>> thing = 'foo'
>>> type(thing).__name__ == 'str' or type(thing).__name__ == 'unicode'
True

How to pass multiple parameters in a querystring

I use the AbsoluteUri and you can get it like this:

string myURI = Request.Url.AbsoluteUri;
 if (!WebSecurity.IsAuthenticated) {
        Response.Redirect("~/Login?returnUrl="
            + Request.Url.AbsoluteUri );

Then after you login:

var returnUrl = Request.QueryString["returnUrl"];
 if(WebSecurity.Login(username,password,true)){
                Context.RedirectLocal(returnUrl);

It works well for me.

How to get primary key column in Oracle?

Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;

(This will list the primary key and then)

Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’; 

(This will give you the column, here PK_XYZ is the primay key name)

Laravel - check if Ajax request

Most of the answers are working fine. We can also check the request header

request()->header('Accept')=='application/json'

to check the request type

What is the difference between a mutable and immutable string in C#?

The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

How can I add new item to the String array?

You can't do it the way you wanted.

Use ArrayList instead:

List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp");

And then you can have an array again by using toArray:

String[] myArray = new String[a.size()];
a.toArray(myArray);

How to check if a scope variable is undefined in AngularJS template?

Here is the cleanest way to do this:

<p ng-show="{{foo === undefined}}">Show this if $scope.foo === undefined</p>

No need to create a helper function in the controller!

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

How do I select last 5 rows in a table without sorting?

This is just about the most bizarre query I've ever written, but I'm pretty sure it gets the "last 5" rows from a table without ordering:

select * 
from issues
where issueid not in (
    select top (
        (select count(*) from issues) - 5
    ) issueid
    from issues
)

Note that this makes use of SQL Server 2005's ability to pass a value into the "top" clause - it doesn't work on SQL Server 2000.

C# - using List<T>.Find() with custom objects

It's easy, just use list.Find(x => x.name == "stringNameOfObjectToFind");

How to detect window.print() finish

It works for me with $(window).focus().

var w;
var src = 'http://pagetoprint';
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
    w = $('<iframe></iframe>');
    w.attr('src', src);
    w.css('display', 'none');
    $('body').append(w);
    w.load(function() {
        w[0].focus();
        w[0].contentWindow.print();
    });
    $(window).focus(function() {
        console.log('After print');
    });
}
else {
    w = window.open(src);
    $(w).unload(function() {
        console.log('After print');
    });
}

Angular 2 http post params and body

Seems like you use Angular 4.3 version, I also faced with same problem. Use Angular 4.0.1 and post with code by @trichetricheand and it will work. I am also not sure how to solve it on Angular 4.3 :S

How do I copy a 2 Dimensional array in Java?

I am using this function:

public static int[][] copy(final int[][] array) {
    if (array != null) {
        final int[][] copy = new int[array.length][];

        for (int i = 0; i < array.length; i++) {
            final int[] row = array[i];

            copy[i] = new int[row.length];
            System.arraycopy(row, 0, copy[i], 0, row.length);
        }

        return copy;
    }

    return null;
}

The big advantage of this approach is that it can also copy arrays that don't have the same row count such as:

final int[][] array = new int[][] { { 5, 3, 6 }, { 1 } };

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

That's not the right way to set the permissions as you are overwriting them with each method call.

Replace this:

mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.setReadPermissions("public_profile");
mButtonLogin.setReadPermissions("email");
mButtonLogin.setReadPermissions("user_birthday");

With the following, as the method setReadPermissions() accepts an ArrayList:

loginButton.setReadPermissions(Arrays.asList(
        "public_profile", "email", "user_birthday", "user_friends"));

Also here is how to query extra data GraphRequest:

private LoginButton loginButton;
private CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginButton = (LoginButton) findViewById(R.id.login_button);

    loginButton.setReadPermissions(Arrays.asList(
            "public_profile", "email", "user_birthday", "user_friends"));

    callbackManager = CallbackManager.Factory.create();

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v("LoginActivity", response.toString());

                            // Application code
                            String email = object.getString("email");
                            String birthday = object.getString("birthday"); // 01/31/1980 format
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender,birthday");
            request.setParameters(parameters);
            request.executeAsync();


        }

        @Override
        public void onCancel() {
            // App code
            Log.v("LoginActivity", "cancel");
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.v("LoginActivity", exception.getCause().toString());
        }
    });
}

EDIT:

One possible problem is that Facebook assumes that your email is invalid. To test it, use the Graph API Explorer and try to get it. If even there you can't get your email, change it in your profile settings and try again. This approach resolved this issue for some developers commenting my answer.

Pandas dataframe groupby plot

Simple plot,

you can use:

df.plot(x='Date',y='adj_close')

Or you can set the index to be Date beforehand, then it's easy to plot the column you want:

df.set_index('Date', inplace=True)
df['adj_close'].plot()

If you want a chart with one series by ticker on it

You need to groupby before:

df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)

enter image description here


If you want a chart with individual subplots:

grouped = df.groupby('ticker')

ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(ax=ax)

ax.legend()
plt.show()

enter image description here

Value Change Listener to JTextField

The usual answer to this is "use a DocumentListener". However, I always find that interface cumbersome. Truthfully the interface is over-engineered. It has three methods, for insertion, removal, and replacement of text, when it only needs one method: replacement. (An insertion can be viewed as a replacement of no text with some text, and a removal can be viewed as a replacement of some text with no text.)

Usually all you want is to know is when the text in the box has changed, so a typical DocumentListener implementation has the three methods calling one method.

Therefore I made the following utility method, which lets you use a simpler ChangeListener rather than a DocumentListener. (It uses Java 8's lambda syntax, but you can adapt it for old Java if needed.)

/**
 * Installs a listener to receive notification when the text of any
 * {@code JTextComponent} is changed. Internally, it installs a
 * {@link DocumentListener} on the text component's {@link Document},
 * and a {@link PropertyChangeListener} on the text component to detect
 * if the {@code Document} itself is replaced.
 * 
 * @param text any text component, such as a {@link JTextField}
 *        or {@link JTextArea}
 * @param changeListener a listener to receieve {@link ChangeEvent}s
 *        when the text is changed; the source object for the events
 *        will be the text component
 * @throws NullPointerException if either parameter is null
 */
public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
    Objects.requireNonNull(text);
    Objects.requireNonNull(changeListener);
    DocumentListener dl = new DocumentListener() {
        private int lastChange = 0, lastNotifiedChange = 0;

        @Override
        public void insertUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            lastChange++;
            SwingUtilities.invokeLater(() -> {
                if (lastNotifiedChange != lastChange) {
                    lastNotifiedChange = lastChange;
                    changeListener.stateChanged(new ChangeEvent(text));
                }
            });
        }
    };
    text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
        Document d1 = (Document)e.getOldValue();
        Document d2 = (Document)e.getNewValue();
        if (d1 != null) d1.removeDocumentListener(dl);
        if (d2 != null) d2.addDocumentListener(dl);
        dl.changedUpdate(null);
    });
    Document d = text.getDocument();
    if (d != null) d.addDocumentListener(dl);
}

Unlike with adding a listener directly to the document, this handles the (uncommon) case that you install a new document object on a text component. Additionally, it works around the problem mentioned in Jean-Marc Astesana's answer, where the document sometimes fires more events than it needs to.

Anyway, this method lets you replace annoying code which looks like this:

someTextBox.getDocument().addDocumentListener(new DocumentListener() {
    @Override
    public void insertUpdate(DocumentEvent e) {
        doSomething();
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        doSomething();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        doSomething();
    }
});

With:

addChangeListener(someTextBox, e -> doSomething());

Code released to public domain. Have fun!

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

How to set the initial zoom/width for a webview

in Kotlin You can use,

webView.isScrollbarFadingEnabled = true
webView.setInitialScale(100)

How can I assign the output of a function to a variable using bash?

VAR=$(scan)

Exactly the same way as for programs.

Center Oversized Image in Div

This is an old Q, but a modern solution without flexbox or position absolute works like this.

margin-left: 50%;
transform: translateX(-50%);

_x000D_
_x000D_
.outer {_x000D_
  border: 1px solid green;_x000D_
  margin: 20px auto;_x000D_
  width: 20%;_x000D_
  padding: 10px 0;_x000D_
  /*   overflow: hidden; */_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  width: 150%;_x000D_
  background-color: gold;_x000D_
  /* Set left edge of inner element to 50% of the parent element */_x000D_
  margin-left: 50%; _x000D_
  /* Move to the left by 50% of own width */_x000D_
  transform: translateX(-50%); _x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos exercitationem error nemo amet cum quia eaque alias nihil, similique laboriosam enim expedita fugit neque earum et esse ad, dolores sapiente sit cumque vero odit! Ullam corrupti iure eum similique magnam voluptatum ipsam. Maxime ad cumque ut atque suscipit enim quidem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi impedit esse modi, porro quibusdam voluptate dolores molestias, sit dolorum veritatis laudantium rem, labore et nobis ratione. Ipsum, aliquid totam repellendus non fugiat id magni voluptate, doloribus tenetur illo mollitia. Voluptatum.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So why does it work?
At first glance it seems that we shift 50% to the right and then 50% to the left again. That would result in zero shift, so what?
But the 50% are not the same, because context is important. If you use relative units, a margin will be calculated as percentage of the width of the parent element, while the transform will be 50% relative to the same element.

We have this situation before we add the CSS

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       +-----------------------------------------------------------+
       | Element E                                                 |
       +-----------------------------------------------------------+
       |                                           |
       +-------------------------------------------+

With the added style margin-left: 50% we have

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       |                     +-----------------------------------------------------------+
       |                     | Element E                                                 |
       |                     +-----------------------------------------------------------+
       |                     |                     |
       +---------------------|---------------------+
       |========= a ========>|

       a is 50% width of P

And the transform: translateX(-50%) shifts back to the left

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
+-----------------------------------------------------------+
| Element E                 |                               |
+-----------------------------------------------------------+
|<============ b ===========|                      |
       |                    |                      |
       +--------------------|----------------------+
       |========= a =======>|

       a is 50% width of P
       b is 50% width of E

Unfortunately this does only work for horizontal centering as the margin percentage calculation is always relative to the width. I.e. not only margin-left and margin-right, but also margin-top and margin-bottom are calculated with respect to width.

Browser compatibility should be no problem: https://caniuse.com/#feat=transforms2d

parsing a tab-separated file in Python

You can use the csv module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
        ... 

Where line is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip() builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
        ...

How can I declare optional function parameters in JavaScript?

Update

With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

Old answer

Default parameters in JavaScript can be implemented in mainly two ways:

function myfunc(a, b)
{
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    }
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    }
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";
}

The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

Alternative declaration:

function myfunc(a)
{
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument
    }
}

The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

Further considerations

Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables

How to export data to CSV in PowerShell?

what you are searching for is the Export-Csv file.csv

try using Get-Help Export-Csv to see whats possible

also Out-File -FilePath "file.csv" will work

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

How do I remove an array item in TypeScript?

let departments is an array. You want to remove an item from this array.

departments: string[] = [];

 removeDepartment(name: string): void {
    this.departments = this.departments.filter(item => item != name);
  }

Have a variable in images path in Sass?

We can use relative path instead of absolute path:

$assetPath: '~src/assets/images/';
$logo-img: '#{$assetPath}logo.png';
@mixin logo {
  background-image: url(#{$logo-img});
}

.logo {
    max-width: 65px;
    @include logo;
 }

Simulating a click in jQuery/JavaScript on a link

Just

$("#your_item").trigger("click");

using .trigger() you can simulate many type of events, just passing it as the parameter.

Using Java generics for JPA findAll() query with WHERE clause

This will work, and if you need where statement you can add it as parameter.

class GenericDAOWithJPA<T, ID extends Serializable> {

.......

public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

How to prevent downloading images and video files from my website?

Images must be downloaded in order to be viewed by the client. Videos are a similar case, in many scenarios. You can setup proxy scripts to serve the files out, but that doesn't really solve the issue of preventing the user from getting their own copy. For a more thorough discussion of this topic, see the question How can I prevent/make it hard to download my flash video?

Android: how do I check if activity is running?

if(!activity.isFinishing() && !activity.isDestroyed())

From the official docs:

Activity#isFinishing()

Check to see whether this activity is in the process of finishing, either because you called finish() on it or someone else has requested that it finished. This is often used in onPause() to determine whether the activity is simply pausing or completely finishing.

Activity#isDestroyed()

Returns true if the final onDestroy() call has been made on the Activity, so this instance is now dead.

How can I check the extension of a file?

#!/usr/bin/python

import shutil, os

source = ['test_sound.flac','ts.mp3']

for files in source:
  fileName,fileExtension = os.path.splitext(files)

  if fileExtension==".flac" :
    print 'This file is flac file %s' %files
  elif  fileExtension==".mp3":
    print 'This file is mp3 file %s' %files
  else:
    print 'Format is not valid'

how to use json file in html code

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>

<script>

    $(function() {


   var people = [];

   $.getJSON('people.json', function(data) {
       $.each(data.person, function(i, f) {
          var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
           "<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
           $(tblRow).appendTo("#userdata tbody");
     });

   });

});
</script>
</head>

<body>

<div class="wrapper">
<div class="profile">
   <table id= "userdata" border="2">
  <thead>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email Address</th>
            <th>City</th>
        </thead>
      <tbody>

       </tbody>
   </table>

</div>
</div>

</body>
</html>

My JSON file:

{
   "person": [
       {
           "firstName": "Clark",
           "lastName": "Kent",
           "job": "Reporter",
           "roll": 20
       },
       {
           "firstName": "Bruce",
           "lastName": "Wayne",
           "job": "Playboy",
           "roll": 30
       },
       {
           "firstName": "Peter",
           "lastName": "Parker",
           "job": "Photographer",
           "roll": 40
       }
   ]
}

I succeeded in integrating a JSON file to HTML table after working a day on it!!!

How to change the value of attribute in appSettings section with Web.config transformation

I do not like transformations to have any more info than needed. So instead of restating the keys, I simply state the condition and intention. It is much easier to see the intention when done like this, at least IMO. Also, I try and put all the xdt attributes first to indicate to the reader, these are transformations and not new things being defined.

<appSettings>
  <add xdt:Locator="Condition(@key='developmentModeUserId')" xdt:Transform="Remove" />
  <add xdt:Locator="Condition(@key='developmentMode')" xdt:Transform="SetAttributes"
       value="false"/>
</appSettings>

In the above it is much easier to see that the first one is removing the element. The 2nd one is setting attributes. It will set/replace any attributes you define here. In this case it will simply set value to false.

Can I delete data from the iOS DeviceSupport directory?

Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect

Refused to apply inline style because it violates the following Content Security Policy directive

As the error message says, you have an inline style, which CSP prohibits. I see at least one (list-style: none) in your HTML. Put that style in your CSS file instead.

To explain further, Content Security Policy does not allow inline CSS because it could be dangerous. From An Introduction to Content Security Policy:

"If an attacker can inject a script tag that directly contains some malicious payload .. the browser has no mechanism by which to distinguish it from a legitimate inline script tag. CSP solves this problem by banning inline script entirely: it’s the only way to be sure."

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

I have a struct KeyValuePairSerializable:

[Serializable]
public struct KeyValuePairSerializable<K, V>
{
    public KeyValuePairSerializable(KeyValuePair<K, V> pair)
    {
        Key = pair.Key;
        Value = pair.Value;
    }

    [XmlAttribute]
    public K Key { get; set; }

    [XmlText]
    public V Value { get; set; }

    public override string ToString()
    {
        return "[" + StringHelper.ToString(Key, "") + ", " + StringHelper.ToString(Value, "") + "]";
    }
}

Then, the XML serialization of a Dictionary property is by:

[XmlIgnore]
public Dictionary<string, string> Parameters { get; set; }

[XmlArray("Parameters")]
[XmlArrayItem("Pair")]
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // not necessary
public KeyValuePairSerializable<string, string>[] ParametersXml
{
    get 
    { 
        return Parameters?.Select(p => new KeyValuePairSerializable<string, string>(p)).ToArray(); 
    }
    set
    {
        Parameters = value?.ToDictionary(i => i.Key, i => i.Value);
    }
}

Just the property must be the array, not the List.

What should be the package name of android app?

package name with 0 may cause problem for sharedPreference.

(OK) con = createPackageContext("com.example.android.sf1", 0);

(Problem but no error)

con = createPackageContext("com.example.android.sf01", 0);

AngularJS does not send hidden field value

I've found a nice solution written by Mike on sapiensworks. It is as simple as using a directive that watches for changes on your model:

.directive('ngUpdateHidden',function() {
    return function(scope, el, attr) {
        var model = attr['ngModel'];
        scope.$watch(model, function(nv) {
            el.val(nv);
        });
    };
})

and then bind your input:

<input type="hidden" name="item.Name" ng-model="item.Name" ng-update-hidden />

But the solution provided by tymeJV could be better as input hidden doesn't fire change event in javascript as yycorman told on this post, so when changing the value through a jQuery plugin will still work.

Edit I've changed the directive to apply the a new value back to the model when change event is triggered, so it will work as an input text.

.directive('ngUpdateHidden', function () {
    return {
        restrict: 'AE', //attribute or element
        scope: {},
        replace: true,
        require: 'ngModel',
        link: function ($scope, elem, attr, ngModel) {
            $scope.$watch(ngModel, function (nv) {
                elem.val(nv);
            });
            elem.change(function () { //bind the change event to hidden input
                $scope.$apply(function () {
                    ngModel.$setViewValue(  elem.val());
                });
            });
        }
    };
})

so when you trigger $("#yourInputHidden").trigger('change') event with jQuery, it will update the binded model as well.

Get everything after and before certain character in SQL Server

I know this has been a while.. but here is an idea

declare @test varchar(25) = 'images/test.jpg'

select
 @test as column_name
 , parsename(replace(@test,'/','.'),1) as jpg
 ,parsename(replace(@test,'/','.'),2) as test
  ,parsename(replace(@test,'/','.'),3) as images

Python, creating objects

Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -

# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
    name = "Unknown name"
    age = 0
    major = "Unknown major"

You can create a make_student function by explicitly assigning the attributes to a new instance of Student -

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    return student

But it probably makes more sense to do this in a constructor (__init__) -

class Student(object):
    def __init__(self, name="Unknown name", age=0, major="Unknown major"):
        self.name = name
        self.age = age
        self.major = major

The constructor is called when you use Student(). It will take the arguments defined in the __init__ method. The constructor signature would now essentially be Student(name, age, major).

If you use that, then a make_student function is trivial (and superfluous) -

def make_student(name, age, major):
    return Student(name, age, major)

For fun, here is an example of how to create a make_student function without defining a class. Please do not try this at home.

def make_student(name, age, major):
    return type('Student', (object,),
                {'name': name, 'age': age, 'major': major})()

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

delete the module which is identified in .Net error message , 1 down vote

In Windows server 2012. Go to ISS -> Modules -> Remove the ServiceModel3-0. (without number worked for me)

How can I rollback an UPDATE query in SQL server 2005?

You can rollback the statements you've executed within a transaction. Instead of commiting the transaction, rollback the transaction.

If you have updated something and want to rollback those updates, and you haven't done this inside a (not-yet-commited) transaction, then I think it's though luck ...

(Manually repair, or, restore backups)

Removing address bar from browser (to view on Android)

If you've loaded jQuery, you can see if the height of the content is greater than the viewport height. If not, then you can make it that height (or a little less). I ran the following code in WVGA800 mode in the Android emulator, and then ran it on my Samsung Galaxy Tab, and in both cases it hid the addressbar.

$(document).ready(function() {

  if (navigator.userAgent.match(/Android/i)) {
    window.scrollTo(0,0); // reset in case prev not scrolled  
    var nPageH = $(document).height();
    var nViewH = window.outerHeight;
    if (nViewH > nPageH) {
      nViewH -= 250;
      $('BODY').css('height',nViewH + 'px');
    }
    window.scrollTo(0,1);
  }

});

How can I get the intersection, union, and subset of arrays in Ruby?

If Multiset extends from the Array class

x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]

UNION

x.union(y)           # => [1, 2, 4, 7]      (ONLY IN RUBY 2.6)
x.union(y, z)        # => [1, 2, 4, 7, 3]   (ONLY IN RUBY 2.6)
x | y                # => [1, 2, 4, 7]

DIFFERENCE

x.difference(y)      # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z)   # => [4] (ONLY IN RUBY 2.6)
x - y                # => [4, 7]

INTERSECTION

x & y                # => [1, 2]

For more info about the new methods in Ruby 2.6, you can check this blog post about its new features

Is it possible to simulate key press events programmatically?

What you can do is programmatically trigger keyevent listeners by firing keyevents. It makes sense to allow this from a sandboxed security-perspective. Using this ability, you can then apply a typical observer-pattern. You could call this method "simulating".

Below is an example of how to accomplish this in the W3C DOM standard along with jQuery:

function triggerClick() {
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
  var cb = document.querySelector('input[type=submit][name=btnK]'); 
  var canceled = !cb.dispatchEvent(event);
  if (canceled) {
    // preventDefault was called and the event cancelled
  } else {
    // insert your event-logic here...
  }
}

This example is adapted from: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

In jQuery:

jQuery('input[type=submit][name=btnK]')
  .trigger({
    type: 'keypress',
    which: character.charCodeAt(0 /*the key to trigger*/)      
   });

But as of recently, there is no [DOM] way to actually trigger keyevents leaving the browser-sandbox. And all major browser vendors will adhere to that security concept.

As for plugins such as Adobe Flash - which are based on the NPAPI-, and permit bypassing the sandbox: these are phasing-out ; Firefox.

Detailed Explanation:

You cannot and you must not for security reasons (as Pekka already pointed out). You will always require a user interaction in between. Additionally imagine the chance of the browser vendors getting sued by users, as various programmatic keyboard events will have led to spoofing attacks.

See this post for alternatives and more details. There is always the flash based copy-and-paste. Here is an elegant example. At the same time it is a testimony why the web is moving away from plugin vendors.

There is a similar security mindset applied in case of the opt-in CORS policy to access remote content programmatically.

The answer is:
There is no way to programmatically trigger input keys in the sandboxed browser environment under normal circumstances.

Bottomline: I am not saying it will not be possible in the future, under special browser-modes and/or privileges towards the end-goal of gaming, or similar user-experiences. However prior to entering such modes, the user will be asked for permissions and risks, similar to the Fullscreen API model.

Useful: In the context of KeyCodes, this tool and keycode mapping will come in handy.

Disclosure: The answer is based on the answer here.

What is the easiest way to encrypt a password when I save it to the registry?

You don't decrypt authentication passwords!

Hash them using something like the SHA256 provider and when you have to challenge, hash the input from the user and see if the two hashes match.

byte[] data = System.Text.Encoding.ASCII.GetBytes(inputString);
data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
String hash = System.Text.Encoding.ASCII.GetString(data);

Leaving passwords reversible is a really horrible model.

Edit2: I thought we were just talking about front-line authentication. Sure there are cases where you want to encrypt passwords for other things that need to be reversible but there should be a 1-way lock on top of it all (with a very few exceptions).

I've upgraded the hashing algorithm but for the best possible strength you want to keep a private salt and add that to your input before hashing it. You would do this again when you compare. This adds another layer making it even harder for somebody to reverse.

input() error - NameError: name '...' is not defined

Try using raw_input rather than input if you simply want to read strings.

print("Enter your name: ")
x = raw_input()
print("Hello, "+x)

Image contains the output screen

How do I detect when someone shakes an iPhone?

I came across this post looking for a "shaking" implementation. millenomi's answer worked well for me, although i was looking for something that required a bit more "shaking action" to trigger. I've replaced to Boolean value with an int shakeCount. I also reimplemented the L0AccelerationIsShaking() method in Objective-C. You can tweak the ammount of shaking required by tweaking the ammount added to shakeCount. I'm not sure i've found the optimal values yet, but it seems to be working well so far. Hope this helps someone:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    if (self.lastAcceleration) {
        if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7] && shakeCount >= 9) {
            //Shaking here, DO stuff.
            shakeCount = 0;
        } else if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7]) {
            shakeCount = shakeCount + 5;
        }else if (![self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.2]) {
            if (shakeCount > 0) {
                shakeCount--;
            }
        }
    }
    self.lastAcceleration = acceleration;
}

- (BOOL) AccelerationIsShakingLast:(UIAcceleration *)last current:(UIAcceleration *)current threshold:(double)threshold {
    double
    deltaX = fabs(last.x - current.x),
    deltaY = fabs(last.y - current.y),
    deltaZ = fabs(last.z - current.z);

    return
    (deltaX > threshold && deltaY > threshold) ||
    (deltaX > threshold && deltaZ > threshold) ||
    (deltaY > threshold && deltaZ > threshold);
}

PS: I've set the update interval to 1/15th of a second.

[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 15)];

Finding what branch a Git commit came from

khichar.anil covered most of this in his answer.

I am just adding the flag that will remove the tags from the revision names list. This gives us:

git name-rev --name-only --exclude=tags/* $SHA

How to upgrade glibc from version 2.13 to 2.15 on Debian?

Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.

I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.

here is a copy of the script I made for your solution but have dos2unix installed.

#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"

this script has been tested on 3 machines with no errors.

How to add (vertical) divider to a horizontal LinearLayout?

If the answer of Kapil Vats is not working try something like this:

drawable/divider_horizontal_green_22.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <size android:width="22dip"/>
    <solid android:color="#00ff00"/>

</shape>

layout/your_layout.xml

LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/llTopBar"
            android:orientation="horizontal"
            android:divider="@drawable/divider_horizontal_green_22"
            android:showDividers="middle"
           >

I encountered an issue where the padding attribute wasn't working, thus I had to set the height of the divider directly in the divider.

Note:

If you want to use it in vertical LinearLayout, make a new one, like this: drawable/divider_vertical_green_22.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <size android:height="22dip"/>
    <solid android:color="#00ff00"/>

</shape>

In R, how to find the standard error of the mean?

A version of John's answer above that removes the pesky NA's:

stderr <- function(x, na.rm=FALSE) {
  if (na.rm) x <- na.omit(x)
  sqrt(var(x)/length(x))
}

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Is it not possible to stringify an Error using JSON.stringify?

Modifying Jonathan's great answer to avoid monkey patching:

var stringifyError = function(err, filter, space) {
  var plainObject = {};
  Object.getOwnPropertyNames(err).forEach(function(key) {
    plainObject[key] = err[key];
  });
  return JSON.stringify(plainObject, filter, space);
};

var error = new Error('testing');
error.detail = 'foo bar';

console.log(stringifyError(error, null, '\t'));

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

You edit an element's value by editing it's .value property.

document.getElementById('DATE').value = 'New Value';

Get size of a View in React Native

Here is the code to get the Dimensions of the complete view of the device.

var windowSize = Dimensions.get("window");

Use it like this:

width=windowSize.width,heigth=windowSize.width/0.565

What is the difference between Integrated Security = True and Integrated Security = SSPI?

Many questions get answers if we use .Net Reflector to see the actual code of SqlConnection :) true and sspi are the same:

internal class DbConnectionOptions

...

internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
{
    if ((CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true")) || CompareInsensitiveInvariant(stringValue, "yes"))
    {
        return true;
    }
}

...

EDIT 20.02.2018 Now in .Net Core we can see its open source on github! Search for ConvertValueToIntegratedSecurityInternal method:

https://github.com/dotnet/corefx/blob/fdbb160aeb0fad168b3603dbdd971d568151a0c8/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs

Show pop-ups the most elegant way

It's funny because I'm learning Angular myself and was watching some video's from their channel on Youtube. The speaker mentions your exact problem in this video https://www.youtube.com/watch?v=ZhfUv0spHCY#t=1681 around the 28:30 minute mark.

It comes down to placing that particular piece of code in a service rather then a controller.

My guess would be to inject new popup elements into the DOM and handle them separate instead of showing and hiding the same element. This way you can have multiple popups.

The whole video is very interesting to watch as well :-)

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

Ignore Typescript Errors "property does not exist on value of type"

In my particular project I couldn't get it to work, and used declare var $;. Not a clean/recommended solution, it doesnt recognise the JQuery variables, but I had no errors after using that (and had to for my automatic builds to succeed).

Import-CSV and Foreach

Solution is to change Delimiter.

Content of the csv file -> Note .. Also space and , in value

Values are 6 Dutch word aap,noot,mies,Piet, Gijs, Jan

Col1;Col2;Col3

a,ap;noo,t;mi es

P,iet;G ,ijs;Ja ,n



$csv = Import-Csv C:\TejaCopy.csv -Delimiter ';' 

Answer:

Write-Host $csv
@{Col1=a,ap; Col2=noo,t; Col3=mi es} @{Col1=P,iet; Col2=G ,ijs; Col3=Ja ,n}

It is possible to read a CSV file and use other Delimiter to separate each column.

It worked for my script :-)

SQL Logic Operator Precedence: And and Or

I'll add 2 points:

  • "IN" is effectively serial ORs with parentheses around them
  • AND has precedence over OR in every language I know

So, the 2 expressions are simply not equal.

WHERE some_col in (1,2,3,4,5) AND some_other_expr
--to the optimiser is this
WHERE
     (
     some_col = 1 OR
     some_col = 2 OR 
     some_col = 3 OR 
     some_col = 4 OR 
     some_col = 5
     )
     AND
     some_other_expr

So, when you break the IN clause up, you split the serial ORs up, and changed precedence.

What does enumerate() mean?

It's a builtin function that returns an object that can be iterated over. See the documentation.

In short, it loops over the elements of an iterable (like a list), as well as an index number, combined in a tuple:

for item in enumerate(["a", "b", "c"]):
    print item

prints

(0, "a")
(1, "b")
(2, "c")

It's helpful if you want to loop over a sequence (or other iterable thing), and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate.

How to create a Calendar table for 100 years in Sql

This will create you the result in lightning fast.

select top 100000  identity (int ,1,1) as Sequence into Tally from sysobjects , sys.all_columns


select dateadd(dd,sequence,-1) Dates into CalenderTable from tally


delete from CalenderTable where dates < -- mention the mindate you need
delete from CalenderTable where dates >  -- mention the max date you need

Step 1 : Create a sequence table

Step 2 : Use the sequence table to generate the desired dates

Step 3 : Delete unwanted dates

How to set margin with jquery?

Set it with a px value. Changing the code like below should work

el.css('marginLeft', mrg + 'px');

How to convert integers to characters in C?

In C, int, char, long, etc. are all integers.

They typically have different memory sizes and thus different ranges as in INT_MIN to INT_MAX. char and arrays of char are often used to store characters and strings. Integers are stored in many types: int being the most popular for a balance of speed, size and range.

ASCII is by far the most popular character encoding, but others exist. The ASCII code for an 'A' is 65, 'a' is 97, '\n' is 10, etc. ASCII data is most often stored in a char variable. If the C environment is using ASCII encoding, the following all store the same value into the integer variable.

int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;

To convert an int to a char, simple assign:

int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4; 

This warning comes up because int typically has a greater range than char and so some loss-of-information may occur. By using the cast (char), the potential loss of info is explicitly directed.

To print the value of an integer:

printf("<%c>\n", c3); // prints <b>

// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>

// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>

printf("<%d>\n", i3); // prints <98>

There are additional issues about printing such as using %hhu or casting when printing an unsigned char, but leave that for later. There is a lot to printf().

How do I find out if first character of a string is a number?

regular expression starts with number->'^[0-9]' 
Pattern pattern = Pattern.compile('^[0-9]');
 Matcher matcher = pattern.matcher(String);

if(matcher.find()){

System.out.println("true");
}

How do I get the Git commit count?

How about making an alias ?

alias gc="git rev-list --all --count"      #Or whatever name you wish

How can I read Chrome Cache files?

Note: The flag show-saved-copy has been removed and the below answer will not work


You can read cached files using Chrome alone.

Chrome has a feature called Show Saved Copy Button:

Show Saved Copy Button Mac, Windows, Linux, Chrome OS, Android

When a page fails to load, if a stale copy of the page exists in the browser cache, a button will be presented to allow the user to load that stale copy. The primary enabling choice puts the button in the most salient position on the error page; the secondary enabling choice puts it secondary to the reload button. #show-saved-copy

First disconnect from the Internet to make sure that browser doesn't overwrite cache entry. Then navigate to chrome://flags/#show-saved-copy and set flag value to Enable: Primary. After you restart browser Show Saved Copy Button will be enabled. Now insert cached file URI into browser's address bar and hit enter. Chrome will display There is no Internet connection page alongside with Show saved copy button: enter image description here

After you hit the button browser will display cached file.

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

How can I see the current value of my $PATH variable on OS X?

for MacOS, make sure you know where the GO install

export GOPATH=/usr/local/go
PATH=$PATH:$GOPATH/bin

How to configure "Shorten command line" method for whole project in IntelliJ

Thanks to Rajesh Goel in Android Studio:

Run > Edit Configurations...

enter image description here

Select a test (better to select a parent test class) and set a Shorten command line: option to classpath file. Then OK (or Apply, OK).

enter image description here

How to swap two variables in JavaScript

(function(A, B){ b=A; a=B; })(parseInt(a), parseInt(b));

Java 8 Filter Array Using Lambda

even simpler, adding up to String[],

use built-in filter filter(StringUtils::isNotEmpty) of org.apache.commons.lang3

import org.apache.commons.lang3.StringUtils;

    String test = "a\nb\n\nc\n";
    String[] lines = test.split("\\n", -1);


    String[]  result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
    System.out.println(Arrays.toString(lines));
    System.out.println(Arrays.toString(result));

and output: [a, b, , c, ] [a, b, c]

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Pass C# ASP.NET array to Javascript array

In the page file:

<script type="text/javascript">
    var a = eval('[<% =string.Join(", ", numbers) %>]');
</script>

while in code behind:

public int[] numbers = WhatEverGetTheArray();

Center an item with position: relative

Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:

#parent {
    -webkit-box-align:center;
    -webkit-box-pack:center;
    display:-webkit-box;
}

How do I view executed queries within SQL Server Management Studio?

You need a SQL profiler, which actually runs outside SQL Management Studio. If you have a paid version of SQL Server (like the developer edition), it should be included in that as another utility.

If you're using a free edition (SQL Express), they have freeware profiles that you can download. I've used AnjLab's profiler (available at http://sites.google.com/site/sqlprofiler), and it seemed to work well.

Importing data from a JSON file into R

import httr package

library(httr)

Get the url

url <- "http://www.omdbapi.com/?apikey=72bc447a&t=Annie+Hall&y=&plot=short&r=json"
resp <- GET(url)

Print content of resp as text

content(resp, as = "text")

Print content of resp

content(resp)

Use content() to get the content of resp, but this time do not specify a second argument. R figures out automatically that you're dealing with a JSON, and converts the JSON to a named R list.

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

WordPress overrides PHP's memory limit to 256M, with the assumption that whatever it was set to before is going to be too low to render the dashboard. You can override this by defining WP_MAX_MEMORY_LIMIT in wp-config.php:

define( 'WP_MAX_MEMORY_LIMIT' , '512M' );

I agree with DanFromGermany, 256M is really a lot of memory for rendering a dashboard page. Changing the memory limit is really putting a bandage on the problem.

How to change the name of an iOS app?

If you want to change display name only then you can directly change from property file(plist) of app.

You can add a new row with the following key : bundle display name

Here is an example for this

enter image description here

When you use this the app name which you have given with this key will be display.

So you can do this simply.

Python error: AttributeError: 'module' object has no attribute

When you import lib, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py in the lib directory.

If you want access to your function, you can do something like this from lib.mod1 import mod1 and then run the mod12 function like so mod1.mod12().

If you want to be able to access mod1 when you import lib, you need to put an import mod1 inside the __init__.py file inside the lib directory.

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

on windows I made the iis development certificate trusted by using MMC (start > run > mmc), then add the certificate snapin, choosing "local computer" and accepting the defaults. Once that certificate snapip is added expand the local computer certificate tree to look under Personal, select the localhost certificate, right click > all task > export. accept all defaults in the exporting wizard.

Once that file is saved, expand trusted certificates and begin to import the cert you just exported. https://localhost is now trusted in chrome having no security warnings.

I used this guide resolution #2 from the MSDN blog, the op also shared a link in his question about that also should using MMC but this worked for me. resolution #2

Error: The 'brew link' step did not complete successfully

I completely uninstalled brew and started again, only to find the same problem again.

Brew appears to work by symlinking the required binaries into your system where other installation methods would typically copy the files.

I found an existing set of node libraries here:

/usr/local/include/node

After some head scratching I remembered installing node at the date against this old version and it hadn't been via brew.

I manually deleted this entire folder and successfully linked npm.

This would explain why using brew uninstall or even uninstall brew itself had no effect.

The highest ranked answer puts this very simply, but I thought I'd add my observations about why it's necessary.

I'm guessing a bunch of issues with other brew packages might be caused by old non-brew instances of packages being in the way.

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Oddly enough, the issue for me was I was trying to open 2012 SQL Server Integration Services on SSMS 2008 R2. When I opened the same in SSMS 2012, it connected right away.

Is it possible to print a variable's type in standard C++?

The other answers involving RTTI (typeid) are probably what you want, as long as:

  • you can afford the memory overhead (which can be considerable with some compilers)
  • the class names your compiler returns are useful

The alternative, (similar to Greg Hewgill's answer), is to build a compile-time table of traits.

template <typename T> struct type_as_string;

// declare your Wibble type (probably with definition of Wibble)
template <>
struct type_as_string<Wibble>
{
    static const char* const value = "Wibble";
};

Be aware that if you wrap the declarations in a macro, you'll have trouble declaring names for template types taking more than one parameter (e.g. std::map), due to the comma.

To access the name of the type of a variable, all you need is

template <typename T>
const char* get_type_as_string(const T&)
{
    return type_as_string<T>::value;
}

Value does not fall within the expected range

This might be due to the fact that you are trying to add a ListBoxItem with a same name to the page.

If you want to refresh the content of the listbox with the newly retrieved values you will have to first manually remove the content of the listbox other wise your loop will try to create lb_1 again and add it to the same list.

Look at here for a similar problem that occured Silverlight: Value does not fall within the expected range exception

Cheers,

How to validate domain name in PHP?

I think once you have isolated the domain name, say, using Erklan's idea:

$myUrl = "http://www.domain.com/link.php";
$myParsedURL = parse_url($myUrl);
$myDomainName= $myParsedURL['host'];

you could use :

if( false === filter_var( $myDomainName, FILTER_VALIDATE_URL ) ) {
// failed test

}

PHP5s Filter functions are for just such a purpose I would have thought.

It does not strictly answer your question as it does not use Regex, I realise.

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

Saving and Reading Bitmaps/Images from Internal memory in Android

if you want to follow Android 10 practices to write in storage, check here and if you only want the images to be app specific, here for example if you want to store an image just to be used by your app:

viewModelScope.launch(Dispatchers.IO) {
            getApplication<Application>().openFileOutput(filename, Context.MODE_PRIVATE).use {
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, it)
            }
        }

getApplication is a method to give you context for ViewModel and it's part of AndroidViewModel later if you want to read it:

viewModelScope.launch(Dispatchers.IO) {
            val savedBitmap = BitmapFactory.decodeStream(
                getApplication<App>().openFileInput(filename).readBytes().inputStream()
            )
        }

How do I check if file exists in jQuery or pure JavaScript?

A similar and more up-to-date approach.

$.get(url)
    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code
    })

How do I make a textbox that only accepts numbers?

Try a MaskedTextBox. It takes a simple mask format so you can limit the input to numbers or dates or whatever.

Purpose of #!/usr/bin/python3 shebang

#!/usr/bin/python3 is a shebang line.

A shebang line defines where the interpreter is located. In this case, the python3 interpreter is located in /usr/bin/python3. A shebang line could also be a bash, ruby, perl or any other scripting languages' interpreter, for example: #!/bin/bash.

Without the shebang line, the operating system does not know it's a python script, even if you set the execution flag (chmod +x script.py) on the script and run it like ./script.py. To make the script run by default in python3, either invoke it as python3 script.py or set the shebang line.

You can use #!/usr/bin/env python3 for portability across different systems in case they have the language interpreter installed in different locations.

Troubleshooting "Illegal mix of collations" error in mysql

Sometimes it can be dangerous to convert charsets, specially on databases with huge amounts of data. I think the best option is to use the "binary" operator:

e.g : WHERE binary table1.column1 = binary table2.column1

Visual Studio 2017: Display method references

In Visual Studio Professional or Enterprise you can enable CodeLens by doing this:

Tools ? Options ? Text Editor ? All Languages ? CodeLens

This is not available in the Community Edition

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

gc() can help

saving data as .RData, closing, re-opening R, and loading the RData can help.

see my answer here: https://stackoverflow.com/a/24754706/190791 for more details

SQL - ORDER BY 'datetime' DESC

  1. use single quotes for strings
  2. do NOT put single quotes around table names(use ` instead)
  3. do NOT put single quotes around numbers (you can, but it's harder to read)
  4. do NOT put AND between ORDER BY and LIMIT
  5. do NOT put = between ORDER BY, LIMIT keywords and condition

So you query will look like:

SELECT post_datetime 
FROM post 
WHERE type = 'published' 
ORDER BY post_datetime DESC 
LIMIT 3

Persist javascript variables across pages?

You can persist values using HTML5 storage, Flash Storage, or Gears. The dojo storage library provides a nice wrapper for this.

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

Just use

y_pred = (y_pred > 0.5)
accuracy_score(y_true, y_pred, normalize=False)

How can I align button in Center or right using IONIC framework?

You should put the button inside a div, and in the div you should be able to use the classes:
text-left, text-center and text-right.

for example:

<div class="row">
   <div class="col text-center">
      <button class="button button-small button-light">Search</button>
   </div>
</div>

And about the "textarea" position:

<div class="list">
<label class="item item-input">
    <span class="input-label">Date</span>
    <input type="text" placeholder="Text Area">
</label>

Demo using your code:
http://codepen.io/douglask/pen/zxXvYY

How do I truly reset every setting in Visual Studio 2012?

To reset your settings

  • On the Tools menu, click Import and Export Settings.
  • On the Welcome to the Import and Export Settings Wizard page, click Reset all settings and then click Next.
  • If you want to delete your current settings combination, choose No, just reset settings, overwriting all current settings, and then click Next. Select the programming language(s) you want to reset the setting for.

Click Finish.

The Reset Complete page alerts you to any problems encountered during the reset.

Validate decimal numbers in JavaScript - IsNumeric()

If I'm not mistaken, this should match any valid JavaScript number value, excluding constants (Infinity, NaN) and the sign operators +/- (because they are not actually part of the number as far as I concerned, they are separate operators):

I needed this for a tokenizer, where sending the number to JavaScript for evaluation wasn't an option... It's definitely not the shortest possible regular expression, but I believe it catches all the finer subtleties of JavaScript's number syntax.

/^(?:(?:(?:[1-9]\d*|\d)\.\d*|(?:[1-9]\d*|\d)?\.\d+|(?:[1-9]\d*|\d)) 
(?:[e]\d+)?|0[0-7]+|0x[0-9a-f]+)$/i

Valid numbers would include:

 - 0
 - 00
 - 01
 - 10
 - 0e1
 - 0e01
 - .0
 - 0.
 - .0e1
 - 0.e1
 - 0.e00
 - 0xf
 - 0Xf

Invalid numbers would be

 - 00e1
 - 01e1
 - 00.0
 - 00x0
 - .
 - .e0

T-sql - determine if value is integer

WHERE IsNumeric(MY_FIELD) = 1 AND CAST(MY_FIELD as VARCHAR(5)) NOT LIKE '%.%'

That is probably the simplest solution. Unless your MY_FIELD contains .00 or something of that sort. In which case, cast it to a float to remove any trailing .00s

Python extending with - using super() Python 3 vs Python 2

Another python3 implementation that involves the use of Abstract classes with super(). You should remember that

super().__init__(name, 10)

has the same effect as

Person.__init__(self, name, 10)

Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it. Hence super()gets translated to Person and then if you include the hidden self, you get the above code frag.

from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

    @abstractmethod
    def showName(self):
        pass

    @abstractmethod
    def showAge(self):
        pass


class Man(Person):

    def __init__(self, name, height):
        self.height = height
        # Person.__init__(self, name, 10)
        super().__init__(name, 10)  # same as Person.__init__(self, name, 10)
        # basically used to call the superclass init . This is used incase you want to call subclass init
        # and then also call superclass's init.
        # Since there's a hidden self in the super's parameters, when it's is called,
        # the superclasses attributes are a part of the same object that was sent out in the super() method

    def showIdentity(self):
        return self.name, self.age, self.height

    def showName(self):
        pass

    def showAge(self):
        pass


a = Man("piyush", "179")
print(a.showIdentity())

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

awk '/Dansk/{a=1}/Norsk/{b=1}/Svenska/{c=1}END{ if (a && b && c) print "0" }' 

you can then catch the return value with the shell

if you have Ruby(1.9+)

ruby -0777 -ne 'print if /Dansk/ and /Norsk/ and /Svenka/' file

Get the selected option id with jQuery

You can get it using the :selected selector, like this:

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});

Understanding Python super() with __init__() methods

super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.

Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of super(ChildB, self).__init__() which IMO is quite a bit nicer. The standard docs also refer to a guide to using super() which is quite explanatory.

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

Actually you can set custom text to that little blue button. In the xml file just use

android:imeActionLabel="whatever"

on your EditText.

Or in the java file use

etEditText.setImeActionLabel("whatever", EditorInfo.IME_ACTION_DONE);

I arbitrarily choose IME_ACTION_DONE as an example of what should go in the second parameter for this function. A full list of these actions can be found here.

It should be noted that this will not cause text to appear on all keyboards on all devices. Some keyboards do not support text on that button (e.g. swiftkey). And some devices don't support it either. A good rule is, if you see text already on the button, this will change it to whatever you'd want.

How to build a Horizontal ListView with RecyclerView?

Recycler View in Horizontal Dynamic.

Recycler View Implementation

RecyclerView musicList = findViewById(R.id.MusicList);

// RecyclerView musiclist = findViewById(R.id.MusicList1);
// RecyclerView musicLIST = findViewById(R.id.MusicList2);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
musicList.setLayoutManager(layoutManager);

String[] names = {"RAP", "CH SHB", "Faheem", "Anum", "Shoaib", "Laiba", "Zoki", "Komal", "Sultan","Mansoob Gull"};
musicList.setAdapter(new ProgrammingAdapter(names));'

Adapter class for recycler view, in which there is is a view holder for holding view of that recycler

public class ProgrammingAdapter 
     extendsRecyclerView.Adapter<ProgrammingAdapter.programmingViewHolder> {

private String[] data;

public ProgrammingAdapter(String[] data)
{
    this.data = data;
}

@Override
public programmingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.list_item_layout, parent, false);

    return new programmingViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull programmingViewHolder holder, int position) {
    String title = data[position];
    holder.textV.setText(title);
}

@Override
public int getItemCount() {
    return data.length;
}

public class programmingViewHolder extends RecyclerView.ViewHolder{
    ImageView img;
    TextView textV;
    public programmingViewHolder(View itemView) {
        super(itemView);
        img =  itemView.findViewById(R.id.img);
        textV =  itemView.findViewById(R.id.textt);
    }
}

Moment Js UTC to Local Time

This is what worked for me, it required moment-tz as well as moment though.

_x000D_
_x000D_
const guess = moment.utc(date).tz(moment.tz.guess());
const correctTimezone = guess.format()
_x000D_
_x000D_
_x000D_

export html table to csv

I found there is a library for this. See example here:

https://editor.datatables.net/examples/extensions/exportButtons.html

In addition to the above code, the following Javascript library files are loaded for use in this example:

In HTML, include following scripts:

jquery.dataTables.min.js   
dataTables.editor.min.js   
dataTables.select.min.js
dataTables.buttons.min.js  
jszip.min.js    
pdfmake.min.js
vfs_fonts.js  
buttons.html5.min.js    
buttons.print.min.js

Enable buttons by adding scripts like:

<script>
$(document).ready( function () {
    $('#table-arrays').DataTable({
        dom: '<"top"Blf>rt<"bottom"ip>',
        buttons: ['copy', 'excel', 'csv', 'pdf', 'print'],
        select: true,
    });
} );
</script>

For some reason, the excel export results in corrupted file, but can be repaired. Alternatively, disable excel and use csv export.

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

On top of @unutbu answer, you could coerce pandas numpy object array to native (float64) type, something along the line

import pandas as pd
pd.to_numeric(df['tester'], errors='coerce')

Specify errors='coerce' to force strings that can't be parsed to a numeric value to become NaN. Column type would be dtype: float64, and then isnan check should work

CSS transition fade on hover

I recommend you to use an unordered list for your image gallery.

You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.

#photos li {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;
}

#photos li:hover {
    opacity: 1;
}

Wait 5 seconds before executing next line

using angularjs:

$timeout(function(){
if(yourvariable===-1){
doSomeThingAfter5Seconds();
}
},5000)

Best way to find os name and version in Unix/Linux platform

With and Linux::Distribution, the cleanest solution for an old problem :

#!/bin/sh

perl -e '
    use Linux::Distribution qw(distribution_name distribution_version);

    my $linux = Linux::Distribution->new;
    if(my $distro = $linux->distribution_name()) {
          my $version = $linux->distribution_version();
          print "you are running $distro";
          print " version $version" if $version;
          print "\n";
    } else {
          print "distribution unknown\n";
    }
'

How do I change the android actionbar title and icon

Go to AndroidManifest.xml file. Find the <application> tag There you can see a attribute

android:label="@string/app_name"

Now go to res > values > strings.xml

Change the

<string name="app_name">MainActivity</string> 

to

<string name="app_name">Your Desired Name</string>

Example

AndroidManifest.xml

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SubmitForm">

        </activity>
    </application>

strings.xml

<resources>
    <string name="app_name">Your Desired Name</string>
    <string name="action_settings">Settings</string>
</resources>

What are major differences between C# and Java?

Generics:

With Java generics, you don't actually get any of the execution efficiency that you get with .NET because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. For instance if you have a Foo<T> class the java compiler generates Byte Code as if it was Foo<Object>. This means casting and also boxing/unboxing will have to be done in the "background".

I've been playing with Java/C# for a while now and, in my opinion, the major difference at the language level are, as you pointed, delegates.

Difference between webdriver.get() and webdriver.navigate()

Both perform the same function but driver.get(); seems more popular. driver.navigate().to(); is best used when you are already in the middle of a script and you want to redirect from current URL to a new one. For the sake of differentiating your codes, you can use driver.get();to launch the first URL after opening a browser instance, albeit both will work either way.

How to set default values in Rails?

i answered a similar question here.. a clean way to do this is using Rails attr_accessor_with_default

class SOF
  attr_accessor_with_default :is_awesome,true
end

sof = SOF.new
sof.is_awesome

=> true

UPDATE

attr_accessor_with_default has been deprecated in Rails 3.2.. you could do this instead with pure Ruby

class SOF
  attr_writer :is_awesome

  def is_awesome
    @is_awesome ||= true
  end
end

sof = SOF.new
sof.is_awesome

#=> true

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:

split -l 100000 database.sql database-

It will give files like:

database-aaa
database-aab
database-aac
...

How to use ImageBackground to set background image for screen in react-native

Here is a link to the RN docs: https://facebook.github.io/react-native/docs/images

A common feature request from developers familiar with the web is background-image. To handle this use case, you can use the <ImageBackground> component, which has the same props as <Image>, and add whatever children to it you would like to layer on top of it.

You might not want to use <ImageBackground> in some cases, since the implementation is very simple. Refer to <ImageBackground>'s source code for more insight, and create your own custom component when needed.

return (
  <ImageBackground source={require('./image.png')} style={{width: '100%', height: '100%'}}>
    <Text>Inside</Text>
  </ImageBackground>
);

Note that you must specify some width and height style attributes.

Note also that the file path is relative to the directory the component is in.

If condition inside of map() React

If you're a minimalist like me. Say you only want to render a record with a list containing entries.

<div>
  {data.map((record) => (
    record.list.length > 0
      ? (<YourRenderComponent record={record} key={record.id} />)
      : null
  ))}
</div>

How to get the file path from HTML input form in Firefox 3

For preview in Firefox works this - attachment is object of attachment element in first example:

           if (attachment.files)
             previewImage.src = attachment.files.item(0).getAsDataURL();
           else
             previewImage.src = attachment.value;

height: 100% for <div> inside <div> with display: table-cell

In Addition to jsFiddle, I can offer an ugly hack if you wish in order to make it cross-browser (IE11, Chrome, Firefox).

Instead of height:100%;, put height:1em; on the .cell.

How to show two figures using matplotlib?

Alternatively, I would suggest turning interactive on in the beginning and at the very last plot, turn it off. All will show up, but they will not disappear as your program will stay around until you close the figures.

import matplotlib.pyplot as plt
from matplotlib import interactive

plt.figure(1)
... code to make figure (1)

interactive(True)
plt.show()

plt.figure(2)
... code to make figure (2)

plt.show()

plt.figure(3)
... code to make figure (3)

interactive(False)
plt.show()

jQuery `.is(":visible")` not working in Chrome

If an item is child of an item that is hidden is(":visible") will return true, which is incorrect.

I just fixed this by added "display:inherit" to the child item. This will fixed it for me:

<div class="parent">
   <div class="child">
   </div>
<div>

and the CSS:

.parent{
   display: hidden;
}
.child{
   display: inherit;
}

Now the item can be effectively switched on and off by changing the visibility of the parent, and $(element).is(":visible") will return the visibility of the parent item

What is mutex and semaphore in Java ? What is the main difference?

Mutex is basically mutual exclusion. Only one thread can acquire the resource at once. When one thread acquires the resource, no other thread is allowed to acquire the resource until the thread owning the resource releases. All threads waiting for acquiring resource would be blocked.

Semaphore is used to control the number of threads executing. There will be fixed set of resources. The resource count will gets decremented every time when a thread owns the same. When the semaphore count reaches 0 then no other threads are allowed to acquire the resource. The threads get blocked till other threads owning resource releases.

In short, the main difference is how many threads are allowed to acquire the resource at once ?

  • Mutex --its ONE.
  • Semaphore -- its DEFINED_COUNT, ( as many as semaphore count)

Get nth character of a string in Swift programming language

Swift 3: another solution (tested in playground)

extension String {
    func substr(_ start:Int, length:Int=0) -> String? {
        guard start > -1 else {
            return nil
        }

        let count = self.characters.count - 1

        guard start <= count else {
            return nil
        }

        let startOffset = max(0, start)
        let endOffset = length > 0 ? min(count, startOffset + length - 1) : count

        return self[self.index(self.startIndex, offsetBy: startOffset)...self.index(self.startIndex, offsetBy: endOffset)]
    }
}

Usage:

let txt = "12345"

txt.substr(-1) //nil
txt.substr(0) //"12345"
txt.substr(0, length: 0) //"12345"
txt.substr(1) //"2345"
txt.substr(2) //"345"
txt.substr(3) //"45"
txt.substr(4) //"5"
txt.substr(6) //nil
txt.substr(0, length: 1) //"1"
txt.substr(1, length: 1) //"2"
txt.substr(2, length: 1) //"3"
txt.substr(3, length: 1) //"4"
txt.substr(3, length: 2) //"45"
txt.substr(3, length: 3) //"45"
txt.substr(4, length: 1) //"5"
txt.substr(4, length: 2) //"5"
txt.substr(5, length: 1) //nil
txt.substr(5, length: -1) //nil
txt.substr(-1, length: -1) //nil

Inserting multiple rows in a single SQL query?

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.

Example:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

Check if a String contains numbers Java

Try the following pattern:

.matches("[a-zA-Z ]*\\d+.*")

How do you get the file size in C#?

FileInfo.Length will return the length of file, in bytes (not size on disk), so this is what you are looking for, I think.

How to print out all the elements of a List in Java?

  1. You haven't specified what kind of elements the list contains, if it is a primitive data type then you can print out the elements.
  2. But if the elements are objects then as Kshitij Mehta mentioned you need to implement (override) the method "toString" within that object - if it is not already implemented - and let it return something meaning full from within the object, example:

    class Person {
        private String firstName;
        private String lastName;
    
        @Override
        public String toString() {
            return this.firstName + " " + this.lastName;
        }
    }
    

What's the difference between [ and [[ in Bash?

  • [ is the same as the test builtin, and works like the test binary (man test)
    • works about the same as [ in all the other sh-based shells in many UNIX-like environments
    • only supports a single condition. Multiple tests with the bash && and || operators must be in separate brackets.
    • doesn't natively support a 'not' operator. To invert a condition, use a ! outside the first bracket to use the shell's facility for inverting command return values.
    • == and != are literal string comparisons
  • [[ is a bash
    • is bash-specific, though others shells may have implemented similar constructs. Don't expect it in an old-school UNIX sh.
    • == and != apply bash pattern matching rules, see "Pattern Matching" in man bash
    • has a =~ regex match operator
    • allows use of parentheses and the !, &&, and || logical operators within the brackets to combine subexpressions

Aside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.

.NET DateTime to SqlDateTime Conversion

on my quest to do this with entitie, i stumbled over here, just hitting back to post what i've found out...

when using EF4, "a sql's" datetime column can be filled from .NET's DateTime using BitConverter.

EntitieObj.thetime = BitConverter.GetBytes(DateTime.Now.ToBinary());

also Fakrudeen's link brought me further... thank you.

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

Every Driver service in selenium calls the similar code(following is the firefox specific code) while creating the driver object

 @Override
 protected File findDefaultExecutable() {
      return findExecutable(
        "geckodriver", GECKO_DRIVER_EXE_PROPERTY,
        "https://github.com/mozilla/geckodriver",
        "https://github.com/mozilla/geckodriver/releases");
    }

now for the driver that you want to use, you have to set the system property with the value of path to the driver executable.

for firefox GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver" and this can be set before creating the driver object as below

System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe");
WebDriver driver = new FirefoxDriver();

What's the difference between Perl's backticks, system, and exec?

What's the difference between Perl's backticks (`), system, and exec?

exec -> exec "command"; ,
system -> system("command"); and 
backticks -> print `command`;

exec

exec executes a command and never resumes the Perl script. It's to a script like a return statement is to a function.

If the command is not found, exec returns false. It never returns true, because if the command is found, it never returns at all. There is also no point in returning STDOUT, STDERR or exit status of the command. You can find documentation about it in perlfunc, because it is a function.

E.g.:

#!/usr/bin/perl
print "Need to start exec command";
my $data2 = exec('ls');
print "Now END exec command";
print "Hello $data2\n\n";

In above code, there are three print statements, but due to exec leaving the script, only the first print statement is executed. Also, the exec command output is not being assigned to any variable.

Here, only you're only getting the output of the first print statement and of executing the ls command on standard out.

system

system executes a command and your Perl script is resumed after the command has finished. The return value is the exit status of the command. You can find documentation about it in perlfunc.

E.g.:

#!/usr/bin/perl
print "Need to start system command";
my $data2 = system('ls');
print "Now END system command";
print "Hello $data2\n\n";

In above code, there are three print statements. As the script is resumed after the system command, all three print statements are executed.

Also, the result of running system is assigned to data2, but the assigned value is 0 (the exit code from ls).

Here, you're getting the output of the first print statement, then that of the ls command, followed by the outputs of the final two print statements on standard out.

backticks (`)

Like system, enclosing a command in backticks executes that command and your Perl script is resumed after the command has finished. In contrast to system, the return value is STDOUT of the command. qx// is equivalent to backticks. You can find documentation about it in perlop, because unlike system and exec, it is an operator.

E.g.:

#!/usr/bin/perl
print "Need to start backticks command";
my $data2 = `ls`;
print "Now END system command";
print "Hello $data2\n\n";

In above code, there are three print statements and all three are being executed. The output of ls is not going to standard out directly, but assigned to the variable data2 and then printed by the final print statement.

How can I determine whether a 2D Point is within a Polygon?

Really like the solution posted by Nirg and edited by bobobobo. I just made it javascript friendly and a little more legible for my use:

function insidePoly(poly, pointx, pointy) {
    var i, j;
    var inside = false;
    for (i = 0, j = poly.length - 1; i < poly.length; j = i++) {
        if(((poly[i].y > pointy) != (poly[j].y > pointy)) && (pointx < (poly[j].x-poly[i].x) * (pointy-poly[i].y) / (poly[j].y-poly[i].y) + poly[i].x) ) inside = !inside;
    }
    return inside;
}

jQuery autocomplete with callback ajax json

I hope this helps:

var token = document.getElementById('token').value;
var nombre = document.getElementById('txtNombre').value;    

$("#txtNombre").keyup(function () {
    $.ajax({
        type: "POST",
        url: host() + "Formulario/BuscarNombreAutocompletar/",
        data: JSON.stringify({ "nombre": nombre }),
        headers: {
            'Authorization': 'Bearer ' + token
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var dataArray = [];
            if (controlCarga(data)) {

                $.each(data[1], function (i, item) {
                    dataArray.push(item.frmNombre)
                });

                $('#txtNombre').autocomplete({
                    clearButton: true,
                    source: dataArray,
                    selectFirst: true,
                    minLength: 2
                });
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('Error: ' + xhr.responseText);
        }
    });
});

Can someone explain how to implement the jQuery File Upload plugin?

Hi try bellow link it is very easy. I've been stuck for long time and it solve my issue in few minutes. http://simpleupload.michaelcbrook.com/#examples

iOS Swift - Get the Current Local Time and Date Timestamp

If you just want the unix timestamp, create an extension:

extension Date {
    func currentTimeMillis() -> Int64 {
        return Int64(self.timeIntervalSince1970 * 1000)
    }
}

Then you can use it just like in other programming languages:

let timestamp = Date().currentTimeMillis()

How to set JFrame to appear centered, regardless of monitor resolution?

Use setLocationRelativeTo(null)

This method has a special effect when you pass it a null. According to the Javadoc:

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

This should be done after setting the size or calling pack(), but before setting it visible, like this:

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Android Studio - Failed to notify project evaluation listener error

In my case I had to update all the Firebase libraries to the latest versions.

Disable building workspace process in Eclipse

You can switch to manual build so can control when this is done. Just make sure that Project > Build Automatically from the main menu is unchecked.

Numpy matrix to array

First, Mv = numpy.asarray(M.T), which gives you a 4x1 but 2D array.

Then, perform A = Mv[0,:], which gives you what you want. You could put them together, as numpy.asarray(M.T)[0,:].

Indentation Error in Python

This has happened with me too, python is space sensitive, so after " : "(colon) you might have left a space,
for example: [space is represented by "."]

`if command == 'HOWMANY':.
     opcodegroupr = "A0"
     opcoder = "85"
 elif command == 'IDENTIFY':.
     opcodegroupr = "A0"
     opcoder = "81"`

so try removing the unnecessary spaces,if you open it in IDE your cursor will be displayed away from ":" something like :- "if command == 'HOWMANY': |"
....whereas it should be:- "if command == 'HOWMANY':| "

How to set border on jPanel?

Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:

public GoBoard(){
    this.linien = 9;
    this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
}

public GoBoard(int pLinien){
    this.linien = pLinien;

}

If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:

// default constructor
public GoBoard(){
    this(9);  // calls other constructor
}

public GoBoard(int pLinien){
    this.linien = pLinien;
    this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
}

edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,

class GoTest {
   private static final int JB_WIDTH = 400;
   private static final int JB_HEIGHT = JB_WIDTH;

   private static void initGui() {
      JFrame frame = new JFrame("GoBoard");
      GoBoard jboard = new GoBoard();
      jboard.setLayout(new BorderLayout(10, 10));

      JPanel holdingPanel = new JPanel(new BorderLayout());
      int eb = 20;
      holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
      holdingPanel.add(jboard, BorderLayout.CENTER);
      frame.add(holdingPanel, BorderLayout.CENTER);
      jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      //!! frame.setSize(400, 400);
      frame.pack();
      frame.setVisible(true);
   }

// .... etc....

Styling an anchor tag to look like a submit button

Style your change the Submit button to an anchor tag instead and submit using javascript:

<a class="link-button" href="javascript:submit();">Submit</a>
<a class="link-button" href="some_url">Cancel</a>

function submit() {
    var form = document.getElementById("form_id");
    form.submit();
}

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

This is simple solution for this warning:

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. There is a server Option Tab. inside that tab click check Box to activate "Publish module contents to separate XML files".

Finally, restart your server, the message must disappear.

what innerHTML is doing in javascript?

It represents the textual contents of a given HTML tag. Can also contain tags of its own.

Expected corresponding JSX closing tag for input Reactjs

You need to close the input element with a /> at the end.

<input id="icon_prefix" type="text" class="validate" />

Could not find an implementation of the query pattern

For those of you (like me) that wasted too much time from this error:

I had received the same error: "Could not find implementation of query Pattern for source type 'DbSet'" but the solution for me was fixing a mistake at the DbContext level.

When I created my context I had this:

public class ContactContext : DbContext
    {
        public ContactContext() : base() { }

        public DbSet Contacts { get; set; }
    }

And my Repository (I was following a Repository pattern in ASP.NET guide) looked like this:

public Contact FindById(int id)
    {       
        var contact = from c in _db.Contacts where c.Id == id select c;
        return contact;
    }

My issue came from the initial setup of my DbContext, when I used DbSet as a generic instead of the type.

I changed public DbSet Contacts { get; set; } to public DbSet<Contact> Contacts { get; set; } and suddenly the query was recognized.


This is probably what k.m says in his answer, but since he mentioned IEnumerable<t> and not DbSet<<YourDomainObject>> I had to dig around in the code for a couple hours to find the line that caused this headache.

How to remove extension from string (only real extension!)

You could use what PHP has built in to assist...

$withoutExt = pathinfo($path, PATHINFO_DIRNAME) . '/' . pathinfo($path, PATHINFO_FILENAME);

Though if you are only dealing with a filename (.somefile.jpg), you will get...

./somefile

See it on CodePad.org

Or use a regex...

$withoutExt = preg_replace('/\.' . preg_quote(pathinfo($path, PATHINFO_EXTENSION), '/') . '$/', '', $path);

See it on CodePad.org

If you don't have a path, but just a filename, this will work and be much terser...

$withoutExt = pathinfo($path, PATHINFO_FILENAME);

See it on CodePad.org

Of course, these both just look for the last period (.).

Rounding up to next power of 2

An efficient Microsoft (e.g., Visual Studio 2017) specific solution in C / C++ for integer input. Handles the case of the input exactly matching a power of two value by decrementing before checking the location of the most significant 1 bit.

inline unsigned int ExpandToPowerOf2(unsigned int Value)
{
    unsigned long Index;
    _BitScanReverse(&Index, Value - 1);
    return (1U << (Index + 1));
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

#if defined(WIN64) // The _BitScanReverse64 intrinsic is only available for 64 bit builds because it depends on x64

inline unsigned long long ExpandToPowerOf2(unsigned long long Value)
{
    unsigned long Index;
    _BitScanReverse64(&Index, Value - 1);
    return (1ULL << (Index + 1));
}

#endif

This generates 5 or so inlined instructions for an Intel processor similar to the following:

dec eax
bsr rcx, rax
inc ecx
mov eax, 1
shl rax, cl

Apparently the Visual Studio C++ compiler isn't coded to optimize this for compile-time values, but it's not like there are a whole lot of instructions there.

Edit:

If you want an input value of 1 to yield 1 (2 to the zeroth power), a small modification to the above code still generates straight through instructions with no branch.

inline unsigned int ExpandToPowerOf2(unsigned int Value)
{
    unsigned long Index;
    _BitScanReverse(&Index, --Value);
    if (Value == 0)
        Index = (unsigned long) -1;
    return (1U << (Index + 1));
}

Generates just a few more instructions. The trick is that Index can be replaced by a test followed by a cmove instruction.

php search array key and get value

array_search('20120504', array_keys($your_array));

Linq to SQL .Sum() without group ... into

you can:

itemsCart.Select(c=>c.Price).Sum();

To hit the db only once do:

var itemsInCart = (from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
                  ).ToList();
var sum = itemsCart.Select(c=>c.Price).Sum();

The extra round-trip saved is worth it :)

Calculate distance between 2 GPS coordinates

C# Version of Haversine

double _eQuatorialEarthRadius = 6378.1370D;
double _d2r = (Math.PI / 180D);

private int HaversineInM(double lat1, double long1, double lat2, double long2)
{
    return (int)(1000D * HaversineInKM(lat1, long1, lat2, long2));
}

private double HaversineInKM(double lat1, double long1, double lat2, double long2)
{
    double dlong = (long2 - long1) * _d2r;
    double dlat = (lat2 - lat1) * _d2r;
    double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
    double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
    double d = _eQuatorialEarthRadius * c;

    return d;
}

Here's a .NET Fiddle of this, so you can test it out with your own Lat/Longs.

The following untracked working tree files would be overwritten by merge, but I don't care

If this is a one-time operation, you could just remove all untracked files from the working directory before doing the pull. Read How to remove local (untracked) files from the current Git working tree? for information on how to remove all untracked files.

Be sure to not accidentally remove untracked file that you still need ;)

Launching a website via windows commandline

Ok, The Windows 10 BatchFile is done works just like I had hoped. First press the windows key and R. Type mmc and Enter. In File Add SnapIn>Got to a specific Website and add it to the list. Press OK in the tab, and on the left side console root menu double click your site. Once it opens Add it to favourites. That should place it in C:\Users\user\AppData\Roaming\Microsoft\StartMenu\Programs\Windows Administrative Tools. I made a shortcut of this to a folder on the desktop. Right click the Shortcut and view the properties. In the Shortcut tab of the Properties click advanced and check the Run as Administrator. The Start in Location is also on the Shortcuts Tab you can add that to your batch file if you need. The Batch I made is as follows

@echo off
title Manage SiteEnviro
color 0a
:Clock
cls
echo Date:%date% Time:%time%
pause
cls
c:\WINDOWS\System32\netstat
c:\WINDOWS\System32\netstat -an
goto Greeting

:Greeting
cls
echo Open ShellSite
pause
cls
goto Manage SiteEnviro

:Manage SiteEnviro
"C:\Users\user\AppData\Roaming\Microsoft\Start Menu\Programs\Administrative Tools\YourCustomSavedMMC.msc"

You need to make a shortcut when you save this as a bat file and in the properties>shortcuts>advanced enable administrator access, can also set a keybind there and change the icon if you like. I probably did not need :Clock. The netstat commands can change to setting a hosted network or anything you want including nothing. Can Canscade websites in 1 mmc console and have more than 1 favourite added into the batch file.

Getting current unixtimestamp using Moment.js

For anyone who finds this page looking for unix timestamp w/ milliseconds, the documentation says

moment().valueOf()

or

+moment();

you can also get it through moment().format('x') (or .format('X') [capital X] for unix seconds with decimal milliseconds), but that will give you a string. Which moment.js won't actually parse back afterwards, unless you convert/cast it back to a number first.

Remove redundant paths from $PATH variable

For an easy copy-paste template I use this Perl snippet:

PATH=`echo $PATH | perl -pe s:/path/to/be/excluded::`

This way you don't need to escape the slashes for the substitute operator.

Calculating the difference between two Java date instances

The JDK Date API is horribly broken unfortunately. I recommend using Joda Time library.

Joda Time has a concept of time Interval:

Interval interval = new Interval(oldTime, new Instant());

EDIT: By the way, Joda has two concepts: Interval for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration that represents a length of time without the actual time boundaries (e.g. represent two hours!)

If you only care about time comparisions, most Date implementations (including the JDK one) implements Comparable interface which allows you to use the Comparable.compareTo()

How to get SQL from Hibernate Criteria API (*not* for logging)

For those using NHibernate, this is a port of [ram]'s code

public static string GenerateSQL(ICriteria criteria)
    {
        NHibernate.Impl.CriteriaImpl criteriaImpl = (NHibernate.Impl.CriteriaImpl)criteria;
        NHibernate.Engine.ISessionImplementor session = criteriaImpl.Session;
        NHibernate.Engine.ISessionFactoryImplementor factory = session.Factory;

        NHibernate.Loader.Criteria.CriteriaQueryTranslator translator = 
            new NHibernate.Loader.Criteria.CriteriaQueryTranslator(
                factory, 
                criteriaImpl, 
                criteriaImpl.EntityOrClassName, 
                NHibernate.Loader.Criteria.CriteriaQueryTranslator.RootSqlAlias);

        String[] implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName);

        NHibernate.Loader.Criteria.CriteriaJoinWalker walker = new NHibernate.Loader.Criteria.CriteriaJoinWalker(
            (NHibernate.Persister.Entity.IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]),
                                translator,
                                factory,
                                criteriaImpl,
                                criteriaImpl.EntityOrClassName,
                                session.EnabledFilters);

        return walker.SqlString.ToString();
    }