Programs & Examples On #Oocss

OOCSS (Object-oriented CSS) is an initiative by Nicole Sullivan. It is a CSS design pattern, intended to give developers the opportunity to write CSS that is straight-forward to implement, executes fast (as in browser reflows and repaints) and easy to maintain.

How to add anything in <head> through jquery/javascript?

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

Make DOM element like so:

link=document.createElement('link');
link.href='href';
link.rel='rel';

document.getElementsByTagName('head')[0].appendChild(link);

Plot multiple boxplot in one graph

You should get your data in a specific format by melting your data (see below for how melted data looks like) before you plot. Otherwise, what you have done seems to be okay.

require(reshape2)
df <- read.csv("TestData.csv", header=T)
# melting by "Label". `melt is from the reshape2 package. 
# do ?melt to see what other things it can do (you will surely need it)
df.m <- melt(df, id.var = "Label")
> df.m # pasting some rows of the melted data.frame

#     Label variable      value
# 1    Good       F1 0.64778924
# 2    Good       F1 0.54608791
# 3    Good       F1 0.46134200
# 4    Good       F1 0.79421221
# 5    Good       F1 0.56919951
# 6    Good       F1 0.73568570
# 7    Good       F1 0.65094207
# 8    Good       F1 0.45749702
# 9    Good       F1 0.80861929
# 10   Good       F1 0.67310067
# 11   Good       F1 0.68781739
# 12   Good       F1 0.47009455
# 13   Good       F1 0.95859182
# 14   Good       F1 1.00000000
# 15   Good       F1 0.46908343
# 16    Bad       F1 0.57875528
# 17    Bad       F1 0.28938046
# 18    Bad       F1 0.68511766

require(ggplot2)
ggplot(data = df.m, aes(x=variable, y=value)) + geom_boxplot(aes(fill=Label))

boxplot_ggplot2

Edit: I realise that you might need to facet. Here's an implementation of that as well:

p <- ggplot(data = df.m, aes(x=variable, y=value)) + 
             geom_boxplot(aes(fill=Label))
p + facet_wrap( ~ variable, scales="free")

ggplot2_faceted

Edit 2: How to add x-labels, y-labels, title, change legend heading, add a jitter?

p <- ggplot(data = df.m, aes(x=variable, y=value)) 
p <- p + geom_boxplot(aes(fill=Label))
p <- p + geom_jitter()
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p 

ggplot2_geom_plot

Edit 3: How to align geom_point() points to the center of box-plot? It could be done using position_dodge. This should work.

require(ggplot2)
p <- ggplot(data = df.m, aes(x=variable, y=value)) 
p <- p + geom_boxplot(aes(fill = Label))
# if you want color for points replace group with colour=Label
p <- p + geom_point(aes(y=value, group=Label), position = position_dodge(width=0.75))
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p 

ggplot2_position_dodge_geom_point

MySQL COUNT DISTINCT

You need to use a group by clause.

SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id

Converting Epoch time into the datetime

>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
'2012-09-13 14:22:50' # Local time

To get UTC:

>>> datetime.datetime.utcfromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
  '2012-09-13 06:22:50'

How to read a large file line by line?

This how I manage with very big file (tested with up to 100G). And it's faster than fgets()

$block =1024*1024;//1MB or counld be any higher than HDD block_size*2
if ($fh = fopen("file.txt", "r")) { 
    $left='';
    while (!feof($fh)) {// read the file
       $temp = fread($fh, $block);  
       $fgetslines = explode("\n",$temp);
       $fgetslines[0]=$left.$fgetslines[0];
       if(!feof($fh) )$left = array_pop($lines);           
       foreach ($fgetslines as $k => $line) {
           //do smth with $line
        }
     }
}
fclose($fh);

What is difference between INNER join and OUTER join

Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
Left outer join - A left outer join will give all rows in A, plus any common rows in B.
Full outer join - A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa. check this

What's the fastest way of checking if a point is inside a polygon in python

If speed is what you need and extra dependencies are not a problem, you maybe find numba quite useful (now it is pretty easy to install, on any platform). The classic ray_tracing approach you proposed can be easily ported to numba by using numba @jit decorator and casting the polygon to a numpy array. The code should look like:

@jit(nopython=True)
def ray_tracing(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside

The first execution will take a little longer than any subsequent call:

%%time
polygon=np.array(polygon)
inside1 = [numba_ray_tracing_method(point[0], point[1], polygon) for 
point in points]

CPU times: user 129 ms, sys: 4.08 ms, total: 133 ms
Wall time: 132 ms

Which, after compilation will decrease to:

CPU times: user 18.7 ms, sys: 320 µs, total: 19.1 ms
Wall time: 18.4 ms

If you need speed at the first call of the function you can then pre-compile the code in a module using pycc. Store the function in a src.py like:

from numba import jit
from numba.pycc import CC
cc = CC('nbspatial')


@cc.export('ray_tracing',  'b1(f8, f8, f8[:,:])')
@jit(nopython=True)
def ray_tracing(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


if __name__ == "__main__":
    cc.compile()

Build it with python src.py and run:

import nbspatial

import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in 
np.linspace(0,2*np.pi,lenpoly)[:-1]]

# random points set of points to test 
N = 10000
# making a list instead of a generator to help debug
points = zip(np.random.random(N),np.random.random(N))

polygon = np.array(polygon)

%%time
result = [nbspatial.ray_tracing(point[0], point[1], polygon) for point in points]

CPU times: user 20.7 ms, sys: 64 µs, total: 20.8 ms
Wall time: 19.9 ms

In the numba code I used: 'b1(f8, f8, f8[:,:])'

In order to compile with nopython=True, each var needs to be declared before the for loop.

In the prebuild src code the line:

@cc.export('ray_tracing' , 'b1(f8, f8, f8[:,:])')

Is used to declare the function name and its I/O var types, a boolean output b1 and two floats f8 and a two-dimensional array of floats f8[:,:] as input.

Edit Jan/4/2021

For my use case, I need to check if multiple points are inside a single polygon - In such a context, it is useful to take advantage of numba parallel capabilities to loop over a series of points. The example above can be changed to:

from numba import jit, njit
import numba
import numpy as np 

@jit(nopython=True)
def pointinpolygon(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in numba.prange(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
    D = np.empty(len(points), dtype=numba.boolean) 
    for i in numba.prange(0, len(D)):
        D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
    return D    

Note: pre-compiling the above code will not enable the parallel capabilities of numba (parallel CPU target is not supported by pycc/AOT compilation) see: https://github.com/numba/numba/issues/3336

Test:


import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]
polygon = np.array(polygon)
N = 10000
points = np.random.uniform(-1.5, 1.5, size=(N, 2))

For N=10000 on a 72 core machine, returns:

%%timeit
parallelpointinpolygon(points, polygon)
# 480 µs ± 8.19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Edit 17 Feb '21:

  • fixing loop to start from 0 instead of 1 (thanks @mehdi):

for i in numba.prange(0, len(D))

Edit 20 Feb '21:

Follow-up on the comparison made by @mehdi, I am adding a GPU-based method below. It uses the point_in_polygon method, from the cuspatial library:

    import numpy as np
    import cudf
    import cuspatial

    N = 100000002
    lenpoly = 1000
    polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in 
    np.linspace(0,2*np.pi,lenpoly)]
    polygon = np.array(polygon)
    points = np.random.uniform(-1.5, 1.5, size=(N, 2))


    x_pnt = points[:,0]
    y_pnt = points[:,1]
    x_poly =polygon[:,0]
    y_poly = polygon[:,1]
    result = cuspatial.point_in_polygon(
        x_pnt,
        y_pnt,
        cudf.Series([0], index=['geom']),
        cudf.Series([0], name='r_pos', dtype='int32'), 
        x_poly, 
        y_poly,
    )

Following @Mehdi comparison. For N=100000002 and lenpoly=1000 - I got the following results:

 time_parallelpointinpolygon:         161.54760098457336 
 time_mpltPath:                       307.1664695739746 
 time_ray_tracing_numpy_numba:        353.07356882095337 
 time_is_inside_sm_parallel:          37.45389246940613 
 time_is_inside_postgis_parallel:     127.13793849945068 
 time_is_inside_rapids:               4.246025562286377

point in poligon methods comparison, #poins: 10e07

hardware specs:

  • CPU Intel xeon E1240
  • GPU Nvidia GTX 1070

Notes:

  • The cuspatial.point_in_poligon method, is quite robust and powerful, it offers the ability to work with multiple and complex polygons (I guess at the expense of performance)

  • The numba methods can also be 'ported' on the GPU - it will be interesting to see a comparison which includes a porting to cuda of fastest method mentioned by @Mehdi (is_inside_sm).

How to import a csv file into MySQL workbench?

I guess you're missing the ENCLOSED BY clause

LOAD DATA LOCAL INFILE '/path/to/your/csv/file/model.csv'
INTO TABLE test.dummy FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n';

And specify the csv file full path

Load Data Infile - MySQL documentation

How to SELECT the last 10 rows of an SQL table which has no ID field?

you can with code select 10 row from end of table. select * from (SELECT * FROM table1 order by id desc LIMIT 10) as table2 order by id"

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

The problem is that a template doesn't generate an actual class, it's just a template telling the compiler how to generate a class. You need to generate a concrete class.

The easy and natural way is to put the methods in the header file. But there is another way.

In your .cpp file, if you have a reference to every template instantiation and method you require, the compiler will generate them there for use throughout your project.

new stack.cpp:

#include <iostream>
#include "stack.hpp"
template <typename Type> stack<Type>::stack() {
        std::cerr << "Hello, stack " << this << "!" << std::endl;
}
template <typename Type> stack<Type>::~stack() {
        std::cerr << "Goodbye, stack " << this << "." << std::endl;
}
static void DummyFunc() {
    static stack<int> stack_int;  // generates the constructor and destructor code
    // ... any other method invocations need to go here to produce the method code
}

How to disable compiler optimizations in gcc?

You can disable optimizations if you pass -O0 with the gcc command-line.

E.g. to turn a .C file into a .S file call:

gcc -O0 -S test.c

Windows equivalent of the 'tail' command

you can also use Git bash where head and tail are emulated as well

If statement in aspx page

<div>
    <% 
        if (true)
        {
    %>
    <div>
        Show true content
    </div>
    <%
        }
        else
        {
    %>
    <div>
        Show false content
    </div>
    <%
        }
    %>
</div>

Difference between Key, Primary Key, Unique Key and Index in MySQL

KEY and INDEX are synonyms in MySQL. They mean the same thing. In databases you would use indexes to improve the speed of data retrieval. An index is typically created on columns used in JOIN, WHERE, and ORDER BY clauses.

Imagine you have a table called users and you want to search for all the users which have the last name 'Smith'. Without an index, the database would have to go through all the records of the table: this is slow, because the more records you have in your database, the more work it has to do to find the result. On the other hand, an index will help the database skip quickly to the relevant pages where the 'Smith' records are held. This is very similar to how we, humans, go through a phone book directory to find someone by the last name: We don't start searching through the directory from cover to cover, as long we inserted the information in some order that we can use to skip quickly to the 'S' pages.

Primary keys and unique keys are similar. A primary key is a column, or a combination of columns, that can uniquely identify a row. It is a special case of unique key. A table can have at most one primary key, but more than one unique key. When you specify a unique key on a column, no two distinct rows in a table can have the same value.

Also note that columns defined as primary keys or unique keys are automatically indexed in MySQL.

Angular 4 checkbox change value

You can use this:

<input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">

And on your ts file,

changeStatus(id, e) {
    var status = e.target.checked;
    this.yourseverice.changeStatus(id, status).subscribe(result => {
        if (status)
            this.notify.success(this.l('AddedAsKeyPeople'));
        else
            this.notify.success(this.l('RemovedFromKeyPeople'));

    });
}

Here, record is the model for current row and status is boolean value.

Send HTTP GET request with header

Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.

/**
 * HTTP request types
 */
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

/**
 * HTTP request header constants
 */
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
    }

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    }
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    //.... code omitted ....//

}

How do I get the APK of an installed app without root access?

Open ES explorer -> push Menu button at the left upper corner (three horizontal stripes) -> in the Libraries section choose APPs.

Thus, you get the list of all the user apps. Find your app and select it with long pushing on it. Then press "More" in the right low corner and choose "Send". Then you can use different options, e.g. you can choose "ES Save To" in order to save the .apk file to your home directory or anywhere else.

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

Catch checked change event of a checkbox

Use the :checked selector to determine the checkbox's state:

$('input[type=checkbox]').click(function() {
    if($(this).is(':checked')) {
        ...
    } else {
        ...
    }
});

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

My solution to this would be to use the string.replace() to convert these items to a string:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

How long do browsers cache HTTP 301s?

On the latest Google Chrome Version 79, you can use the chrome://net-internals and select on DNS from the left panel, then tap the Clear host cache button

Screenshot of chrome opening the net-internals page

Simplest way to detect keypresses in javascript

There are a few ways to handle that; Vanilla JavaScript can do it quite nicely:

function code(e) {
    e = e || window.event;
    return(e.keyCode || e.which);
}
window.onload = function(){
    document.onkeypress = function(e){
        var key = code(e);
        // do something with key
    };
};

Or a more structured way of handling it:

(function(d){
    var modern = (d.addEventListener), event = function(obj, evt, fn){
        if(modern) {
            obj.addEventListener(evt, fn, false);
        } else {
            obj.attachEvent("on" + evt, fn);
        }
    }, code = function(e){
        e = e || window.event;
        return(e.keyCode || e.which);
    }, init = function(){
        event(d, "keypress", function(e){
            var key = code(e);
            // do stuff with key here
        });
    };
    if(modern) {
        d.addEventListener("DOMContentLoaded", init, false);
    } else {
        d.attachEvent("onreadystatechange", function(){
            if(d.readyState === "complete") {
                init();
            }
        });
    }
})(document);

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

Stop wasting your time, just add the following encoding="cp437" and errors='ignore' to your code in both read and write:

open('filename.csv', encoding="cp437", errors='ignore')
open(file_name, 'w', newline='', encoding="cp437", errors='ignore')

Godspeed

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

Most programs will check the $EDITOR environment variable, so you can set that to the path of TextEdit in your bashrc. Git will use this as well.

How to do this:

  • Add the following to your ~/.bashrc file:
    export EDITOR="/Applications/TextEdit.app/Contents/MacOS/TextEdit"
  • or just type the following command into your Terminal:
    echo "export EDITOR=\"/Applications/TextEdit.app/Contents/MacOS/TextEdit\"" >> ~/.bashrc

If you are using zsh, use ~/.zshrc instead of ~/.bashrc.

Elegant way to read file into byte[] array in Java

Use a ByteArrayOutputStream. Here is the process:

  • Get an InputStream to read data
  • Create a ByteArrayOutputStream.
  • Copy all the InputStream into the OutputStream
  • Get your byte[] from the ByteArrayOutputStream using the toByteArray() method

How to SUM and SUBTRACT using SQL?

Simple copy & paste example with subqueries, Note, that both queries should return 1 row:

select
(select sum(items_1) from items_table_1 where ...)
-
(select count(items_2) from items_table_1 where ...) 

as difference

Creating a blurring overlay view

Accepted answer is correct but there's an important step missing here, in case this view - for which you want blurred background - is presented using

[self presentViewController:vc animated:YES completion:nil]

By default, this will negate the blur as UIKit removes the presenter's view, which you are actually blurring. To avoid that removal, add this line before the previous one

vc.modalPresentationStyle = UIModalPresentationOverFullScreen;

Or use other Over styles.

Injecting @Autowired private field during testing

I'm a new user for Spring. I found a different solution for this. Using reflection and making public necessary fields and assign mock objects.

This is my auth controller and it has some Autowired private properties.

@RestController
public class AuthController {

    @Autowired
    private UsersDAOInterface usersDao;

    @Autowired
    private TokensDAOInterface tokensDao;

    @RequestMapping(path = "/auth/getToken", method = RequestMethod.POST)
    public @ResponseBody Object getToken(@RequestParam String username,
            @RequestParam String password) {
        User user = usersDao.getLoginUser(username, password);

        if (user == null)
            return new ErrorResult("Kullaniciadi veya sifre hatali");

        Token token = new Token();
        token.setTokenId("aergaerg");
        token.setUserId(1);
        token.setInsertDatetime(new Date());
        return token;
    }
}

And this is my Junit test for AuthController. I'm making public needed private properties and assign mock objects to them and rock :)

public class AuthControllerTest {

    @Test
    public void getToken() {
        try {
            UsersDAO mockUsersDao = mock(UsersDAO.class);
            TokensDAO mockTokensDao = mock(TokensDAO.class);

            User dummyUser = new User();
            dummyUser.setId(10);
            dummyUser.setUsername("nixarsoft");
            dummyUser.setTopId(0);

            when(mockUsersDao.getLoginUser(Matchers.anyString(), Matchers.anyString())) //
                    .thenReturn(dummyUser);

            AuthController ctrl = new AuthController();

            Field usersDaoField = ctrl.getClass().getDeclaredField("usersDao");
            usersDaoField.setAccessible(true);
            usersDaoField.set(ctrl, mockUsersDao);

            Field tokensDaoField = ctrl.getClass().getDeclaredField("tokensDao");
            tokensDaoField.setAccessible(true);
            tokensDaoField.set(ctrl, mockTokensDao);

            Token t = (Token) ctrl.getToken("test", "aergaeg");

            Assert.assertNotNull(t);

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

}

I don't know advantages and disadvantages for this way but this is working. This technic has a little bit more code but these codes can be seperated by different methods etc. There are more good answers for this question but I want to point to different solution. Sorry for my bad english. Have a good java to everybody :)

converting a javascript string to a html object

Had the same issue. I used a dirty trick like so:

var s = '<div id="myDiv"></div>';
var temp = document.createElement('div');
temp.innerHTML = s;
var htmlObject = temp.firstChild;

Now, you can add styles the way you like:

htmlObject.style.marginTop = something;

A KeyValuePair in Java

The Pair class from Commons Lang might help:

Pair<String, String> keyValue = new ImmutablePair("key", "value");

Of course, you would need to include commons-lang.

How to change button color with tkinter

When you do self.button = Button(...).grid(...), what gets assigned to self.button is the result of the grid() command, not a reference to the Button object created.

You need to assign your self.button variable before packing/griding it. It should look something like this:

self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)

AngularJs ReferenceError: angular is not defined

Always make sure that js file (angular.min.js) is referenced first in the HTML file. For example:

----------------- This reference will THROW error -------------------------

< script src="otherXYZ.js"></script>
< script src="angular.min.js"></script>

----------------- This reference will WORK as expected -------------------

< script src="angular.min.js"></script>
< script src="otherXYZ.js"></script>

pandas: multiple conditions while indexing data frame - unexpected behavior

A little mathematical logic theory here:

"NOT a AND NOT b" is the same as "NOT (a OR b)", so:

"a NOT -1 AND b NOT -1" is equivalent of "NOT (a is -1 OR b is -1)", which is opposite (Complement) of "(a is -1 OR b is -1)".

So if you want exact opposite result, df1 and df2 should be as below:

df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a == -1) | (df.b == -1)]

Path.Combine absolute with relative path strings

For windows universal apps Path.GetFullPath() is not available, you can use the System.Uri class instead:

 Uri uri = new Uri(Path.Combine(@"C:\blah\",@"..\bling"));
 Console.WriteLine(uri.LocalPath);

Get current scroll position of ScrollView in React Native

Try.

<ScrollView onScroll={this.handleScroll} />

And then:

handleScroll: function(event: Object) {
 console.log(event.nativeEvent.contentOffset.y);
},

Scala vs. Groovy vs. Clojure

I never had time to play with clojure. But for scala vs groovy, this is words from James Strachan - Groovy creator

"Though my tip though for the long term replacement of javac is Scala. I'm very impressed with it! I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy."

You can read the whole story here

Streaming video from Android camera to server

I have hosted an open-source project to enable Android phone to IP camera:

http://code.google.com/p/ipcamera-for-android

Raw video data is fetched from LocalSocket, and the MDAT MOOV of MP4 was checked first before streaming. The live video is packed in FLV format, and can be played via Flash video player with a build in web server :)

How do I start my app on startup?

For Android 10 there is background restrictions.

For android 10 and all version of android follow this steps to start an app after a restart or turn on mobile

Add this two permission in Android Manifest

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

Add this in your application tag

<receiver
        android:name=".BootReciever"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>

Add this class to start activity when boot up

public class BootReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    if (Objects.equals(intent.getAction(), Intent.ACTION_BOOT_COMPLETED)) {
        Intent i = new Intent(context, SplashActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
 }}

We need Draw overlay permission for android 10

so add this in your first activity

 private fun requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!Settings.canDrawOverlays(this)) {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + this.packageName)
            )
            startActivityForResult(intent, 232)
        } else {
            //Permission Granted-System will work
        }
    }
}

conflicting types error when compiling c program using gcc

To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.

A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.

Select columns from result set of stored procedure

To achieve this, first you create a #test_table like below:

create table #test_table(
    col1 int,
    col2 int,
   .
   .
   .
    col80 int
)

Now execute procedure and put value in #test_table:

insert into #test_table
EXEC MyStoredProc 'param1', 'param2'

Now you fetch the value from #test_table:

select col1,col2....,col80 from #test_table

Determining if an Object is of primitive type

I'm late to the show, but if you're testing a field, you can use getGenericType:

import static org.junit.Assert.*;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

import org.junit.Test;

public class PrimitiveVsObjectTest {

    private static final Collection<String> PRIMITIVE_TYPES = 
            new HashSet<>(Arrays.asList("byte", "short", "int", "long", "float", "double", "boolean", "char"));

    private static boolean isPrimitive(Type type) {
        return PRIMITIVE_TYPES.contains(type.getTypeName());
    }

    public int i1 = 34;
    public Integer i2 = 34;

    @Test
    public void primitive_type() throws NoSuchFieldException, SecurityException {
        Field i1Field = PrimitiveVsObjectTest.class.getField("i1");
        Type genericType1 = i1Field.getGenericType();
        assertEquals("int", genericType1.getTypeName());
        assertNotEquals("java.lang.Integer", genericType1.getTypeName());
        assertTrue(isPrimitive(genericType1));
    }

    @Test
    public void object_type() throws NoSuchFieldException, SecurityException {
        Field i2Field = PrimitiveVsObjectTest.class.getField("i2");
        Type genericType2 = i2Field.getGenericType();
        assertEquals("java.lang.Integer", genericType2.getTypeName());
        assertNotEquals("int", genericType2.getTypeName());
        assertFalse(isPrimitive(genericType2));
    }
}

The Oracle docs list the 8 primitive types.

How to create SPF record for multiple IPs?

Yes the second syntax is fine.

Have you tried using the SPF wizard? https://www.spfwizard.net/

It can quickly generate basic and complex SPF records.

Angular - Set headers for every request

You can use canActive in your routes, like so:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router) {}

  canActivate() {
    // If user is not logged in we'll send them to the homepage 
    if (!this.auth.loggedIn()) {
      this.router.navigate(['']);
      return false;
    }
    return true;
  }

}

const appRoutes: Routes = [
  {
    path: '', redirectTo: '/deals', pathMatch: 'full'
  },
  {
    path: 'special',
    component: PrivateDealsComponent,
    /* We'll use the canActivate API and pass in our AuthGuard.
       Now any time the /special route is hit, the AuthGuard will run
       first to make sure the user is logged in before activating and
       loading this route. */
    canActivate: [AuthGuard]
  }
];

Taken from: https://auth0.com/blog/angular-2-authentication

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

Converting string to byte array in C#

If you already have a byte array then you will need to know what type of encoding was used to make it into that byte array.

For example, if the byte array was created like this:

byte[] bytes = Encoding.ASCII.GetBytes(someString);

You will need to turn it back into a string like this:

string someString = Encoding.ASCII.GetString(bytes);

If you can find in the code you inherited, the encoding used to create the byte array then you should be set.

What is the difference between an annotated and unannotated tag?

Push annotated tags, keep lightweight local

man git-tag says:

Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels.

And certain behaviors do differentiate between them in ways that this recommendation is useful e.g.:

  • annotated tags can contain a message, creator, and date different than the commit they point to. So you could use them to describe a release without making a release commit.

    Lightweight tags don't have that extra information, and don't need it, since you are only going to use it yourself to develop.

  • git push --follow-tags will only push annotated tags
  • git describe without command line options only sees annotated tags

Internals differences

  • both lightweight and annotated tags are a file under .git/refs/tags that contains a SHA-1

  • for lightweight tags, the SHA-1 points directly to a commit:

    git tag light
    cat .git/refs/tags/light
    

    prints the same as the HEAD's SHA-1.

    So no wonder they cannot contain any other metadata.

  • annotated tags point to a tag object in the object database.

    git tag -as -m msg annot
    cat .git/refs/tags/annot
    

    contains the SHA of the annotated tag object:

    c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    and then we can get its content with:

    git cat-file -p c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    sample output:

    object 4284c41353e51a07e4ed4192ad2e9eaada9c059f
    type commit
    tag annot
    tagger Ciro Santilli <[email protected]> 1411478848 +0200
    
    msg
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.11 (GNU/Linux)
    
    <YOUR PGP SIGNATURE>
    -----END PGP SIGNAT
    

    And this is how it contains extra metadata. As we can see from the output, the metadata fields are:

    A more detailed analysis of the format is present at: What is the format of a git tag object and how to calculate its SHA?

Bonuses

  • Determine if a tag is annotated:

    git cat-file -t tag
    

    Outputs

    • commit for lightweight, since there is no tag object, it points directly to the commit
    • tag for annotated, since there is a tag object in that case
  • List only lightweight tags: How can I list all lightweight tags?

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

If none of the above works, try using this in web.config or app.config:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
        </dependentAssembly>
    </assemblyBinding>
</runtime>

how to git commit a whole folder?

I ran into the same problem. Placing a forward slash after the folder name worked for me.

ex: git add foldername/

How to sort a List<Object> alphabetically using Object name field

Using Java 8 Comparator.comparing:

list.sort(Comparator.comparing(Campaign::getName));

How do I add a simple jQuery script to WordPress?

After much searching, I finally found something that works with the latest WordPress. Here are the steps to follow:

  1. Find your theme's directory, create a folder in the directory for your custom js (custom_js in this example).
  2. Put your custom jQuery in a .js file in this directory (jquery_test.js in this example).
  3. Make sure your custom jQuery .js looks like this:

    (function($) {
    $(document).ready(function() {
    $('.your-class').addClass('do-my-bidding');
    })
    })(jQuery);
    
  4. Go to the theme's directory, open up functions.php

  5. Add some code near the top that looks like this:

    //this goes in functions.php near the top
    function my_scripts_method() {
    // register your script location, dependencies and version
       wp_register_script('custom_script',
       get_template_directory_uri() . '/custom_js/jquery_test.js',
       array('jquery'),
       '1.0' );
     // enqueue the script
      wp_enqueue_script('custom_script');
      }
    add_action('wp_enqueue_scripts', 'my_scripts_method');
    
  6. Check out your site to make sure it works!

SSRS chart does not show all labels on Horizontal axis

The problem here is that if there are too many data bars the labels will not show.

To fix this, under the "Chart Axis" properties set the Interval value to "=1". Then all the labels will be shown.

Encode/Decode URLs in C++

[Necromancer mode on]
Stumbled upon this question when was looking for fast, modern, platform independent and elegant solution. Didnt like any of above, cpp-netlib would be the winner but it has horrific memory vulnerability in "decoded" function. So I came up with boost's spirit qi/karma solution.

namespace bsq = boost::spirit::qi;
namespace bk = boost::spirit::karma;
bsq::int_parser<unsigned char, 16, 2, 2> hex_byte;
template <typename InputIterator>
struct unescaped_string
    : bsq::grammar<InputIterator, std::string(char const *)> {
  unescaped_string() : unescaped_string::base_type(unesc_str) {
    unesc_char.add("+", ' ');

    unesc_str = *(unesc_char | "%" >> hex_byte | bsq::char_);
  }

  bsq::rule<InputIterator, std::string(char const *)> unesc_str;
  bsq::symbols<char const, char const> unesc_char;
};

template <typename OutputIterator>
struct escaped_string : bk::grammar<OutputIterator, std::string(char const *)> {
  escaped_string() : escaped_string::base_type(esc_str) {

    esc_str = *(bk::char_("a-zA-Z0-9_.~-") | "%" << bk::right_align(2,0)[bk::hex]);
  }
  bk::rule<OutputIterator, std::string(char const *)> esc_str;
};

The usage of above as following:

std::string unescape(const std::string &input) {
  std::string retVal;
  retVal.reserve(input.size());
  typedef std::string::const_iterator iterator_type;

  char const *start = "";
  iterator_type beg = input.begin();
  iterator_type end = input.end();
  unescaped_string<iterator_type> p;

  if (!bsq::parse(beg, end, p(start), retVal))
    retVal = input;
  return retVal;
}

std::string escape(const std::string &input) {
  typedef std::back_insert_iterator<std::string> sink_type;
  std::string retVal;
  retVal.reserve(input.size() * 3);
  sink_type sink(retVal);
  char const *start = "";

  escaped_string<sink_type> g;
  if (!bk::generate(sink, g(start), input))
    retVal = input;
  return retVal;
}

[Necromancer mode off]

EDIT01: fixed the zero padding stuff - special thanks to Hartmut Kaiser
EDIT02: Live on CoLiRu

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

I had this in an MVC5 app in Windows 10 against IIS Express. My solution was the following:

  • Tools =>
    • Options =>
      • Projects and Solutions =>
        • Web Projects =>
          • Use the 64 bit version of IIS Express for web sites and projects

What is the best algorithm for overriding GetHashCode?

Microsoft lead for several way of hashing...

//for classes that contain a single int value
return this.value;

//for classes that contain multiple int value
return x ^ y;

//for classes that contain single number bigger than int    
return ((int)value ^ (int)(value >> 32)); 

//for classes that contain class instance fields which inherit from object
return obj1.GetHashCode();

//for classes that contain multiple class instance fields which inherit from object
return obj1.GetHashCode() ^ obj2.GetHashCode() ^ obj3.GetHashCode(); 

I can guess that for multiple big int you can use this:

int a=((int)value1 ^ (int)(value1 >> 32));
int b=((int)value2 ^ (int)(value2 >> 32));
int c=((int)value3 ^ (int)(value3 >> 32));
return a ^ b ^ c;

And same for multi-type: all converted first to int using GetHashCode() then the int values will be xor'ed and the result is your hash.

For those who use hash as ID (I mean an unique value), hash is naturally limited to a number of digits, I think it was 5 bytes for hashing algorithm, at least MD5.

You may turn multiple values to a hashed value and some of them be same, so don't use it as an identifier. (maybe some day I am going to use your component)

Submit form without page reloading

Fastest and easiest way is to use an iframe. Put a frame at the bottom of your page.

<iframe name="frame"></iframe>

And in your form do this.

<form target="frame">
</form>

and to make the frame invisible in your css.

iframe{
  display: none;
}

Angular - res.json() is not a function

You can remove the entire line below:

 .map((res: Response) => res.json());

No need to use the map method at all.

Issue with background color in JavaFX 8

Try this one in your css document,

-fx-background-color : #ffaadd;

or

-fx-base : #ffaadd; 

Also, you can set background color on your object with this code directly.

yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));

How to get http headers in flask?

just note, The different between the methods are, if the header is not exist

request.headers.get('your-header-name')

will return None or no exception, so you can use it like

if request.headers.get('your-header-name'):
    ....

but the following will throw an error

if request.headers['your-header-name'] # KeyError: 'your-header-name'
    ....

You can handle it by

if 'your-header-name' in request.headers:
   customHeader = request.headers['your-header-name']
   ....

How to check if a string contains only digits in Java

One more solution, that hasn't been posted, yet:

String regex = "\\p{Digit}+"; // uses POSIX character class

Displaying a webcam feed using OpenCV and Python

As in the opencv-doc you can get video feed from a camera which is connected to your computer by following code.

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

You can change cap = cv2.VideoCapture(0) index from 0 to 1 to access the 2nd camera.
Tested in opencv-3.2.0

convert date string to mysql datetime field

$time = strtotime($oldtime);

Then use date() to put it into the correct format.

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

How to set header and options in axios?

_x000D_
_x000D_
axios.post('url', {"body":data}, {
    headers: {
    'Content-Type': 'application/json'
    }
  }
)
_x000D_
_x000D_
_x000D_

How do I add a ToolTip to a control?

ToolTip in C# is very easy to add to almost all UI controls. You don't need to add any MouseHover event for this.

This is how to do it-

  1. Add a ToolTip object to your form. One object is enough for the entire form. ToolTip toolTip = new ToolTip();

  2. Add the control to the tooltip with the desired text.

    toolTip.SetToolTip(Button1,"Click here");

SyntaxError: expected expression, got '<'

This should work for you. If you are using SPA.

app.use('/', express.static(path.join(__dirname, 'your folder')));
// Send all other requests to the SPA
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'your folder/index.html'));
});

How do I change the default library path for R packages

See help(Startup) and help(.libPaths) as you have several possibilities where this may have gotten set. Among them are

  • setting R_LIBS_USER
  • assigning .libPaths() in .Rprofile or Rprofile.site

and more.

In this particular case you need to go backwards and unset whereever \\\\The library/path/I/don't/want is set.

To otherwise ignore it you need to override it use explicitly i.e. via

library("somePackage", lib.loc=.libPaths()[-1])

when loading a package.

Port 80 is being used by SYSTEM (PID 4), what is that?

I had the same problem and it was because of IIS running on the server, you can stop it using IIS Manager if it is the case for you.

jQuery event to trigger action when a div is made visible

Use jQuery Waypoints :

$('#contentDiv').waypoint(function() {
   alert('do something');
});

Other examples on the site of jQuery Waypoints.

UTF-8 problems while reading CSV file with fgetcsv

Now I got it working (after removing the header command). I think the problem was that the encoding of the php file was in ISO-8859-1. I set it to UTF-8 without BOM. I thought I already have done that, but perhaps I made an additional undo.

Furthermore, I used SET NAMES 'utf8' for the database. Now it is also correct in the database.

array.select() in javascript

There is Array.filter():

var numbers = [1, 2, 3, 4, 5];
var filtered = numbers.filter(function(x) { return x > 3; });

// As a JavaScript 1.8 expression closure
filtered = numbers.filter(function(x) x > 3);

Note that Array.filter() is not standard ECMAScript, and it does not appear in ECMAScript specs older than ES5 (thanks Yi Jiang and jAndy). As such, it may not be supported by other ECMAScript dialects like JScript (on MSIE).

Nov 2020 Update: Array.filter is now supported across all major browsers.

Android Animation Alpha

Try this

AlphaAnimation animation1 = new AlphaAnimation(0.2f, 1.0f);
animation1.setDuration(1000);
animation1.setStartOffset(5000);
animation1.setFillAfter(true);
iv.startAnimation(animation1);

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

Assuming you don't store things like the '+', '()', '-', spaces and what-have-yous (and why would you, they are presentational concerns which would vary based on local customs and the network distributions anyways), the ITU-T recommendation E.164 for the international telephone network (which most national networks are connected via) specifies that the entire number (including country code, but not including prefixes such as the international calling prefix necessary for dialling out, which varies from country to country, nor including suffixes, such as PBX extension numbers) be at most 15 characters.

Call prefixes depend on the caller, not the callee, and thus shouldn't (in many circumstances) be stored with a phone number. If the database stores data for a personal address book (in which case storing the international call prefix makes sense), the longest international prefixes you'd have to deal with (according to Wikipedia) are currently 5 digits, in Finland.

As for suffixes, some PBXs support up to 11 digit extensions (again, according to Wikipedia). Since PBX extension numbers are part of a different dialing plan (PBXs are separate from phone companies' exchanges), extension numbers need to be distinguishable from phone numbers, either with a separator character or by storing them in a different column.

How to get parameters from a URL string?

In Laravel, I'm use:

private function getValueFromString(string $string, string $key)
{
    parse_str(parse_url($string, PHP_URL_QUERY), $result);

    return isset($result[$key]) ? $result[$key] : null;
}

Python 'list indices must be integers, not tuple"

Why does the error mention tuples?

Others have explained that the problem was the missing ,, but the final mystery is why does the error message talk about tuples?

The reason is that your:

["pennies", '2.5', '50.0', '.01'] 
["nickles", '5.0', '40.0', '.05']

can be reduced to:

[][1, 2]

as mentioned by 6502 with the same error.

But then __getitem__, which deals with [] resolution, converts object[1, 2] to a tuple:

class C(object):
    def __getitem__(self, k):
        return k

# Single argument is passed directly.
assert C()[0] == 0

# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)

and the implementation of __getitem__ for the list built-in class cannot deal with tuple arguments like that.

More examples of __getitem__ action at: https://stackoverflow.com/a/33086813/895245

How to make Bootstrap Panel body with fixed height

You can use max-height in an inline style attribute, as below:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

To use scrolling with content that overflows a given max-height, you can alternatively try the following:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>

To restrict the height to a fixed value you can use something like this.

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

Specify the same value for both max-height and min-height (either in pixels or in points – as long as it’s consistent).

You can also put the same styles in css class in a stylesheet (or a style tag as shown below) and then include the same in your tag. See below:

Style Code:

.fixed-panel {
  min-height: 10;
  max-height: 10;
  overflow-y: scroll;
}

Apply Style :

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>

Hope this helps with your need.

Select values from XML field in SQL Server 2008

MSSQL uses regular XPath rules as follows:

  • nodename Selects all nodes with the name "nodename"
  • / Selects from the root node
  • // Selects nodes in the document from the current node that match the selection no matter where they are
  • . Selects the current node
  • .. Selects the parent of the current node
  • @ Selects attributes

W3Schools

How to test for $null array in PowerShell

It's an array, so you're looking for Count to test for contents.

I'd recommend

$foo.count -gt 0

The "why" of this is related to how PSH handles comparison of collection objects

How to fix warning from date() in PHP"

error_reporting(E_ALL ^ E_WARNING);

:)

You should change subject to "How to fix warning from date() in PHP"...

PPT to PNG with transparent background

I found a workaround.

  1. Export with a white background (or other color that will work with transparent graphics). This will be out "whitescreen" layer.
  2. Export with "bluescreen" background, or some terrible other color that will make it easy to select out the background from foreground.
  3. Open the bluescreen version as a layer on top of the white screen.
  4. Use the bluescreen layer to select out only the parts you want to use.
  5. Create a mask for the whitescreen layer with the selection made from the bluescreen layer.

This will get good results for edges and aliasing, whilst retaining a good color for the see-

Disable scrolling when touch moving certain element

To my surprise, the "preventDefault()" method is working for me on latest Google Chrome (version 85) on iOS 13.7. It also works on Safari on the same device and also working on my Android 8.0 tablet. I am currently implemented it for 2D view on my site here: https://papercraft-maker.com

Sample random rows in dataframe

The data.table package provides the function DT[sample(.N, M)], sampling M random rows from the data table DT.

library(data.table)
set.seed(10)

mtcars <- data.table(mtcars)
mtcars[sample(.N, 6)]

    mpg cyl  disp  hp drat    wt  qsec vs am gear carb
1: 14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
2: 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
3: 17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
4: 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
5: 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
6: 15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2

SELECT *, COUNT(*) in SQLite

If you want to count the number of records in your table, simply run:

    SELECT COUNT(*) FROM your_table;

Is it possible to overwrite a function in PHP

Edit

To address comments that this answer doesn't directly address the original question. If you got here from a Google Search, start here

There is a function available called override_function that actually fits the bill. However, given that this function is part of The Advanced PHP Debugger extension, it's hard to make an argument that override_function() is intended for production use. Therefore, I would say "No", it is not possible to overwrite a function with the intent that the original questioner had in mind.

Original Answer

This is where you should take advantage of OOP, specifically polymorphism.

interface Fooable
{
    public function ihatefooexamples();
}

class Foo implements Fooable
{
    public function ihatefooexamples()
    {
        return "boo-foo!";
    }
}

class FooBar implements Fooable
{
    public function ihatefooexamples()
    {
        return "really boo-foo";
    }
}

$foo = new Foo();

if (10 == $_GET['foolevel']) {
    $foo = new FooBar();
}

echo $foo->ihatefooexamples();

How much faster is C++ than C#?

For 'embarassingly parallel' problems, when using Intel TBB and OpenMP on C++ I have observed a roughly 10x performance increase compared to similar (pure math) problems done with C# and TPL. SIMD is one area where C# cannot compete, but I also got the impression that TPL has a sizeable overhead.

That said, I only use C++ for performance-critical tasks where I know I will be able to multithread and get results quickly. For everything else, C# (and occasionally F#) is just fine.

Capture iframe load complete event

Note that the onload event doesn't seem to fire if the iframe is loaded when offscreen. This frequently occurs when using "Open in New Window" /w tabs.

How to make div background color transparent in CSS

    /*Fully Opaque*/
    .class-name {
      opacity:1.0;
    }

    /*Translucent*/
    .class-name {
      opacity:0.5;
    }

    /*Transparent*/
    .class-name {
      opacity:0;
    }

    /*or you can use a transparent rgba value like this*/
    .class-name{
      background-color: rgba(255, 242, 0, 0.7);
      }

    /*Note - Opacity value can be anything between 0 to 1;
    Eg(0.1,0.8)etc */

Session timeout in ASP.NET

if you are want session timeout for website than remove

<authentication mode="Forms">
      <forms timeout="50"/>
</authentication>

tag from web.config file.

How do android screen coordinates work?

This picture will remove everyone's confusion hopefully which is collected from there.

Android screen coordinate

Excel Define a range based on a cell value

Here is an option. It works by using making an INDIRECT(ADDRESS(...)) from the ROW and COLUMN of the start cell, A1, down to the initial row + the number of rows held in B1.

SUM(INDIRECT(ADDRESS(ROW(A1),COLUMN(A1))):INDIRECT(ADDRESS(ROW(A1)+B1,COLUMN(A1))))

A1: is the start of data in a the "A" column

B1: is the number of rows to sum

Window vs Page vs UserControl for WPF navigation?

Most of all has posted correct answer. I would like to add few links, so that you can refer to them and have clear and better ideas about the same:

UserControl: http://msdn.microsoft.com/en-IN/library/a6h7e207(v=vs.71).aspx

The difference between page and window with respect to WPF: Page vs Window in WPF?

Custom HTTP headers : naming conventions

The header field name registry is defined in RFC3864, and there's nothing special with "X-".

As far as I can tell, there are no guidelines for private headers; in doubt, avoid them. Or have a look at the HTTP Extension Framework (RFC 2774).

It would be interesting to understand more of the use case; why can't the information be added to the message body?

Html.Textbox VS Html.TextboxFor

The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

PHP code to get selected text of a combo box

if you fetching it from database then

<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<?php $s2="select * from <tablename>"; 
$q2=mysql_query($s2); 
while($rw2=mysql_fetch_array($q2)) { 
?>
<option value="<?php echo $rw2['id']; ?>"><?php echo $rw2['carname']; ?></option><?php } ?>
</select>

What are the -Xms and -Xmx parameters when starting JVM?

The flag Xmx specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms specifies the initial memory allocation pool.

This means that your JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory. For example, starting a JVM like below will start it with 256 MB of memory and will allow the process to use up to 2048 MB of memory:

java -Xms256m -Xmx2048m

The memory flag can also be specified in different sizes, such as kilobytes, megabytes, and so on.

-Xmx1024k
-Xmx512m
-Xmx8g

The Xms flag has no default value, and Xmx typically has a default value of 256 MB. A common use for these flags is when you encounter a java.lang.OutOfMemoryError.

When using these settings, keep in mind that these settings are for the JVM's heap, and that the JVM can and will use more memory than just the size allocated to the heap. From Oracle's documentation:

Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.

Android Studio AVD - Emulator: Process finished with exit code 1

I had same issue for windows , the cause of the problem was currupted or missing dll files. I had to change them.

In android studio ,

Help Menu -> Show log in explorer.

It opens log folder, where you can find all logs . In my situation error like "Emulator terminated with exit code -1073741515"

  1. Try to run emulator from command prompt ,
  • Go to folder ~\Android\Sdk\emulator

  • Run this command:

    emulator.exe -netdelay none -netspeed full -avd <virtual device name> 
    
    ex: emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_26.avd
    

    You can find this command from folder ~.android\avd\xxx.avd\emu-launch-params.txt

  1. If you get error about vcruntime140 ,
  • Search and download the appropriate vcruntime140.dll file for your system from the internet (32 / 64 bit version) , and replace it with the vcruntime140.dll file in the folder ~\Android\Sdk\emulator

  • Try step 1

  • If you get error about vcruntime140_1 , change the file name as vcruntime140_1.dll ,try step 1

  1. If you get error about msvcp140.dll
  • Search and download the appropriate msvcp140.dll file for your system from the internet (32 / 64 bit version)
  • Replace the file in the folder C:\Windows\System32 with file msvcp140.dll
  • Try step 1

If it runs , you can run it from Android Studio also.

Remove Android App Title Bar

Use this to remove title from android app in your Androidmainfest.xml

android:theme="@android:style/Theme.NoTitleBar"

or you can use this in your activity

requestWindowFeature(Window.FEATURE_NO_TITLE); 
setContentView(R.layout.activity_main);

index.php not loading by default

This post might be old but i am just posting it incase it helps some other person, I would not advise to Create a .htaccess file in your web root and change the index. I feel it is better to follow the steps

  1. Go to the conf folder of your apache folder mine is

    C:\Apache24\conf

  2. Open the file named

    httpd.conf

  3. Go to the section

    <IfModule dir_module>
       DirectoryIndex index.html 
    
     </IfModule>
    
  4. Add index.php to it as shown below

     <IfModule dir_module>
      DirectoryIndex index.html index.php
    
    </IfModule>
    

This way, it still picks index.html and index.php as the default index but giving priority to index.html because index.html came before *index.php. By this I mean in you have both index.html and index.php in the same directory, the index.html will be used as the default index except you write **index.php* before index.hml

I hope it helps someone... Happy Coding

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

How can I display the users profile pic using the facebook graph api?

Here is the code that worked for me!

Assuming that you have a valid session going,

//Get the current users id
$uid = $facebook->getUser();

//create the url
$profile_pic =  "http://graph.facebook.com/".$uid."/picture";

//echo the image out
echo "<img src=\"" . $profile_pic . "\" />";

Thanx goes to Raine, you da man!

Way to get all alphabetic chars in an array in PHP?

To contribute, yesterday, PEZ's answer in this post, https://stackoverflow.com/a/431930/9710921 helped me to create an array to manage Excel columns for data exportations, like that:

public static function makeAlphas() : array {
    $alphas = $cells = range('A', 'Z');
    foreach($alphas as $alpha) {
        foreach($alphas as $beta) {
            $cells[] = $alpha.$beta;
        }
    }
    return $cells;
}

// Output
// array:702 ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ", "DK", "DL", "DM", "DN", "DO", "DP", "DQ", "DR", "DS", "DT", "DU", "DV", "DW", "DX", "DY", "DZ", "EA", "EB", "EC", "ED", "EE", "EF", "EG", "EH", "EI", "EJ", "EK", "EL", "EM", "EN", "EO", "EP", "EQ", "ER", "ES", "ET", "EU", "EV", "EW", "EX", "EY", "EZ", "FA", "FB", "FC", "FD", "FE", "FF", "FG", "FH", "FI", "FJ", "FK", "FL", "FM", "FN", "FO", "FP", "FQ", "FR", "FS", "FT", "FU", "FV", "FW", "FX", "FY", "FZ", "GA", "GB", "GC", "GD", "GE", "GF", "GG", "GH", "GI", "GJ", "GK", "GL", "GM", "GN", "GO", "GP", "GQ", "GR", "GS", "GT", "GU", "GV", "GW", "GX", "GY", "GZ", "HA", "HB", "HC", "HD", "HE", "HF", "HG", "HH", "HI", "HJ", "HK", "HL", "HM", "HN", "HO", "HP", "HQ", "HR", "HS", "HT", "HU", "HV", "HW", "HX", "HY", "HZ", "IA", "IB", "IC", "ID", "IE", "IF", "IG", "IH", "II", "IJ", "IK", "IL", "IM", "IN", "IO", "IP", "IQ", "IR", "IS", "IT", "IU", "IV", "IW", "IX", "IY", "IZ", "JA", "JB", "JC", "JD", "JE", "JF", "JG", "JH", "JI", "JJ", "JK", "JL", "JM", "JN", "JO", "JP", "JQ", "JR", "JS", "JT", "JU", "JV", "JW", "JX", "JY", "JZ", "KA", "KB", "KC", "KD", "KE", "KF", "KG", "KH", "KI", "KJ", "KK", "KL", "KM", "KN", "KO", "KP", "KQ", "KR", "KS", "KT", "KU", "KV", "KW", "KX", "KY", "KZ", "LA", "LB", "LC", "LD", "LE", "LF", "LG", "LH", "LI", "LJ", "LK", "LL", "LM", "LN", "LO", "LP", "LQ", "LR", "LS", "LT", "LU", "LV", "LW", "LX", "LY", "LZ", "MA", "MB", "MC", "MD", "ME", "MF", "MG", "MH", "MI", "MJ", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NB", "NC", "ND", "NE", "NF", "NG", "NH", "NI", "NJ", "NK", "NL", "NM", "NN", "NO", "NP", "NQ", "NR", "NS", "NT", "NU", "NV", "NW", "NX", "NY", "NZ", "OA", "OB", "OC", "OD", "OE", "OF", "OG", "OH", "OI", "OJ", "OK", "OL", "OM", "ON", "OO", "OP", "OQ", "OR", "OS", "OT", "OU", "OV", "OW", "OX", "OY", "OZ", "PA", "PB", "PC", "PD", "PE", "PF", "PG", "PH", "PI", "PJ", "PK", "PL", "PM", "PN", "PO", "PP", "PQ", "PR", "PS", "PT", "PU", "PV", "PW", "PX", "PY", "PZ", "QA", "QB", "QC", "QD", "QE", "QF", "QG", "QH", "QI", "QJ", "QK", "QL", "QM", "QN", "QO", "QP", "QQ", "QR", "QS", "QT", "QU", "QV", "QW", "QX", "QY", "QZ", "RA", "RB", "RC", "RD", "RE", "RF", "RG", "RH", "RI", "RJ", "RK", "RL", "RM", "RN", "RO", "RP", "RQ", "RR", "RS", "RT", "RU", "RV", "RW", "RX", "RY", "RZ", "SA", "SB", "SC", "SD", "SE", "SF", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SP", "SQ", "SR", "SS", "ST", "SU", "SV", "SW", "SX", "SY", "SZ", "TA", "TB", "TC", "TD", "TE", "TF", "TG", "TH", "TI", "TJ", "TK", "TL", "TM", "TN", "TO", "TP", "TQ", "TR", "TS", "TT", "TU", "TV", "TW", "TX", "TY", "TZ", "UA", "UB", "UC", "UD", "UE", "UF", "UG", "UH", "UI", "UJ", "UK", "UL", "UM", "UN", "UO", "UP", "UQ", "UR", "US", "UT", "UU", "UV", "UW", "UX", "UY", "UZ", "VA", "VB", "VC", "VD", "VE", "VF", "VG", "VH", "VI", "VJ", "VK", "VL", "VM", "VN", "VO", "VP", "VQ", "VR", "VS", "VT", "VU", "VV", "VW", "VX", "VY", "VZ", "WA", "WB", "WC", "WD", "WE", "WF", "WG", "WH", "WI", "WJ", "WK", "WL", "WM", "WN", "WO", "WP", "WQ", "WR", "WS", "WT", "WU", "WV", "WW", "WX", "WY", "WZ", "XA", "XB", "XC", "XD", "XE", "XF", "XG", "XH", "XI", "XJ", "XK", "XL", "XM", "XN", "XO", "XP", "XQ", "XR", "XS", "XT", "XU", "XV", "XW", "XX", "XY", "XZ", "YA", "YB", "YC", "YD", "YE", "YF", "YG", "YH", "YI", "YJ", "YK", "YL", "YM", "YN", "YO", "YP", "YQ", "YR", "YS", "YT", "YU", "YV", "YW", "YX", "YY", "YZ", "ZA", "ZB", "ZC", "ZD", "ZE", "ZF", "ZG", "ZH", "ZI", "ZJ", "ZK", "ZL", "ZM", "ZN", "ZO", "ZP", "ZQ", "ZR", "ZS", "ZT", "ZU", "ZV", "ZW", "ZX", "ZY", "ZZ",];

Thanks PEZ!

MySQL: Convert INT to DATETIME

The function STR_TO_DATE(COLUMN, '%input_format') can do it, you only have to specify the input format. Example : to convert p052011

SELECT STR_TO_DATE('p052011','p%m%Y') FROM your_table;

The result : 2011-05-00

Normal arguments vs. keyword arguments

There are two related concepts, both called "keyword arguments".

On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.

The other concept is on the function definition side: you can define a function that takes parameters by name -- and you don't even have to specify what those names are. These are pure keyword arguments, and can't be passed positionally. The syntax is

def my_function(arg1, arg2, **kwargs)

Any keyword arguments you pass into this function will be placed into a dictionary named kwargs. You can examine the keys of this dictionary at run-time, like this:

def my_function(**kwargs):
    print str(kwargs)

my_function(a=12, b="abc")

{'a': 12, 'b': 'abc'}

How to use the DropDownList's SelectedIndexChanged event

The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..

    <asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
        AutoPostBack="True" AppendDataBoundItems="true">
    <asp:DropDownList ID="DropDownList2" runat="server"
        onselectedindexchanged="DropDownList2_SelectedIndexChanged">
    </asp:DropDownList> 


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList2

}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList3
}

Best way to convert strings to symbols in hash

If you are using json, and want to use it as a hash, in core Ruby you can do it:

json_obj = JSON.parse(json_str, symbolize_names: true)

symbolize_names: If set to true, returns symbols for the names (keys) in a JSON object. Otherwise strings are returned. Strings are the default.

Doc: Json#parse symbolize_names

JavaScript: how to change form action attribute value based on selection?

Is required that you have a form?
If not, then you could use this:

<div>
    <input type="hidden" value="ServletParameter" />
    <input type="button" id="callJavaScriptServlet" onclick="callJavaScriptServlet()" />
</div>

with the following JavaScript:

function callJavaScriptServlet() {
    this.form.action = "MyServlet";
    this.form.submit();
}

Constructor in an Interface?

This is because interfaces do not allow to define the method body in it.but we should have to define the constructor in the same class as interfaces have by default abstract modifier for all the methods to define. That's why we can not define constructor in the interfaces.

Disable HttpClient logging

For log4j, add the following to log4j.properties (in the application's source directory):

log4j.logger.org.apache=WARN
log4j.logger.httpclient=WARN

For logback, the following logback.xml will kill the noise:

<configuration>
    <logger name="org.apache" level="WARN" />
    <logger name="httpclient" level="WARN" /> 
</configuration>

How can I create a product key for my C# application?

Another good inexpensive tool for product keys and activations is a product called InstallKey. Take a look at www.lomacons.com

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

PySpark: multiple conditions in when clause

It should be:

$when(((tdata.Age == "" ) & (tdata.Survived == "0")), mean_age_0)

Simpler way to check if variable is not equal to multiple string values?

You need to multi value check. Try using the following code :

<?php
    $illstack=array(...............);
    $val=array('uk','bn','in');
    if(count(array_intersect($illstack,$val))===count($val)){ // all of $val is in $illstack}
?>

How can I use NSError in my iPhone App?

Well, what I usually do is have my methods that could error-out at runtime take a reference to a NSError pointer. If something does indeed go wrong in that method, I can populate the NSError reference with error data and return nil from the method.

Example:

- (id) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
    // begin feeding the world's children...
    // it's all going well until....
    if (ohNoImOutOfMonies) {
        // sad, we can't solve world hunger, but we can let people know what went wrong!
        // init dictionary to be used to populate error object
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
        // populate the error object with the details
        *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
        // we couldn't feed the world's children...return nil..sniffle...sniffle
        return nil;
    }
    // wohoo! We fed the world's children. The world is now in lots of debt. But who cares? 
    return YES;
}

We can then use the method like this. Don't even bother to inspect the error object unless the method returns nil:

// initialize NSError object
NSError* error = nil;
// try to feed the world
id yayOrNay = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!yayOrNay) {
   // inspect error
   NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.

We were able to access the error's localizedDescription because we set a value for NSLocalizedDescriptionKey.

The best place for more information is Apple's documentation. It really is good.

There is also a nice, simple tutorial on Cocoa Is My Girlfriend.

SSL Connection / Connection Reset with IISExpress

If you need to use a port outside of the 44300-44399 range, here's a workaround:

  • Create a new site in IIS (not Express)
  • Bind HTTPS to the port you need
  • For SSL Certificate, choose IIS Express Development Certificate
  • Once the site is created, stop it, since it doesn't actually need to be running

This registers the IIS Express Development certificate with that port and is the easiest way I've found to get around the 44300-44399 range requirement.

Connect Bluestacks to Android Studio

Steps to connect Blue Stack with Android Studio

  1. Close Android Studio.
  2. Go to adb.exe location (default location: %LocalAppData%\Android\sdk\platform-tools)
  3. Run adb connect localhost:5555 from this location.
  4. Start Android Studio and you will get Blue Stack as emulator when you run your app.

Global keyboard capture in C# application

As requested by dube I'm posting my modified version of Siarhei Kuchuk's answer.
If you want to check my changes search for // EDT. I've commented most of it.

The Setup

class GlobalKeyboardHookEventArgs : HandledEventArgs
{
    public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
    public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }

    public GlobalKeyboardHookEventArgs(
        GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
        GlobalKeyboardHook.KeyboardState keyboardState)
    {
        KeyboardData = keyboardData;
        KeyboardState = keyboardState;
    }
}

//Based on https://gist.github.com/Stasonix
class GlobalKeyboardHook : IDisposable
{
    public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;

    // EDT: Added an optional parameter (registeredKeys) that accepts keys to restict
    // the logging mechanism.
    /// <summary>
    /// 
    /// </summary>
    /// <param name="registeredKeys">Keys that should trigger logging. Pass null for full logging.</param>
    public GlobalKeyboardHook(Keys[] registeredKeys = null)
    {
        RegisteredKeys = registeredKeys;
        _windowsHookHandle = IntPtr.Zero;
        _user32LibraryHandle = IntPtr.Zero;
        _hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

        _user32LibraryHandle = LoadLibrary("User32");
        if (_user32LibraryHandle == IntPtr.Zero)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
        }



        _windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
        if (_windowsHookHandle == IntPtr.Zero)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // because we can unhook only in the same thread, not in garbage collector thread
            if (_windowsHookHandle != IntPtr.Zero)
            {
                if (!UnhookWindowsHookEx(_windowsHookHandle))
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                }
                _windowsHookHandle = IntPtr.Zero;

                // ReSharper disable once DelegateSubtraction
                _hookProc -= LowLevelKeyboardProc;
            }
        }

        if (_user32LibraryHandle != IntPtr.Zero)
        {
            if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }
            _user32LibraryHandle = IntPtr.Zero;
        }
    }

    ~GlobalKeyboardHook()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private IntPtr _windowsHookHandle;
    private IntPtr _user32LibraryHandle;
    private HookProc _hookProc;

    delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll")]
    private static extern IntPtr LoadLibrary(string lpFileName);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    private static extern bool FreeLibrary(IntPtr hModule);

    /// <summary>
    /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
    /// You would install a hook procedure to monitor the system for certain types of events. These events are
    /// associated either with a specific thread or with all threads in the same desktop as the calling thread.
    /// </summary>
    /// <param name="idHook">hook type</param>
    /// <param name="lpfn">hook procedure</param>
    /// <param name="hMod">handle to application instance</param>
    /// <param name="dwThreadId">thread identifier</param>
    /// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
    [DllImport("USER32", SetLastError = true)]
    static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);

    /// <summary>
    /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
    /// </summary>
    /// <param name="hhk">handle to hook procedure</param>
    /// <returns>If the function succeeds, the return value is true.</returns>
    [DllImport("USER32", SetLastError = true)]
    public static extern bool UnhookWindowsHookEx(IntPtr hHook);

    /// <summary>
    /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
    /// A hook procedure can call this function either before or after processing the hook information.
    /// </summary>
    /// <param name="hHook">handle to current hook</param>
    /// <param name="code">hook code passed to hook procedure</param>
    /// <param name="wParam">value passed to hook procedure</param>
    /// <param name="lParam">value passed to hook procedure</param>
    /// <returns>If the function succeeds, the return value is true.</returns>
    [DllImport("USER32", SetLastError = true)]
    static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);

    [StructLayout(LayoutKind.Sequential)]
    public struct LowLevelKeyboardInputEvent
    {
        /// <summary>
        /// A virtual-key code. The code must be a value in the range 1 to 254.
        /// </summary>
        public int VirtualCode;

        // EDT: added a conversion from VirtualCode to Keys.
        /// <summary>
        /// The VirtualCode converted to typeof(Keys) for higher usability.
        /// </summary>
        public Keys Key { get { return (Keys)VirtualCode; } }

        /// <summary>
        /// A hardware scan code for the key. 
        /// </summary>
        public int HardwareScanCode;

        /// <summary>
        /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
        /// </summary>
        public int Flags;

        /// <summary>
        /// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
        /// </summary>
        public int TimeStamp;

        /// <summary>
        /// Additional information associated with the message. 
        /// </summary>
        public IntPtr AdditionalInformation;
    }

    public const int WH_KEYBOARD_LL = 13;
    //const int HC_ACTION = 0;

    public enum KeyboardState
    {
        KeyDown = 0x0100,
        KeyUp = 0x0101,
        SysKeyDown = 0x0104,
        SysKeyUp = 0x0105
    }

    // EDT: Replaced VkSnapshot(int) with RegisteredKeys(Keys[])
    public static Keys[] RegisteredKeys;
    const int KfAltdown = 0x2000;
    public const int LlkhfAltdown = (KfAltdown >> 8);

    public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        bool fEatKeyStroke = false;

        var wparamTyped = wParam.ToInt32();
        if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
        {
            object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
            LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;

            var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);

            // EDT: Removed the comparison-logic from the usage-area so the user does not need to mess around with it.
            // Either the incoming key has to be part of RegisteredKeys (see constructor on top) or RegisterdKeys
            // has to be null for the event to get fired.
            var key = (Keys)p.VirtualCode;
            if (RegisteredKeys == null || RegisteredKeys.Contains(key))
            {
                EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
                handler?.Invoke(this, eventArguments);

                fEatKeyStroke = eventArguments.Handled;
            }
        }

        return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
    }
}

The Usage differences can be seen here

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private GlobalKeyboardHook _globalKeyboardHook;

    private void buttonHook_Click(object sender, EventArgs e)
    {
        // Hooks only into specified Keys (here "A" and "B").
        _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

        // Hooks into all keys.
        _globalKeyboardHook = new GlobalKeyboardHook();
        _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
    }

    private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
    {
        // EDT: No need to filter for VkSnapshot anymore. This now gets handled
        // through the constructor of GlobalKeyboardHook(...).
        if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
        {
            // Now you can access both, the key and virtual code
            Keys loggedKey = e.KeyboardData.Key;
            int loggedVkCode = e.KeyboardData.VirtualCode;
        }
    }
}

Thanks to Siarhei Kuchuk for his post. Even tho I've simplified the usage this initial code was very useful for me.

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

ArrayAdapter in android to create simple listview

The TextView resource id it needs is for a TextView layout file, so it won't be in the same activity.

You can create it by going to File > New > XML > XML Layout File, and enter the widget type, which is 'TextView' in the root tag field.

Source: https://www.kompulsa.com/the-simplest-way-to-implement-an-android-listview/

Can I simultaneously declare and assign a variable in VBA?

There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the : continuation character if you want it on one line for readability;

Dim clientToTest As String:  clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)

Hint (summary of other answers/comments): Works with objects too (Excel 2010):

Dim ws  As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"

Loading .sql files from within PHP

The simplest solution is to use shell_exec() to run the mysql client with the SQL script as input. This might run a little slower because it has to fork, but you can write the code in a couple of minutes and then get back to working on something useful. Writing a PHP script to run any SQL script could take you weeks.

Supporting SQL scripts is more complex than what people are describing here, unless you're certain that your script contains only a subset of the functionality of scripts. Below are some examples of things that may appear in an ordinary SQL script that make it complex to code a script to interpret it line by line.

-- Comment lines cannot be prepared as statements
-- This is a MySQL client tool builtin command.  
-- It cannot be prepared or executed by server.
USE testdb;

-- This is a multi-line statement.
CREATE TABLE foo (
  string VARCHAR(100)
);

-- This statement is not supported as a prepared statement.
LOAD DATA INFILE 'datafile.txt' INTO TABLE foo;

-- This statement is not terminated with a semicolon.
DELIMITER //

-- This multi-line statement contains a semicolon 
-- but not as the statement terminator.
CREATE PROCEDURE simpleproc (OUT param1 INT)
BEGIN
  SELECT COUNT(*) INTO param1 FROM foo;
END
// 

If you only support a subset of SQL scripts, excluding some corner cases such as those above, it's relatively easy to write a PHP script that reads a file and executes the SQL statements within the file. But if you want to support any valid SQL script, that's much more complex.


See also my answers to these related questions:

Can we have multiple <tbody> in same <table>?

Yes. From the DTD

<!ELEMENT table
     (caption?, (col*|colgroup*), thead?, tfoot?, (tbody+|tr+))>

So it expects one or more. It then goes on to say

Use multiple tbody sections when rules are needed between groups of table rows.

How to change maven logging level to display only warning and errors?

Answering your question

I made a small investigation because I am also interested in the solution.

Maven command line verbosity options

According to http://books.sonatype.com/mvnref-book/reference/running-sect-options.html#running-sect-verbose-option

  • -e for error
  • -X for debug
  • -q for only error

Maven logging config file

Currently maven 3.1.x uses SLF4J to log to the System.out . You can modify the logging settings at the file:

${MAVEN_HOME}/conf/logging/simplelogger.properties

According to the page : http://maven.apache.org/maven-logging.html

Command line setup

I think you should be able to setup the default Log level of the simple logger via a command line parameter, like this:

$ mvn clean package -Dorg.slf4j.simpleLogger.defaultLogLevel=debug

But I could not get it to work. I guess the only problem with this is, maven picks up the default level from the config file on the classpath. I also tried a couple of other settings via System.properties, but all of them were unsuccessful.

Appendix

You can find the source of slf4j on github here : slf4j github

The source of the simplelogger here : slf4j/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SimpleLog.java

The plexus loader loads the simplelogger.properties.

How do I compare two strings in Perl?

  • cmp Compare

    'a' cmp 'b' # -1
    'b' cmp 'a' #  1
    'a' cmp 'a' #  0
    
  • eq Equal to

    'a' eq  'b' #  0
    'b' eq  'a' #  0
    'a' eq  'a' #  1
    
  • ne Not-Equal to

    'a' ne  'b' #  1
    'b' ne  'a' #  1
    'a' ne  'a' #  0
    
  • lt Less than

    'a' lt  'b' #  1
    'b' lt  'a' #  0
    'a' lt  'a' #  0
    
  • le Less than or equal to

    'a' le  'b' #  1
    'b' le  'a' #  0
    'a' le  'a' #  1
    
  • gt Greater than

    'a' gt  'b' #  0
    'b' gt  'a' #  1
    'a' gt  'a' #  0
    
  • ge Greater than or equal to

    'a' ge  'b' #  0
    'b' ge  'a' #  1
    'a' ge  'a' #  1
    

See perldoc perlop for more information.

( I'm simplifying this a little bit as all but cmp return a value that is both an empty string, and a numerically zero value instead of 0, and a value that is both the string '1' and the numeric value 1. These are the same values you will always get from boolean operators in Perl. You should really only be using the return values for boolean or numeric operations, in which case the difference doesn't really matter. )

How to calculate growth with a positive and negative number?

Use this code:

=IFERROR((This Year/Last Year)-1,IF(AND(D2=0,E2=0),0,1))

The first part of this code iferror gets rid of the N/A issues when there is a negative or a 0 value. It does this by looking at the values in e2 and d2 and makes sure they are not both 0. If they are both 0 then it will place a 0%. If only one of the cells are a 0 then it will place 100% or -100% depending on where the 0 value falls. The second part of this code (e2/d2)-1 is the same code as (this year - lastyear)/Last year

Please click here for example picture

how to change the default positioning of modal in bootstrap?

I know it's a bit late but I had issues with a modal window not allowing some links on the menu bar to work, even when it has not been triggered. But I solved it by doing the following:

.modal{
display:none;
}

Can I change the color of Font Awesome's icon color?

This worked for me:

.icon-cog {
  color: black;
}

For versions of Font Awesome above 4.7.0, it looks this:

.fa-cog {
  color: black;
}

What are best practices for REST nested resources?

I've tried both design strategies - nested and non-nested endpoints. I've found that:

  1. if the nested resource has a primary key and you don't have its parent primary key, the nested structure requires you to get it, even though the system doesn't actually require it.

  2. nested endpoints typically require redundant endpoints. In other words, you will more often than not, need the additional /employees endpoint so you can get a list of employees across departments. If you have /employees, what exactly does /companies/departments/employees buy you?

  3. nesting endpoints don't evolve as nicely. E.g. you might not need to search for employees now but you might later and if you have a nested structure, you have no choice but to add another endpoint. With a non-nested design, you just add more parameters, which is simpler.

  4. sometimes a resource could have multiple types of parents. Resulting in multiple endpoints all returning the same resource.

  5. redundant endpoints makes the docs harder to write and also makes the api harder to learn.

In short, the non-nested design seems to allow a more flexible and simpler endpoint schema.

Get first key in a (possibly) associative array?

 $arr = array('key1'=>'value1','key2'=>'value2','key3'=>'key3');
 list($first_key) = each($arr);
 print $first_key;
 // key1

Checking something isEmpty in Javascript?

This is a bigger question than you think. Variables can empty in a lot of ways. Kinda depends on what you need to know.

// quick and dirty will be true for '', null, undefined, 0, NaN and false.
if (!x) 

// test for null OR undefined
if (x == null)  

// test for undefined OR null 
if (x == undefined) 

// test for undefined
if (x === undefined) 
// or safer test for undefined since the variable undefined can be set causing tests against it to fail.
if (typeof x == 'undefined') 

// test for empty string
if (x === '') 

// if you know its an array
if (x.length == 0)  
// or
if (!x.length)

// BONUS test for empty object
var empty = true, fld;
for (fld in x) {
  empty = false;
  break;
}

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Only using Session.Clear() when a user logs out can pose a security hole. As the session is still valid as far as the Web Server is concerned. It is then a reasonably trivial matter to sniff, and grab the session Id, and hijack that session.

For this reason, when logging a user out it would be safer and more sensible to use Session.Abandon() so that the session is destroyed, and a new session created (even though the logout UI page would be part of the new session, the new session would not have any of the users details in it and hijacking the new session would be equivalent to having a fresh session, hence it would be mute).

Removing elements from array Ruby

[1,3].inject([1,1,1,2,2,3]) do |memo,element|
  memo.tap do |memo|
    i = memo.find_index(e)
    memo.delete_at(i) if i
  end
end

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

How to return an array from a function?

Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.

So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:

int *gnabber(){
  static int foo[] = {1,2,3}
  return foo;
}

file_put_contents(meta/services.json): failed to open stream: Permission denied

Suggestion from vsmoraes worked for me:

Laravel >= 5.4

php artisan cache:clear 
chmod -R 775 storage/
composer dump-autoload

Laravel < 5.4

php artisan cache:clear 
chmod -R 775 app/storage 
composer dump-autoload

NOTE: DO NOT DO THIS ON ANY REMOTE SERVER (DEV OR PRODUCTION)

When I asked this question, this was a problem on my localhost, running in a Virtual Machine. So I thought setting up a 777 was safe enough, however, folks are right when they say you should look for a different solution. Try 775 first

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

For window if you download scr folder say apache-jmeter-5.3_src then you won't find ApacheJMeter.jar file insider bin folder.One might have downloaded zip file under source section. Form this link download zip file under binaries section and click on ApacheJMeter.jar from bin folder https://jmeter.apache.org/download_jmeter.cgi

Change background color of edittext in android

Here the best way

First : make new xml file in res/drawable name it rounded_edit_text then paste this:

<?xml version="1.0" encoding="utf-8"?>
<shape  xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#F9966B" />
    <corners
        android:bottomRightRadius="15dp"
        android:bottomLeftRadius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp" />
</shape>

Second: in res/layout copy and past following code (code of EditText)

<EditText
    android:id="@+id/txtdoctor"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/rounded_edit_text"
    android:ems="10" >
    <requestFocus />
</EditText>

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

.htaccess file to allow access to images folder to view pictures?

<Directory /uploads>
   Options +Indexes
</Directory>

How can I decrypt MySQL passwords

If a proper encryption method was used, it's not going to be possible to easily retrieve them.

Just reset them with new passwords.

Edit: The string looks like it is using PASSWORD():

UPDATE user SET password = PASSWORD("newpassword");

Connection Java-MySql : Public Key Retrieval is not allowed

Alternatively to the suggested answers you could try and use mysql_native_password authentication plugin instead of caching_sha2_password authentication plugin.

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_password_here'; 

How do I check that a number is float or integer?

Here's what I use for integers:

Math.ceil(parseFloat(val)) === val

Short, nice :) Works all the time. This is what David Flanagan suggests if I'm not mistaken.

Executable directory where application is running from?

You can write the following:

Path.Combine(Path.GetParentDirectory(GetType(MyClass).Assembly.Location), "Images\image.jpg")

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".

Could not load file or assembly for Oracle.DataAccess in .NET

Try the following: In Visual Studio, go to Tools/Options....Projects and Solutions...Web Projects... Make sure that 64 bit version of IIS Express checkbox is checked off.

How to correctly use the ASP.NET FileUpload control

My solution in code behind was:

System.Web.UI.WebControls.FileUpload fileUpload;

I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.

VirtualBox and vmdk vmx files

Actually, for the configuration of the machine, just open the .vmx file with a text editor (e.g. notepad, gedit, etc.). You will be able to see the OS type, memsize, ethernet.connectionType, and other settings. Then when you make your machine, just look in the text editor for the corresponding settings. When it asks for the disk, select the .vmdk disk as mentioned above.

How to import Maven dependency in Android Studio/IntelliJ?

Android Studio 3

The answers that talk about Maven Central are dated since Android Studio uses JCenter as the default repository center now. Your project's build.gradle file should have something like this:

repositories {
    google()
    jcenter()
}

So as long as the developer has their Maven repository there (which Picasso does), then all you would have to do is add a single line to the dependencies section of your app's build.gradle file.

dependencies {
    // ...
    implementation 'com.squareup.picasso:picasso:2.5.2'
}

Deny direct access to all .php files except index.php

An easy solution is to rename all non-index.php files to .inc, then deny access to *.inc files. I use this in a lot of my projects and it works perfectly fine.

How do I validate a date in this format (yyyy-mm-dd) using jquery?

I expanded just slightly on the isValidDate function Thorbin posted above (using a regex). We use a regex to check the format (to prevent us from getting another format which would be valid for Date). After this loose check we then actually run it through the Date constructor and return true or false if it is valid within this format. If it is not a valid date we will get false from this function.

_x000D_
_x000D_
function isValidDate(dateString) {_x000D_
  var regEx = /^\d{4}-\d{2}-\d{2}$/;_x000D_
  if(!dateString.match(regEx)) return false;  // Invalid format_x000D_
  var d = new Date(dateString);_x000D_
  var dNum = d.getTime();_x000D_
  if(!dNum && dNum !== 0) return false; // NaN value, Invalid date_x000D_
  return d.toISOString().slice(0,10) === dateString;_x000D_
}_x000D_
_x000D_
_x000D_
/* Example Uses */_x000D_
console.log(isValidDate("0000-00-00"));  // false_x000D_
console.log(isValidDate("2015-01-40"));  // false_x000D_
console.log(isValidDate("2016-11-25"));  // true_x000D_
console.log(isValidDate("1970-01-01"));  // true = epoch_x000D_
console.log(isValidDate("2016-02-29"));  // true = leap day_x000D_
console.log(isValidDate("2013-02-29"));  // false = not leap day
_x000D_
_x000D_
_x000D_

What is <=> (the 'Spaceship' Operator) in PHP 7?

Its a new operator for combined comparison. Similar to strcmp() or version_compare() in behavior, but it can be used on all generic PHP values with the same semantics as <, <=, ==, >=, >. It returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It uses exactly the same comparison rules as used by our existing comparison operators: <, <=, ==, >= and >.

click here to know more

Call Javascript function from URL/address bar

About the window.location.hash property:

Return the anchor part of a URL.


Example 1:

//Assume that the current URL is 

var URL = "http://www.example.com/test.htm#part2";

var x = window.location.hash;

//The result of x will be:

x = "#part2"

Exmaple 2:

$(function(){   
    setTimeout(function(){
        var id = document.location.hash;
        $(id).click().blur();
    }, 200);
})

Example 3:

var hash = "#search" || window.location.hash;
window.location.hash = hash; 

switch(hash){   
case "#search":  
    selectPanel("pnlSearch");
    break;    
case "#advsearch":    

case "#admin":  

}

DNS caching in linux

Firefox contains a dns cache. To disable the DNS cache:

  1. Open your browser
  2. Type in about:config in the address bar
  3. Right click on the list of Properties and select New > Integer in the Context menu
  4. Enter 'network.dnsCacheExpiration' as the preference name and 0 as the integer value

When disabled, Firefox will use the DNS cache provided by the OS.

Create controller for partial view in ASP.NET MVC

If it were me, I would simply create a new Controller with a Single Action and then use RenderAction in place of Partial:

// Assuming the controller is named NewController
@{Html.RenderAction("ActionName", 
                     "New", 
                      new { routeValueOne = "SomeValue" });
}

How to delete a column from a table in MySQL

If you are running MySQL 5.6 onwards, you can make this operation online, allowing other sessions to read and write to your table while the operation is been performed:

ALTER TABLE tbl_Country DROP COLUMN IsDeleted, ALGORITHM=INPLACE, LOCK=NONE;

How do you round to 1 decimal place in Javascript?

Math.round( num * 10) / 10 doesn't work.

For example, 1455581777.8-145558160.4 gives you 1310023617.3999999.

So only use num.toFixed(1)

.war vs .ear file

J2EE defines three types of archives:

  1. Java Archives (JAR) A JAR file encapsulates one or more Java classes, a manifest, and a descriptor. JAR files are the lowest level of archive. JAR files are used in J2EE for packaging EJBs and client-side Java Applications.

  2. Web Archives (WAR) WAR files are similar to JAR files, except that they are specifically for web applications made from Servlets, JSPs, and supporting classes.

  3. Enterprise Archives (EAR) ”An EAR file contains all of the components that make up a particular J2EE application.

how to use "tab space" while writing in text file

Use "\t". That's the tab space character.

You can find a list of many of the Java escape characters here: http://java.sun.com/docs/books/tutorial/java/data/characters.html

Validate decimal numbers in JavaScript - IsNumeric()

I have run the following below and it passes all the test cases...

It makes use of the different way in which parseFloat and Number handle their inputs...

function IsNumeric(_in) {
    return (parseFloat(_in) === Number(_in) && Number(_in) !== NaN);
}

Select box arrow style

in Firefox 39 I've found that setting a border to the select element will render the arrow as (2). No border set, will render the arrow as (1). I think it's a bug.

javascript return true or return false when and how to use it?

Your code makes no sense, maybe because it's out of context.

If you mean code like this:

$('a').click(function () {
    callFunction();
    return false;
});

The return false will return false to the click-event. That tells the browser to stop following events, like follow a link. It has nothing to do with the previous function call. Javascript runs from top to bottom more or less, so a line cannot affect a previous line.

Adb Devices can't find my phone

Try doing this:

  • Unplug the device
  • Execute adb kill-server && adb start-server(that restarts adb)
  • Re-plug the device

Also you can try to edit an adb config file .android/adb_usb.ini and add a line 04e8 after the header. Restart adb required for changes to take effect.

jQuery: how to get which button was clicked upon form submission?

Building on what Stan and yann-h did but this one defaults to the first button. The beauty of this overall approach is that it picks up both the click and the enter key (even if the focus was not on the button. If you need to allow enter in the form, then just respond to this when a button is focused (i.e. Stan's answer). In my case, I wanted to allow enter to submit the form even if the user's current focus was on the text box.

I was also using a 'name' attribute rather than 'id' but this is the same approach.

var pressedButtonName =
     typeof $(":input[type=submit]:focus")[0] === "undefined" ?
     $(":input[type=submit]:first")[0].name :
     $(":input[type=submit]:focus")[0].name;

Command to get time in milliseconds

On OS X, where date does not support the %N flag, I recommend installing coreutils using Homebrew. This will give you access to a command called gdate that will behave as date does on Linux systems.

brew install coreutils

For a more "native" experience, you can always add this to your .bash_aliases:

alias date='gdate'

Then execute

$ date +%s%N

Image resizing client-side with JavaScript before upload to the server

http://nodeca.github.io/pica/demo/

In modern browser you can use canvas to load/save image data. But you should keep in mind several things if you resize image on the client:

  1. You will have only 8bits per channel (jpeg can have better dynamic range, about 12 bits). If you don't upload professional photos, that should not be a problem.
  2. Be careful about resize algorithm. The most of client side resizers use trivial math, and result is worse than it could be.
  3. You may need to sharpen downscaled image.
  4. If you wish do reuse metadata (exif and other) from original - don't forget to strip color profile info. Because it's applied when you load image to canvas.

How to retrieve a single file from a specific revision in Git?

In Windows, with Git Bash:

  • in your workspace, change dir to the folder where your file lives
  • git show cab485c83b53d56846eb883babaaf4dff2f2cc46:./your_file.ext > old.ext

ListView with OnItemClickListener

1) Check if you are using OnItemClickListener or OnClickListener (which is not supported for ListView)
Documentation Android Developers ListView

2) Check if you added Listener to your ListView properly. It's hooked on ListView not on ListAdapter!

ListView.setOnItemClickListener(listener);

3) If you need to use OnClickListener, check if you do use DialogInterface.OnClickListener or View.OnClickListener (they can be easily exchanged if not validated or if using both of them)

How to empty a char array?

You cannot empty an array as such, it always contains the same amount of data.

In a bigger context the data in the array may represent an empty list of items, but that has to be defined in addition to the array. The most common ways to do this is to keep a count of valid items (see the answer by pmg) or for strings to terminate them with a zero character (the answer by Felix). There are also more complicated ways, for example a ring buffer uses two indices for the positions where data is added and removed.

How to get duplicate items from a list using LINQ?

var duplicates = lst.GroupBy(s => s)
    .SelectMany(grp => grp.Skip(1));

Note that this will return all duplicates, so if you only want to know which items are duplicated in the source list, you could apply Distinct to the resulting sequence or use the solution given by Mark Byers.

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

Basically it depends on the precision you need for your locations. Using DOUBLE you'll have a 3.5nm precision. DECIMAL(8,6)/(9,6) goes down to 16cm. FLOAT is 1.7m...

This very interesting table has a more complete list: http://mysql.rjweb.org/doc.php/latlng :

Datatype               Bytes            Resolution

Deg*100 (SMALLINT)     4      1570 m    1.0 mi  Cities
DECIMAL(4,2)/(5,2)     5      1570 m    1.0 mi  Cities
SMALLINT scaled        4       682 m    0.4 mi  Cities
Deg*10000 (MEDIUMINT)  6        16 m     52 ft  Houses/Businesses
DECIMAL(6,4)/(7,4)     7        16 m     52 ft  Houses/Businesses
MEDIUMINT scaled       6       2.7 m    8.8 ft
FLOAT                  8       1.7 m    5.6 ft
DECIMAL(8,6)/(9,6)     9        16cm    1/2 ft  Friends in a mall
Deg*10000000 (INT)     8        16mm    5/8 in  Marbles
DOUBLE                16       3.5nm     ...    Fleas on a dog

Hope this helps.

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

Eclipse Error: "Failed to connect to remote VM"

Create setenv.bat file in nib folder of Tomcat. Add SET JPDA_ADDRESS = 8787 ; Override the jpda port Open cmd, go to bin folder of Tomcat and Start tomcat using catalina jpda start Set up a debug point on eclipse Next compile your project. Check localhost:8080/ Deploy the war or jar under webapps folder and this must deploy war on Tomcat. Then send the request. the debug point will get hit NOTE : Don't edit catalina.bat file. make changes in setenv.bat file

Creating composite primary key in SQL Server

How about something like

CREATE TABLE testRequest (
        wardNo nchar(5),
        BHTNo nchar(5),
        testID nchar(5),
        reqDateTime datetime,
        PRIMARY KEY (wardNo, BHTNo, testID)
);

Have a look at this example

SQL Fiddle DEMO

Mongoose: Find, modify, save

findOne, modify fields & save

User.findOne({username: oldUsername})
  .then(user => {
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.markModified('username');
    user.markModified('password');
    user.markModified('rights');

    user.save(err => console.log(err));
});

OR findOneAndUpdate

User.findOneAndUpdate({username: oldUsername}, {$set: { username: newUser.username, user: newUser.password, user:newUser.rights;}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }
    console.log(doc);
});

Also see updateOne

How to fix 'fs: re-evaluating native module sources is not supported' - graceful-fs

Just to point out that cordova brings in it's own npm with the graceful-fs dependency, so if you use Cordova make sure that it is the latest so you get the latest graceful-fs from that as well.

What is the difference between jQuery: text() and html() ?

Well in simple term.

html()-- to get inner html(html tags and text).

text()-- to get only text if present inside(only text)

How do I concatenate strings with variables in PowerShell?

You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.

Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}

(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)

Secure FTP using Windows batch script

First, make sure you understand, if you need to use Secure FTP (=FTPS, as per your text) or SFTP (as per tag you have used).

Neither is supported by Windows command-line ftp.exe. As you have suggested, you can use WinSCP. It supports both FTPS and SFTP.

Using WinSCP, your batch file would look like (for SFTP):

echo open sftp://ftp_user:[email protected] -hostkey="server's hostkey" >> ftpcmd.dat
echo put c:\directory\%1-export-%date%.csv >> ftpcmd.dat
echo exit >> ftpcmd.dat
winscp.com /script=ftpcmd.dat
del ftpcmd.dat

And the batch file:

winscp.com /log=ftpcmd.log /script=ftpcmd.dat /parameter %1 %date%

Though using all capabilities of WinSCP (particularly providing commands directly on command-line and the %TIMESTAMP% syntax), the batch file simplifies to:

winscp.com /log=ftpcmd.log /command ^
    "open sftp://ftp_user:[email protected] -hostkey=""server's hostkey""" ^
    "put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
    "exit"

For the purpose of -hostkey switch, see verifying the host key in script.

Easier than assembling the script/batch file manually is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you:

Generate batch file

All you need to tweak is the source file name (use the %TIMESTAMP% syntax as shown previously) and the path to the log file.


For FTPS, replace the sftp:// in the open command with ftpes:// (explicit TLS/SSL) or ftps:// (implicit TLS/SSL). Remove the -hostkey switch.

winscp.com /log=ftpcmd.log /command ^
    "open ftps://ftp_user:[email protected] -explicit" ^
    "put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
    "exit"

You may need to add the -certificate switch, if your server's certificate is not issued by a trusted authority.

Again, as with the SFTP, easier is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you.


See a complete conversion guide from ftp.exe to WinSCP.

You should also read the Guide to automating file transfers to FTP server or SFTP server.


Note to using %TIMESTAMP#yyyymmdd% instead of %date%: A format of %date% variable value is locale-specific. So make sure you test the script on the same locale you are actually going to use the script on. For example on my Czech locale the %date% resolves to ct 06. 11. 2014, what might be problematic when used as a part of a file name.

For this reason WinSCP supports (locale-neutral) timestamp formatting natively. For example %TIMESTAMP#yyyymmdd% resolves to 20170515 on any locale.

(I'm the author of WinSCP)

Switch case: can I use a range instead of a one number

Interval is constant:

 int range = 5
 int newNumber = number / range;
 switch (newNumber)
 {
      case (0): //number 0 to 4
                break;
      case (1): //number 5 to 9
                break;
      case (2): //number 10 to 14
                break;
      default:  break;
 }

Otherwise:

  if else

Pass Array Parameter in SqlCommand

If you are using MS SQL Server 2008 and above you can use table-valued parameters like described here http://www.sommarskog.se/arrays-in-sql-2008.html.

1. Create a table type for each parameter type you will be using

The following command creates a table type for integers:

create type int32_id_list as table (id int not null primary key)

2. Implement helper methods

public static SqlCommand AddParameter<T>(this SqlCommand command, string name, IEnumerable<T> ids)
{
  var parameter = command.CreateParameter();      

  parameter.ParameterName = name;
  parameter.TypeName = typeof(T).Name.ToLowerInvariant() + "_id_list";
  parameter.SqlDbType = SqlDbType.Structured;
  parameter.Direction = ParameterDirection.Input;

  parameter.Value = CreateIdList(ids);

  command.Parameters.Add(parameter);
  return command;
}

private static DataTable CreateIdList<T>(IEnumerable<T> ids)
{
  var table = new DataTable();
  table.Columns.Add("id", typeof (T));

  foreach (var id in ids)
  {
    table.Rows.Add(id);
  }

  return table;
}

3. Use it like this

cmd.CommandText = "select * from TableA where Age in (select id from @age)"; 
cmd.AddParameter("@age", new [] {1,2,3,4,5});

How to sort by Date with DataTables jquery plugin?

Specify the column's type as type: 'date':

{title: 'Expiration Date', data: 'ExpirationDate', type: 'date'}

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

Microsoft Excel ActiveX Controls Disabled?

With Windows 8.1 I couldn't find any .exd files using windows search. On the other hand, a cmd command dir *.exd /S found the one file on my system.

Is PowerShell ready to replace my Cygwin shell on Windows?

TL;DR -- I don't hate Windows or PowerShell. I just can't do anything in Windows or on PowerShell.


I personally still find PowerShell underwhelming at best.

  • tab completion of directory paths do not compound, requiring the user to enter a path separator after every name completion.
  • I still feel like Windows doesn't even have the concept of a path or of what a path is, with no accessible user home indicator ~/ short of some @environment://somejibberish/%user_home%
  • NTFS is still a mess and seemingly always will be. Good luck navigating.

  • cmd-esque interface, The dinosaur cmd.exe is still visible in PowerShell, EditMark still being the only way to copy information, and copying only in the form of rectangular blocks of visible terminal space. and EditMark still being the only way to paste strings into the terminal.

  • Painting it blue doesn't make it any more attractive. I don't mind Microsoft developers having a taste in color though.

  • Windows always opens at top left corner of screen. For somebody who uses vertical task bars this is incredibly annoying, especially considering that the Windows task bar will cover the only corner of the window that gives access to copy/paste functionality.

I can't speak much on the grounds of the tools Windows includes. Being that there is a whole set of open-source, freely licensed CLI tools, and PowerShell ships with, to my knowledge, none of them is an utter disappointment.

  • PowerShell's wget takes seemingly incomparable arguments to GNU wget. Thanks, glimmer of hope portably-useless.
  • PowerShell POSIX is not Bash-compatible, particularly the && operator is not handled, making the simplest of conditional command following not a thing.

I don't know man; I gave it a shot, I really did; I still try to give it a shot in the hopes that the next time I open it it will be any less useless. I cannot do anything in PowerShell, and I can barely do things with a real project to bring GNU tools to Windows.

MySysGit gives me the dinosaur cmd.exe prompt with a couple of GNU tools, and it is still very underwhelming, but at last path completion works. And the Git command will run in Git Bash.

Mintty for MySysGit gives the Cygwin interface over mysysgit's environment, making copy and paste a thing (select to copy (mouse), Shift+Ins to paste, how modern...). However, things like git push are broken in Mintty.

I don't mean to rant, but I still see huge problems with command-line usability on Windows even given tools like Cygwin.


P.S.: Just because something can be done in PowerShell, doesn't make it usable. Usability is deeper than ability and is what I tend to focus on when trying to use a product as a consumer.

Twitter Bootstrap Multilevel Dropdown Menu

Since Bootstrap 3 removed the submenu part and we need to adapt ourselves the style, I think it's better to go with SmartMenu Bootstrap: https://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar.html#

That would save us time on mobile responsive and style.

This plugin also very promising.

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

dplyr mutate with conditional values

Try this:

myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

or this:

myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

Note

Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.

Above used this input:

myfile <- 
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L, 
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

Update 1 Since originally posted dplyr has changed %.% to %>% so have modified answer accordingly.

Update 2 dplyr now has case_when which provides another solution:

myfile %>% 
       mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1, 
                             V2 == 4 & V3 != 1 ~ 2,
                             TRUE ~ 0))

Passing a varchar full of comma delimited values to a SQL Server IN function

You could do it like this:

create or replace 
PROCEDURE UDP_SETBOOKMARK 
(
  P_USERID IN VARCHAR2  
, P_BOOKMARK IN VARCHAR2  
) AS 
BEGIN

UPDATE T_ER_Bewertung
SET LESEZEICHEN = P_BOOKMARK
WHERE STAMM_ID in( select regexp_substr(P_USERID,'[^,]+', 1, level) from dual
                   connect by regexp_substr(P_USERID, '[^,]+', 1, level) is not null )
and ER_ID = (select max(ER_ID) from T_ER_Bewertung_Kopie);

commit;

END UDP_SETBOOKMARK;

Then try it with

Begin
UDP_SETBOOKMARK ('1,2,3,4,5', 'Test');
End;

You can use this IN-Clause with regexp_substr in other situations too, just try it.

Parsing a comma-delimited std::string

Yet another, rather different, approach: use a special locale that treats commas as white space:

#include <locale>
#include <vector>

struct csv_reader: std::ctype<char> {
    csv_reader(): std::ctype<char>(get_table()) {}
    static std::ctype_base::mask const* get_table() {
        static std::vector<std::ctype_base::mask> rc(table_size, std::ctype_base::mask());

        rc[','] = std::ctype_base::space;
        rc['\n'] = std::ctype_base::space;
        rc[' '] = std::ctype_base::space;
        return &rc[0];
    }
}; 

To use this, you imbue() a stream with a locale that includes this facet. Once you've done that, you can read numbers as if the commas weren't there at all. Just for example, we'll read comma-delimited numbers from input, and write then out one-per line on standard output:

#include <algorithm>
#include <iterator>
#include <iostream>

int main() {
    std::cin.imbue(std::locale(std::locale(), new csv_reader()));
    std::copy(std::istream_iterator<int>(std::cin), 
              std::istream_iterator<int>(),
              std::ostream_iterator<int>(std::cout, "\n"));
    return 0;
}

How can I create a link to a local file on a locally-run web page?

Janky at best

<a href="file://///server/folders/x/x/filename.ext">right click </a></td>

and then right click, select "copy location" option, and then paste into url.

CodeIgniter: Load controller within controller

Just use

..............

self::index();

..............

String formatting: % vs. .format vs. string literal

PEP 3101 proposes the replacement of the % operator with the new, advanced string formatting in Python 3, where it would be the default.

Request Permission for Camera and Library in iOS 10 - Info.plist

I wrote an extension that takes into account all possible cases:

  • If access is allowed, then the code onAccessHasBeenGranted will be run.
  • If access is not determined, then requestAuthorization(_:) will be called.
  • If the user has denied your app photo library access, then the user will be shown a window offering to go to settings and allow access. In this window, the "Cancel" and "Settings" buttons will be available to him. When he presses the "settings" button, your application settings will open.

Usage example:

PHPhotoLibrary.execute(controller: self, onAccessHasBeenGranted: {
    // access granted... 
})

Extension code:

import Photos
import UIKit

public extension PHPhotoLibrary {

   static func execute(controller: UIViewController,
                       onAccessHasBeenGranted: @escaping () -> Void,
                       onAccessHasBeenDenied: (() -> Void)? = nil) {

      let onDeniedOrRestricted = onAccessHasBeenDenied ?? {
         let alert = UIAlertController(
            title: "We were unable to load your album groups. Sorry!",
            message: "You can enable access in Privacy Settings",
            preferredStyle: .alert)
         alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
         alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { _ in
            if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
               UIApplication.shared.open(settingsURL)
            }
         }))
         controller.present(alert, animated: true)
      }

      let status = PHPhotoLibrary.authorizationStatus()
      switch status {
      case .notDetermined:
         onNotDetermined(onDeniedOrRestricted, onAccessHasBeenGranted)
      case .denied, .restricted:
         onDeniedOrRestricted()
      case .authorized:
         onAccessHasBeenGranted()
      @unknown default:
         fatalError("PHPhotoLibrary::execute - \"Unknown case\"")
      }
   }

}

private func onNotDetermined(_ onDeniedOrRestricted: @escaping (()->Void), _ onAuthorized: @escaping (()->Void)) {
   PHPhotoLibrary.requestAuthorization({ status in
      switch status {
      case .notDetermined:
         onNotDetermined(onDeniedOrRestricted, onAuthorized)
      case .denied, .restricted:
         onDeniedOrRestricted()
      case .authorized:
         onAuthorized()
      @unknown default:
         fatalError("PHPhotoLibrary::execute - \"Unknown case\"")
      }
   })
}

How to recursively delete an entire directory with PowerShell 2.0?

There seems to be issues where Remove-Item -Force -Recurse can intermittently fail on Windows because the underlying filesystem is asynchronous. This answer seems to address it. The user has also been actively involved with the Powershell team on GitHub.

Check if element is in the list (contains)

You can use std::find

bool found = (std::find(my_list.begin(), my_list.end(), my_var) != my_list.end());

You need to include <algorithm>. It should work on standard containers, vectors lists, etc...

Hibernate Annotations - Which is better, field or property access?

AccessType.PROPERTY: The EJB persistence implementation will load state into your class via JavaBean "setter" methods, and retrieve state from your class using JavaBean "getter" methods. This is the default.

AccessType.FIELD: State is loaded and retrieved directly from your class' fields. You do not have to write JavaBean "getters" and "setters".

Set a path variable with spaces in the path in a Windows .cmd file or batch file

also just try adding double slashes like this works for me only

set dir="C:\\1. Some Folder\\Some Other Folder\\Just Because"

@echo on MKDIR %dir%

OMG after posting they removed the second \ in my post so if you open my comment and it shows three you should read them as two......

Remove part of string after "."

You could do:

sub("*\\.[0-9]", "", a)

or

library(stringr)
str_sub(a, start=1, end=-3)

angular ng-repeat in reverse

Useful tip:

You can reverse you're array with vanilla Js: yourarray .reverse()

Caution: reverse is destructive, so it will change youre array, not only the variable.

How to set HttpResponse timeout for Android in Java

public boolean isInternetWorking(){
    try {
        int timeOut = 5000;
        Socket socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress("8.8.8.8",53);
        socket.connect(socketAddress,timeOut);
        socket.close();
        return true;
    } catch (IOException e) {
        //silent
    }
    return false;
}

How to use "raise" keyword in Python

You can use it to raise errors as part of error-checking:

if (a < b):
    raise ValueError()

Or handle some errors, and then pass them on as part of error-handling:

try:
    f = open('file.txt', 'r')
except IOError:
    # do some processing here
    # and then pass the error on
    raise