Programs & Examples On #Stringtemplate

A templating language which strictly enforces model/view separation

C read file line by line

If your task is not to invent the line-by-line reading function, but just to read the file line-by-line, you may use a typical code snippet involving the getline() function (see the manual page here):

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

int main(void)
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;

    fp = fopen("/etc/motd", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);

    while ((read = getline(&line, &len, fp)) != -1) {
        printf("Retrieved line of length %zu:\n", read);
        printf("%s", line);
    }

    fclose(fp);
    if (line)
        free(line);
    exit(EXIT_SUCCESS);
}

How to convert List<string> to List<int>?

yourEnumList.Select(s => (int)s).ToList()

Disabling Minimize & Maximize On WinForm?

Bind a handler to the FormClosing event, then set e.Cancel = true, and set the form this.WindowState = FormWindowState.Minimized.

If you want to ever actually close the form, make a class-wide boolean _close and, in your handler, set e.Cancel to !_close, so that whenever the user clicks the X on the window, it doesn't close, but you can still close it (without just killing it) with close = true; this.Close();

(And just to make my answer complete) set MaximizeBox and MinimizeBox form properties to False.

EXCEL Multiple Ranges - need different answers for each range

use

=VLOOKUP(D4,F4:G9,2)

with the range F4:G9:

0   0.1
1   0.15
5   0.2
15  0.3
30  1
100 1.3

and D4 being the value in question, e.g. 18.75 -> result: 0.3

Removing body margin in CSS

This should help you get rid of body margins and default top margin of <h1> tag

body{
        margin: 0px;
        padding: 0px;
    }

h1 {
        margin-top: 0px;
    }

Why my regexp for hyphenated words doesn't work?

This regex should do it.

\b[a-z]+-[a-z]+\b 

\b indicates a word-boundary.

standard size for html newsletter template

Short answer: 400-800 pixels.

What I have read is that HTML newsletter width should be as narrow as possible without being too narrow. For instance, 400-500 pixels for a one column layout is a lower limit. Any less may look too weird.

Today's widescreen monitors allow for more horizontal pixels and most web email clients will either be of the two-column variety (Gmail) or 3-pane layout where the content window bellow the inbox list (Hotmail and Yahoo). In either case, you can be okay with 800 pixels if you're targeting the 1280 wide audience. An older or less technical audience may have older, square monitors.

There is the problem of Outlook having a three-column layout. That limits the width of your email even more. With them, you may want to go even narrower.

I just recently created a template that required an ad banner that is 730 pixels wide. It was near in the wide range, but not so much that most people could not double-click the email an open a new window in Outlook (the web email users should be okay for the most part).

Hope this advice helps.

jquery smooth scroll to an anchor?

Using hanoo's script I created a jQuery function:

$.fn.scrollIntoView = function(duration, easing) {
    var dest = 0;
    if (this.offset().top > $(document).height() - $(window).height()) {
        dest = $(document).height() - $(window).height();
    } else {
        dest = this.offset().top;
    }
    $('html,body').animate({
        scrollTop: dest
    }, duration, easing);
    return this;
};

usage:

$('#myelement').scrollIntoView();

Defaults for duration and easing are 400ms and "swing".

Check if a string is a palindrome

    public  bool MojTestPalindrome (string word)
    {
        bool yes = false;

        char[]test1 = word.ToArray();
        char[] test2 = test1.Reverse().ToArray();
        for (int i=0; i< test2.Length; i++)
        {

            if (test1[i] != test2[test2.Length - 1 - i])
            {

                yes = false;
                break;

            }
            else {   
                yes = true;


            }
        }
        if (yes == true)
        {
            return true;
        }
        else

            return false;                
    }

Android Activity as a dialog

If you want to remove activity header & provide a custom view for the dialog add the following to the activity block of you manifest

android:theme="@style/Base.Theme.AppCompat.Dialog"

and design your activity_layout with your desired view

Where can I find decent visio templates/diagrams for software architecture?

There should be templates already included in Visio 2007 for software architecture but you might want to check out Visio 2007 templates.

python: urllib2 how to send cookie with urlopen request

This answer is not working since the urllib2 module has been split across several modules in Python 3. You need to do

from urllib import request
opener = request.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

Can you use if/else conditions in CSS?

You can use calc() in combination with var() to sort of mimic conditionals:

:root {
--var-eq-two: 0;
}

.var-eq-two {
    --var-eq-two: 1;
}

.block {
    background-position: calc(
        150px * var(--var-eq-two) +
        4px * (1 - var(--var-eq-two))
    ) 8px;
}

concept

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

Ajax Success and Error function failure

This may be an old post but I realized there is nothing to be returned from the php and your success function does not have input like as follows, success:function(e){}. I hope that helps you.

how to display data values on Chart.js

This animation option works for 2.1.3 on a bar chart.

Slightly modified @Ross answer

animation: {
duration: 0,
onComplete: function () {
    // render the value of the chart above the bar
    var ctx = this.chart.ctx;
    ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
    ctx.fillStyle = this.chart.config.options.defaultFontColor;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'bottom';
    this.data.datasets.forEach(function (dataset) {
        for (var i = 0; i < dataset.data.length; i++) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            ctx.fillText(dataset.data[i], model.x, model.y - 5);
        }
    });
}}

Bootstrap 4 Center Vertical and Horizontal Alignment

been going thru a lot of posts on getting a form centered in the page and none of them worked. code below is from a react component using bootstrap 4.1. height should be 100vh and not 100%

<div className="container">
      <div className="d-flex justify-content-center align-items-center" style={height}>
        <form>
          <div className="form-group">
            <input className="form-control form-control-lg" placeholder="Email" type="email"/>
          </div>
          <div className="form-group">
            <input className="form-control form-control-lg" placeholder="Password" type="password"/>
          </div>
          <div className="form-group">
            <button className="btn btn-info btn-lg btn-block">Sign In</button>
          </div>
        </form>
      </div>
    </div>

where height in style is:

const height = { height: '100vh' }

How do I download/extract font from chrome developers tools?

Although Marcelo's solution seems to be working great, you may not need to download the font at all! Just link to it remotely.

E.g the font is hosted on example.com, do

@font-face {
  font-family: "Font Name";
  font-style: normal;
  src: url(http://example.com/webfonts/font-name.woff);
}

You may easily figure out the direct url to the font by looking into css code from example.com and see how they linked the file.

How to pass multiple values to single parameter in stored procedure

Either use a User Defined Table

Or you can use CSV by defining your own CSV function as per This Post.

I'd probably recommend the second method, as your stored proc is already written in the correct format and you'll find it handy later on if you need to do this down the road.

Cheers!

Android Studio - Auto complete and other features not working

Close Android Studio Go to C:\Users\UserName.android and rename the folder:

  • build-cache to build-cache_old

Go to C:\Users\UserName.AndroidStudio3.x\system OR (Android studio 4 and Higher) Go to C:\Users\UserName\AppData\Local\Google\AndroidStudio4.x and rename these folders:

  • caches to caches_old

  • compiler to compiler_old

  • compile-server to compile-server_old

  • conversion to conversion_old

  • external_build_system to external_build_system_old

  • frameworks to frameworks_old

  • gradle to gradle_old

  • resource_folder_cache to resource_folder_cache_old

Open the Android Studio and open your project again.

In Tkinter is there any way to make a widget not visible?

I was not using grid or pack.
I used just place for my widgets as their size and positioning was fixed.
I wanted to implement hide/show functionality on frame.
Here is demo

from tkinter import *
window=Tk()
window.geometry("1366x768+1+1")
def toggle_graph_visibility():
    graph_state_chosen=show_graph_checkbox_value.get()
    if graph_state_chosen==0:
        frame.place_forget()
    else:
        frame.place(x=1025,y=165)
score_pixel = PhotoImage(width=300, height=430)
show_graph_checkbox_value = IntVar(value=1)
frame=Frame(window,width=300,height=430)
graph_canvas = Canvas(frame, width = 300, height = 430,scrollregion=(0,0,300,300))
my_canvas=graph_canvas.create_image(20, 20, anchor=NW, image=score_pixel)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.config(command=graph_canvas.yview)
vbar.pack(side=RIGHT,fill=Y)
graph_canvas.config(yscrollcommand=vbar.set)
graph_canvas.pack(side=LEFT,expand=True,fill=BOTH)
frame.place(x=1025,y=165)
Checkbutton(window, text="show graph",variable=show_graph_checkbox_value,command=toggle_graph_visibility).place(x=900,y=165)
window.mainloop()

Note that in above example when 'show graph' is ticked then there is vertical scrollbar.
Graph disappears when checkbox is unselected.
I was fitting some bar graph in that area which I have not shown to keep example simple.
Most important thing to learn from above is the use of frame.place_forget() to hide and frame.place(x=x_pos,y=y_pos) to show back the content.

Using await outside of an async function

Top level await is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.

There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:

// data.js
const data = await fetch( '/data.json' );
export default data;

Now any file that imports data.js won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.

My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.

Install specific branch from github using Npm

you can give git pattern as version, yarn and npm are clever enough to resolve from a git repo.

yarn add any-package@user-name/repo-name#branch-name

or for npm

npm install --save any-package@user-name/repo-name#branch-name

"unmappable character for encoding" warning in Java

If you're using Maven, set the <encoding> explicitly in the compiler plugin's configuration, e.g.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>

Deserializing JSON array into strongly typed .NET object

This solution seems to work for me and gets around having to code a bunch of classes with "Data" in them.

public interface IDataResponse<T> where T : class
{
    List<T> Data { get; set; }
}

public class DataResponse<T> : IDataResponse<T> where T : class
{
   [JsonProperty("data")]
   public List<T> Data { get; set; }
}

I should have included this to begin with, here is an example method using the above:

public List<TheUser> GetUser()
{
    var results = GetUserJson();
    var userList = JsonConvert.DeserializeObject<DataResponse<TheUser>>(results.ToString());

    return userList.Data.ToList();
} 

How to avoid soft keyboard pushing up my layout?

windowSoftInputMode will either pan or resize your activity layout. One thing that you can do is to attach an onFocusChanged listener to your EditText and when the user selects/taps the EditText then you hide or move your navigation buttons out of the screen. When the EditText loses focus then you can put the navigation buttons back at the bottom of the activity.

jQuery - Sticky header that shrinks when scrolling down

This should be what you are looking for using jQuery.

$(function(){
  $('#header_nav').data('size','big');
});

$(window).scroll(function(){
  if($(document).scrollTop() > 0)
{
    if($('#header_nav').data('size') == 'big')
    {
        $('#header_nav').data('size','small');
        $('#header_nav').stop().animate({
            height:'40px'
        },600);
    }
}
else
  {
    if($('#header_nav').data('size') == 'small')
      {
        $('#header_nav').data('size','big');
        $('#header_nav').stop().animate({
            height:'100px'
        },600);
      }  
  }
});

Demonstration: http://jsfiddle.net/jezzipin/JJ8Jc/

How to send an object from one Android Activity to another using Intents?

For situations where you know you will be passing data within an application, use "globals" (like static Classes)

Here is what Dianne Hackborn (hackbod - a Google Android Software Engineer) had to say on the matter:

For situations where you know the activities are running in the same process, you can just share data through globals. For example, you could have a global HashMap<String, WeakReference<MyInterpreterState>> and when you make a new MyInterpreterState come up with a unique name for it and put it in the hash map; to send that state to another activity, simply put the unique name into the hash map and when the second activity is started it can retrieve the MyInterpreterState from the hash map with the name it receives.

How to check if spark dataframe is empty?

I had the same question, and I tested 3 main solution :

  1. (df != null) && (df.count > 0)
  2. df.head(1).isEmpty() as @hulin003 suggest
  3. df.rdd.isEmpty() as @Justin Pihony suggest

and of course the 3 works, however in term of perfermance, here is what I found, when executing the these methods on the same DF in my machine, in terme of execution time :

  1. it takes ~9366ms
  2. it takes ~5607ms
  3. it takes ~1921ms

therefore I think that the best solution is df.rdd.isEmpty() as @Justin Pihony suggest

How to add files/folders to .gitignore in IntelliJ IDEA?

right click on the project create a file with name .ignore, then you can see that file opened.

at the right top of the file you can see install plugins or else you can install using plugins(plugin name - .ignore).

Now when ever you give a right click on the file or project you can see the option call add to .ignore

TypeError: tuple indices must be integers, not str

The Problem is how you access row

Specifically row["waocs"] and row["pool_number"] of ocs[row["pool_number"]]=int(row["waocs"])

If you look up the official-documentation of fetchall() you find.

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples.

Therefore you have to access the values of rows with row[__integer__] like row[0]

Export to csv/excel from kibana

In Kibana 6.5, you can generate CSV under the Share Tab -> CSV Reports.

The request will be queued. Once the CSV is generated, it will be available for download under Management -> Reporting

How to assign the output of a command to a Makefile variable

Use the Make shell builtin like in MY_VAR=$(shell echo whatever)

me@Zack:~$make
MY_VAR IS whatever

me@Zack:~$ cat Makefile 
MY_VAR := $(shell echo whatever)

all:
    @echo MY_VAR IS $(MY_VAR)

How can I get the first two digits of a number?

Comparing the O(n) time solution with the "constant time" O(1) solution provided in other answers goes to show that if the O(n) algorithm is fast enough, n may have to get very large before it is slower than a slow O(1).

The strings version is approx. 60% faster than the "maths" version for numbers of 20 or fewer digits. They become closer only when then number of digits approaches 200 digits

# the "maths" version
import math

def first_n_digits1(num, n):
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

%timeit first_n_digits1(34523452452, 2)
1.21 µs ± 75 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits1(34523452452, 8)
1.24 µs ± 47.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 22 digits
%timeit first_n_digits1(3423234239472523452452, 2)
1.33 µs ± 59.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits1(3423234239472523452452, 15)
1.23 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 196 digits
%timeit first_n_digits1(3423234239472523409283475908723908723409872390871243908172340987123409871234012089172340987734507612340981344509873123401234670350981234098123140987314509812734091823509871345109871234098172340987125988123452452, 39)
1.86 µs ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# The "string" verions
def first_n_digits2(num, n):
    return int(str(num)[:n])

%timeit first_n_digits2(34523452452, 2)
744 ns ± 28.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits2(34523452452, 8)
768 ns ± 42.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 22 digits
%timeit first_n_digits2(3423234239472523452452, 2)
767 ns ± 33.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit first_n_digits2(3423234239472523452452, 15)
830 ns ± 55.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

# 196 digits
%timeit first_n_digits2(3423234239472523409283475908723908723409872390871243908098712340987123401208917234098773450761234098134450987312340123467035098123409812314098734091823509871345109871234098172340987125988123452452, 39)
1.87 µs ± 140 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Alternate background colors for list items

This is set background color on even and odd li:

  li:nth-child(odd) { background: #ffffff; }
  li:nth-child(even) { background: #80808030; }

`ui-router` $stateParams vs. $state.params

There are many differences between these two. But while working practically I have found that using $state.params better. When you use more and more parameters this might be confusing to maintain in $stateParams. where if we use multiple params which are not URL param $state is very useful

 .state('shopping-request', {
      url: '/shopping-request/{cartId}',
      data: {requireLogin: true},
      params : {role: null},
      views: {
        '': {templateUrl: 'views/templates/main.tpl.html', controller: "ShoppingRequestCtrl"},
        'body@shopping-request': {templateUrl: 'views/shops/shopping-request.html'},
        'footer@shopping-request': {templateUrl: 'views/templates/footer.tpl.html'},
        'header@shopping-request': {templateUrl: 'views/templates/header.tpl.html'}
      }
    })

Why would one use nested classes in C++?

I don't use nested classes much, but I do use them now and then. Especially when I define some kind of data type, and I then want to define a STL functor designed for that data type.

For example, consider a generic Field class that has an ID number, a type code and a field name. If I want to search a vector of these Fields by either ID number or name, I might construct a functor to do so:

class Field
{
public:
  unsigned id_;
  string name_;
  unsigned type_;

  class match : public std::unary_function<bool, Field>
  {
  public:
    match(const string& name) : name_(name), has_name_(true) {};
    match(unsigned id) : id_(id), has_id_(true) {};
    bool operator()(const Field& rhs) const
    {
      bool ret = true;
      if( ret && has_id_ ) ret = id_ == rhs.id_;
      if( ret && has_name_ ) ret = name_ == rhs.name_;
      return ret;
    };
    private:
      unsigned id_;
      bool has_id_;
      string name_;
      bool has_name_;
  };
};

Then code that needs to search for these Fields can use the match scoped within the Field class itself:

vector<Field>::const_iterator it = find_if(fields.begin(), fields.end(), Field::match("FieldName"));

How to know user has clicked "X" or the "Close" button?

if (this.DialogResult == DialogResult.Cancel)
        {

        }
        else
        {
            switch (e.CloseReason)
            {
                case CloseReason.UserClosing:
                    e.Cancel = true;
                    break;
            }
        }

if condition will execute when user clicks 'X' or close button on form. The else can be used when user clicks Alt+f4 for any other purpose

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Permission denied for relation

1st and important step is connect to your db:

psql -d yourDBName

2 step, grant privileges

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO userName;

How do you return a JSON object from a Java Servlet

Just write a string to the output stream. You might set the MIME-type to text/javascript (edit: application/json is apparently officialer) if you're feeling helpful. (There's a small but nonzero chance that it'll keep something from messing it up someday, and it's a good practice.)

Typing Greek letters etc. in Python plots

Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:

from matplotlib import rc

rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)

This would change your serif latex font. You can also specify the sans-serif Helvetica like so

rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})

Other options are cursive and monospace with their respective font names. Your label would then be

fig.gca().set_xlabel(r'wavelength $5000 \AA$')

If the font doesn't supply an Angstrom symbol you can try using \mathring{A}

Update just one gem with bundler

The way to do this is to run the following command:

bundle update --source gem-name

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Try changing the port number in your project?

Project Properties ? Web ? Servers ? Project Url:

enter image description here

Don't forget to click Create Virtual Directory, or reply "Yes" to the prompt for creating virtual directory after you change your port number! (Thanks Connor)

Note: I'm a little reluctant to post this as an answer, as I have no idea what the issue is or what caused it, but I had a similar issue, and changing the port number did the trick for me. I'm only posting this per the suggestion in the comments that this worked for someone else as well.

In my case, it seemed like something was conflicting with the specific port number I was using, so I changed to a different one, and my site popped right back up! I'm not sure what that means for the old port number, or if I'll ever be able to use it again. Maybe someone more knowledgeable than myself can chime in on this.

git status (nothing to commit, working directory clean), however with changes commited

I had the same issue because I had 2 .git folders in the working directory.

Your problem may be caused by the same thing, so I recommend checking to see if you have multiple .git folders, and, if so, deleting one of them.

That allowed me to upload the project successfully.

How do you extract a column from a multi-dimensional array?

I think you want to extract a column from an array such as an array below

import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])

Now if you want to get the third column in the format

D=array[[3],
[7],
[11]]

Then you need to first make the array a matrix

B=np.asmatrix(A)
C=B[:,2]
D=asarray(C)

And now you can do element wise calculations much like you would do in excel.

C# '@' before a String

It also means you can use reserved words as variable names

say you want a class named class, since class is a reserved word, you can instead call your class class:

IList<Student> @class = new List<Student>();

How to change line width in IntelliJ (from 120 character)

It seems like Jetbrains made some renaming and moved settings around so the accepted answer is no longer 100% valid anymore.

Intellij 2018.3:

hard wrap - idea will automatically wrap the line as you type, this is not what the OP was asking for

visual guide - just a vertical line indicating a characters limit, default is 120


If you just want to change the visual guide from the default 120 to lets say 80 in my example:

enter image description here

Also you can change the color or the visual guide by clicking on the Foreground:

enter image description here

Lastly, you can also set the visual guide for all file types (unless specified) here:

enter image description here

How display only years in input Bootstrap Datepicker?

format: "YYYY" 

Should be capital instead of "yyyy"

What is the functionality of setSoTimeout and how it works?

Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?

No, it means that if no data arrives within 2000ms a SocketTimeoutException will be thrown.

What does it mean timeout expire?

It means the 2000ms (in your case) elapses without any data arriving.

What is the option which must be enabled prior to blocking operation?

There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.

Infinite Timeout menas that the socket does't read anymore?

What a strange suggestion. It means that if no data ever arrives you will block in the read forever.

How to break out of jQuery each Loop

"each" uses callback function. Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.

use for loop if you have to stop the loop execution based on some condition and remain in to the same function.

Android overlay a view ontop of everything?

The best way is ViewOverlay , You can add any drawable as overlay to any view as its overlay since Android JellyBeanMR2(Api 18).

Add mMyDrawable to mMyView as its overlay:

mMyDrawable.setBounds(0, 0, mMyView.getMeasuredWidth(), mMyView.getMeasuredHeight())
mMyView.getOverlay().add(mMyDrawable)

How does one reorder columns in a data frame?

Maybe it's a coincidence that the column order you want happens to have column names in descending alphabetical order. Since that's the case you could just do:

df<-df[,order(colnames(df),decreasing=TRUE)]

That's what I use when I have large files with many columns.

How to get UTC+0 date in Java 8?

In java8, I would use the Instant class which is already in UTC and is convenient to work with.

import java.time.Instant;

Instant ins = Instant.now();
long ts = ins.toEpochMilli();

Instant ins2 = Instant.ofEpochMilli(ts)

Alternatively, you can use the following:

import java.time.*;

Instant ins = Instant.now(); 

OffsetDateTime odt = ins.atOffset(ZoneOffset.UTC);
ZonedDateTime zdt = ins.atZone(ZoneId.of("UTC"));

Back to Instant

Instant ins4 = Instant.from(odt);

What's the best practice to round a float to 2 decimals?

Let's test 3 methods:
1)

public static double round1(double value, int scale) {
    return Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale);
}

2)

public static float round2(float number, int scale) {
    int pow = 10;
    for (int i = 1; i < scale; i++)
        pow *= 10;
    float tmp = number * pow;
    return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}

3)

public static float round3(float d, int decimalPlace) {
    return BigDecimal.valueOf(d).setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).floatValue();
}



Number is 0.23453f
We'll test 100,000 iterations each method.

Results:
Time 1 - 18 ms
Time 2 - 1 ms
Time 3 - 378 ms


Tested on laptop
Intel i3-3310M CPU 2.4GHz

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

Is it worth using Python's re.compile?

As an alternative answer, as I see that it hasn't been mentioned before, I'll go ahead and quote the Python 3 docs:

Should you use these module-level functions, or should you get the pattern and call its methods yourself? If you’re accessing a regex within a loop, pre-compiling it will save a few function calls. Outside of loops, there’s not much difference thanks to the internal cache.

Spring Boot - Loading Initial Data

You can use the below code. In the following code a database insertion occurs during the startup of the spring boot application.

@SpringBootApplication
public class Application implements CommandLineRunner {
    
    @Autowired
    private IService<Car> service;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        for(int i=1; i<=1000; i++) {
            Car car = new Car();
            car.setName("Car Name "+i);
            book.setPrice(50 + i);
            service.saveOrUpdate(car);
        }
    }

}

Find the closest ancestor element that has a specific class

Use element.closest()

https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

See this example DOM:

<article>
  <div id="div-01">Here is div-01
    <div id="div-02">Here is div-02
      <div id="div-03">Here is div-03</div>
    </div>
  </div>
</article>

This is how you would use element.closest:

var el = document.getElementById('div-03');

var r1 = el.closest("#div-02");  
// returns the element with the id=div-02

var r2 = el.closest("div div");  
// returns the closest ancestor which is a div in div, here is div-03 itself

var r3 = el.closest("article > div");  
// returns the closest ancestor which is a div and has a parent article, here is div-01

var r4 = el.closest(":not(div)");
// returns the closest ancestor which is not a div, here is the outmost article

Paging UICollectionView by cells, not screen

Approach 1: Collection View

flowLayout is UICollectionViewFlowLayout property

override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    if let collectionView = collectionView {

        targetContentOffset.memory = scrollView.contentOffset
        let pageWidth = CGRectGetWidth(scrollView.frame) + flowLayout.minimumInteritemSpacing

        var assistanceOffset : CGFloat = pageWidth / 3.0

        if velocity.x < 0 {
            assistanceOffset = -assistanceOffset
        }

        let assistedScrollPosition = (scrollView.contentOffset.x + assistanceOffset) / pageWidth

        var targetIndex = Int(round(assistedScrollPosition))


        if targetIndex < 0 {
            targetIndex = 0
        }
        else if targetIndex >= collectionView.numberOfItemsInSection(0) {
            targetIndex = collectionView.numberOfItemsInSection(0) - 1
        }

        print("targetIndex = \(targetIndex)")

        let indexPath = NSIndexPath(forItem: targetIndex, inSection: 0)

        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
}

Approach 2: Page View Controller

You could use UIPageViewController if it meets your requirements, each page would have a separate view controller.

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

calling server side event from html button control

The easiest way to accomplish this is to override the RaisePostBackEvent method.

<input type="button" ID="btnRaisePostBack" runat="server" onclick="raisePostBack();" ... />

And in your JavaScript:

raisePostBack = function(){
    __doPostBack("<%=btnRaisePostBack.ClientID%>", "");
}

And in your code:

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
    //call the RaisePostBack event 
    base.RaisePostBackEvent(source, eventArgument);

    if (source == btnRaisePostBack)
    {
         //do some logic
    }
}

Uncompress tar.gz file

Use -C option of tar:

tar zxvf <yourfile>.tar.gz -C /usr/src/

and then, the content of the tar should be in:

/usr/src/<yourfile>

How to open a page in a new window or tab from code-behind

Use:

Target= "_blank" property of anchor tag

jQuery UI DatePicker to show month year only

I know it's a little late response, but I got the same problem a couple of days before and I have came with a nice & smooth solution. First I found this great date picker here

Then I've just updated the CSS class (jquery.calendarPicker.css) that comes with the example like this:

.calMonth {
  /*border-bottom: 1px dashed #666;
  padding-bottom: 5px;
  margin-bottom: 5px;*/
}

.calDay 
{
    display:none;
}

The plugin fires an event DateChanged when you change anything, so it doesn't matter that you are not clicking on a day (and it fits nice as a year and month picker)

Hope it helps!

What does jQuery.fn mean?

fn literally refers to the jquery prototype.

This line of code is in the source code:

jQuery.fn = jQuery.prototype = {
 //list of functions available to the jQuery api
}

But the real tool behind fn is its availability to hook your own functionality into jQuery. Remember that jquery will be the parent scope to your function, so this will refer to the jquery object.

$.fn.myExtension = function(){
 var currentjQueryObject = this;
 //work with currentObject
 return this;//you can include this if you would like to support chaining
};

So here is a simple example of that. Lets say I want to make two extensions, one which puts a blue border, and which colors the text blue, and I want them chained.

jsFiddle Demo

$.fn.blueBorder = function(){
 this.each(function(){
  $(this).css("border","solid blue 2px");
 });
 return this;
};
$.fn.blueText = function(){
 this.each(function(){
  $(this).css("color","blue");
 });
 return this;
};

Now you can use those against a class like this:

$('.blue').blueBorder().blueText();

(I know this is best done with css such as applying different class names, but please keep in mind this is just a demo to show the concept)

This answer has a good example of a full fledged extension.

Getting error "The package appears to be corrupt" while installing apk file

This is weird. I don't know why this was happening with me while generating signed apk but below steps worked for me.

  1. Go to file and select invalidate caches/restarts
  2. After that go to build select clean project
  3. And then select Rebuild project

That's it.

jQuery check if <input> exists and has a value

You could do:

if($('.input1').length && $('.input1').val().length)

length evaluates to false in a condition, when the value is 0.

BackgroundWorker vs background Thread

I want to point out one behavior of BackgroundWorker class that wasn't mentioned yet. You can make a normal Thread to run in background by setting the Thread.IsBackground property.

Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. [1]

You can test this behavoir by calling the following method in the constructor of your form window.

void TestBackgroundThread()
{
    var thread = new Thread((ThreadStart)delegate()
    {
        long count = 0;
        while (true)
        {
            count++;
            Debug.WriteLine("Thread loop count: " + count);
        }
    });

    // Choose one option:
    thread.IsBackground = true; // <--- This will make the thread run in background
    thread.IsBackground = false; // <--- This will delay program termination

    thread.Start();
}

When the IsBackground property is set to true and you close the window, then your application will terminate normaly.

But when the IsBackground property is set to false (by default) and you close the window, then just the window will disapear but the process will still keep running.

The BackgroundWorker class utilize a Thread that runs in the background.

error C4996: 'scanf': This function or variable may be unsafe in c programming

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS

How to take the nth digit of a number in python

You can do it with integer division and remainder methods

def get_digit(number, n):
    return number // 10**n % 10

get_digit(987654321, 0)
# 1

get_digit(987654321, 5)
# 6

The // performs integer division by a power of ten to move the digit to the ones position, then the % gets the remainder after division by 10. Note that the numbering in this scheme uses zero-indexing and starts from the right side of the number.

Where can I download Eclipse Android bundle?

Try www.eclipse.org/downloads/packages/eclipse-android-developers-includes-incubating-components/neonrc3

Add to integers in a list

You can append to the end of a list:

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]

You can edit items in the list like this:

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]

Insert integers into the middle of a list:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]

How to create Gmail filter searching for text only at start of subject line?

The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.

How do I convert NSInteger to NSString datatype?

Modern Objective-C

An NSInteger has the method stringValue that can be used even with a literal

NSString *integerAsString1 = [@12 stringValue];

NSInteger number = 13;
NSString *integerAsString2 = [@(number) stringValue];

Very simple. Isn't it?

Swift

var integerAsString = String(integer)

What is a mutex?

When you have a multi-threaded application, the different threads sometimes share a common resource, such as a variable or similar. This shared source often cannot be accessed at the same time, so a construct is needed to ensure that only one thread is using that resource at a time.

The concept is called "mutual exclusion" (short Mutex), and is a way to ensure that only one thread is allowed inside that area, using that resource etc.

How to use them is language specific, but is often (if not always) based on a operating system mutex.

Some languages doesn't need this construct, due to the paradigm, for example functional programming (Haskell, ML are good examples).

Javascript Image Resize

okay it solved, here is my final code

if($(this).width() > $(this).height()) { 
 $(this).css('width',MaxPreviewDimension+'px');
 $(this).css('height','auto');
} else {
 $(this).css('height',MaxPreviewDimension+'px');
 $(this).css('width','auto');
}

Thanks guys

what is numeric(18, 0) in sql server 2008 r2

The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place. If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.

And to answer, "can I add (-10) in that column?" - Yes, you can.

How do I write a custom init for a UIView subclass in Swift?

The init(frame:) version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init?(coder:) version will be called. Since Swift now requires an implementation of the required init?(coder:), I have updated the example below and changed the let variable declarations to var and optional. In this case, you would initialize them in awakeFromNib() or at some later time.

class TestView : UIView {
    var s: String?
    var i: Int?
    init(s: String, i: Int) {
        self.s = s
        self.i = i
        super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

Post order traversal of binary tree without recursion

Python with 1 stack and no flag:

def postorderTraversal(self, root):
    ret = []
    if not root:
        return ret
    stack = [root]
    current = None
    while stack:
        previous = current
        current = stack.pop()
        if previous and ((previous is current) or (previous is current.left) or (previous is current.right)):
            ret.append(current.val)
        else:
            stack.append(current)
            if current.right:
                stack.append(current.right)
            if current.left:
                stack.append(current.left)

    return ret

And what is better is with similar statements, in order traversal works too

def inorderTraversal(self, root):
    ret = []
    if not root:
        return ret
    stack = [root]
    current = None
    while stack:
        previous = current
        current = stack.pop()
        if None == previous or previous.left is current or previous.right is current:
            if current.right:
                stack.append(current.right)
            stack.append(current)
            if current.left:
                stack.append(current.left)
        else:
            ret.append(current.val)

    return ret

AngularJS : How to watch service variables?

In a scenario like this, where multiple/unkown objects might be interested in changes, use $rootScope.$broadcast from the item being changed.

Rather than creating your own registry of listeners (which have to be cleaned up on various $destroys), you should be able to $broadcast from the service in question.

You must still code the $on handlers in each listener but the pattern is decoupled from multiple calls to $digest and thus avoids the risk of long-running watchers.

This way, also, listeners can come and go from the DOM and/or different child scopes without the service changing its behavior.

** update: examples **

Broadcasts would make the most sense in "global" services that could impact countless other things in your app. A good example is a User service where there are a number of events that could take place such as login, logout, update, idle, etc. I believe this is where broadcasts make the most sense because any scope can listen for an event, without even injecting the service, and it doesn't need to evaluate any expressions or cache results to inspect for changes. It just fires and forgets (so make sure it's a fire-and-forget notification, not something that requires action)

.factory('UserService', [ '$rootScope', function($rootScope) {
   var service = <whatever you do for the object>

   service.save = function(data) {
     .. validate data and update model ..
     // notify listeners and provide the data that changed [optional]
     $rootScope.$broadcast('user:updated',data);
   }

   // alternatively, create a callback function and $broadcast from there if making an ajax call

   return service;
}]);

The service above would broadcast a message to every scope when the save() function completed and the data was valid. Alternatively, if it's a $resource or an ajax submission, move the broadcast call into the callback so it fires when the server has responded. Broadcasts suit that pattern particularly well because every listener just waits for the event without the need to inspect the scope on every single $digest. The listener would look like:

.controller('UserCtrl', [ 'UserService', '$scope', function(UserService, $scope) {

  var user = UserService.getUser();

  // if you don't want to expose the actual object in your scope you could expose just the values, or derive a value for your purposes
   $scope.name = user.firstname + ' ' +user.lastname;

   $scope.$on('user:updated', function(event,data) {
     // you could inspect the data to see if what you care about changed, or just update your own scope
     $scope.name = user.firstname + ' ' + user.lastname;
   });

   // different event names let you group your code and logic by what happened
   $scope.$on('user:logout', function(event,data) {
     .. do something differently entirely ..
   });

 }]);

One of the benefits of this is the elimination of multiple watches. If you were combining fields or deriving values like the example above, you'd have to watch both the firstname and lastname properties. Watching the getUser() function would only work if the user object was replaced on updates, it would not fire if the user object merely had its properties updated. In which case you'd have to do a deep watch and that is more intensive.

$broadcast sends the message from the scope it's called on down into any child scopes. So calling it from $rootScope will fire on every scope. If you were to $broadcast from your controller's scope, for example, it would fire only in the scopes that inherit from your controller scope. $emit goes the opposite direction and behaves similarly to a DOM event in that it bubbles up the scope chain.

Keep in mind that there are scenarios where $broadcast makes a lot of sense, and there are scenarios where $watch is a better option - especially if in an isolate scope with a very specific watch expression.

How can I convert byte size into a human-readable format in Java?

Create an interface:

public interface IUnits {
    public String format(long size, String pattern);
    public long getUnitSize();
}

Create the StorageUnits class:

import java.text.DecimalFormat;

public class StorageUnits {

    private static final long K = 1024;
    private static final long M = K * K;
    private static final long G = M * K;
    private static final long T = G * K;

    enum Unit implements IUnits {

        TERA_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "TB", pattern);
            }
            @Override
            public long getUnitSize() {
                return T;
            }
            @Override
            public String toString() {
                return "Terabytes";
            }
        },
        GIGA_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "GB", pattern);
            }
            @Override
            public long getUnitSize() {
                return G;
            }
            @Override
            public String toString() {
                return "Gigabytes";
            }
        },
        MEGA_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "MB", pattern);
            }
            @Override
            public long getUnitSize() {
                return M;
            }
            @Override
            public String toString() {
                return "Megabytes";
            }
        },
        KILO_BYTE {
            @Override
            public String format(long size, String pattern) {
                return format(size, getUnitSize(), "kB", pattern);
            }
            @Override
            public long getUnitSize() {
                return K;
            }
            @Override
            public String toString() {
                return "Kilobytes";
            }

        };

        String format(long size, long base, String unit, String pattern) {
            return new DecimalFormat(pattern).format(
                           Long.valueOf(size).doubleValue() /
                           Long.valueOf(base).doubleValue()
            ) + unit;
        }
    }

    public static String format(long size, String pattern) {
        for(Unit unit : Unit.values()) {
            if(size >= unit.getUnitSize()) {
                return unit.format(size, pattern);
            }
        }
        return ("???(" + size + ")???");
    }

    public static String format(long size) {
        return format(size, "#,##0.#");
    }
}

Call it:

class Main {
    public static void main(String... args) {
        System.out.println(StorageUnits.format(21885));
        System.out.println(StorageUnits.format(2188121545L));
    }
}

Output:

21.4kB
2GB

How to handle onchange event on input type=file in jQuery?

This jsfiddle works fine for me.

$(document).delegate(':file', 'change', function() {
    console.log(this);
});

Note: .delegate() is the fastest event-binding method for jQuery < 1.7: event-binding methods

Create a Date with a set timezone without using a string representation

Simply Set the Time Zone and Get Back According

new Date().toLocaleString("en-US", {timeZone: "America/New_York"})

Other Time-zones are as Following

var world_timezones =
[
    'Europe/Andorra',
    'Asia/Dubai',
    'Asia/Kabul',
    'Europe/Tirane',
    'Asia/Yerevan',
    'Antarctica/Casey',
    'Antarctica/Davis',
    'Antarctica/DumontDUrville', 
    'Antarctica/Mawson',
    'Antarctica/Palmer',
    'Antarctica/Rothera',
    'Antarctica/Syowa',
    'Antarctica/Troll',
    'Antarctica/Vostok',
    'America/Argentina/Buenos_Aires',
    'America/Argentina/Cordoba',
    'America/Argentina/Salta',
    'America/Argentina/Jujuy',
    'America/Argentina/Tucuman',
    'America/Argentina/Catamarca',
    'America/Argentina/La_Rioja',
    'America/Argentina/San_Juan',
    'America/Argentina/Mendoza',
    'America/Argentina/San_Luis',
    'America/Argentina/Rio_Gallegos',
    'America/Argentina/Ushuaia',
    'Pacific/Pago_Pago',
    'Europe/Vienna',
    'Australia/Lord_Howe',
    'Antarctica/Macquarie',
    'Australia/Hobart',
    'Australia/Currie',
    'Australia/Melbourne',
    'Australia/Sydney',
    'Australia/Broken_Hill',
    'Australia/Brisbane',
    'Australia/Lindeman',
    'Australia/Adelaide',
    'Australia/Darwin',
    'Australia/Perth',
    'Australia/Eucla',
    'Asia/Baku',
    'America/Barbados',
    'Asia/Dhaka',
    'Europe/Brussels',
    'Europe/Sofia',
    'Atlantic/Bermuda',
    'Asia/Brunei',
    'America/La_Paz',
    'America/Noronha',
    'America/Belem',
    'America/Fortaleza',
    'America/Recife',
    'America/Araguaina',
    'America/Maceio',
    'America/Bahia',
    'America/Sao_Paulo',
    'America/Campo_Grande',
    'America/Cuiaba',
    'America/Santarem',
    'America/Porto_Velho',
    'America/Boa_Vista',
    'America/Manaus',
    'America/Eirunepe',
    'America/Rio_Branco',
    'America/Nassau',
    'Asia/Thimphu',
    'Europe/Minsk',
    'America/Belize',
    'America/St_Johns',
    'America/Halifax',
    'America/Glace_Bay',
    'America/Moncton',
    'America/Goose_Bay',
    'America/Blanc-Sablon',
    'America/Toronto',
    'America/Nipigon',
    'America/Thunder_Bay',
    'America/Iqaluit',
    'America/Pangnirtung',
    'America/Atikokan',
    'America/Winnipeg',
    'America/Rainy_River',
    'America/Resolute',
    'America/Rankin_Inlet',
    'America/Regina',
    'America/Swift_Current',
    'America/Edmonton',
    'America/Cambridge_Bay',
    'America/Yellowknife',
    'America/Inuvik',
    'America/Creston',
    'America/Dawson_Creek',
    'America/Fort_Nelson',
    'America/Vancouver',
    'America/Whitehorse',
    'America/Dawson',
    'Indian/Cocos',
    'Europe/Zurich',
    'Africa/Abidjan',
    'Pacific/Rarotonga',
    'America/Santiago',
    'America/Punta_Arenas',
    'Pacific/Easter',
    'Asia/Shanghai',
    'Asia/Urumqi',
    'America/Bogota',
    'America/Costa_Rica',
    'America/Havana',
    'Atlantic/Cape_Verde',
    'America/Curacao',
    'Indian/Christmas',
    'Asia/Nicosia',
    'Asia/Famagusta',
    'Europe/Prague',
    'Europe/Berlin',
    'Europe/Copenhagen',
    'America/Santo_Domingo',
    'Africa/Algiers',
    'America/Guayaquil',
    'Pacific/Galapagos',
    'Europe/Tallinn',
    'Africa/Cairo',
    'Africa/El_Aaiun',
    'Europe/Madrid',
    'Africa/Ceuta',
    'Atlantic/Canary',
    'Europe/Helsinki',
    'Pacific/Fiji',
    'Atlantic/Stanley',
    'Pacific/Chuuk',
    'Pacific/Pohnpei',
    'Pacific/Kosrae',
    'Atlantic/Faroe',
    'Europe/Paris',
    'Europe/London',
    'Asia/Tbilisi',
    'America/Cayenne',
    'Africa/Accra',
    'Europe/Gibraltar',
    'America/Godthab',
    'America/Danmarkshavn',
    'America/Scoresbysund',
    'America/Thule',
    'Europe/Athens',
    'Atlantic/South_Georgia',
    'America/Guatemala',
    'Pacific/Guam',
    'Africa/Bissau',
    'America/Guyana',
    'Asia/Hong_Kong',
    'America/Tegucigalpa',
    'America/Port-au-Prince',
    'Europe/Budapest',
    'Asia/Jakarta',
    'Asia/Pontianak',
    'Asia/Makassar',
    'Asia/Jayapura',
    'Europe/Dublin',
    'Asia/Jerusalem',
    'Asia/Kolkata',
    'Indian/Chagos',
    'Asia/Baghdad',
    'Asia/Tehran',
    'Atlantic/Reykjavik',
    'Europe/Rome',
    'America/Jamaica',
    'Asia/Amman',
    'Asia/Tokyo',
    'Africa/Nairobi',
    'Asia/Bishkek',
    'Pacific/Tarawa',
    'Pacific/Enderbury',
    'Pacific/Kiritimati',
    'Asia/Pyongyang',
    'Asia/Seoul',
    'Asia/Almaty',
    'Asia/Qyzylorda',
    'Asia/Qostanay', 
    'Asia/Aqtobe',
    'Asia/Aqtau',
    'Asia/Atyrau',
    'Asia/Oral',
    'Asia/Beirut',
    'Asia/Colombo',
    'Africa/Monrovia',
    'Europe/Vilnius',
    'Europe/Luxembourg',
    'Europe/Riga',
    'Africa/Tripoli',
    'Africa/Casablanca',
    'Europe/Monaco',
    'Europe/Chisinau',
    'Pacific/Majuro',
    'Pacific/Kwajalein',
    'Asia/Yangon',
    'Asia/Ulaanbaatar',
    'Asia/Hovd',
    'Asia/Choibalsan',
    'Asia/Macau',
    'America/Martinique',
    'Europe/Malta',
    'Indian/Mauritius',
    'Indian/Maldives',
    'America/Mexico_City',
    'America/Cancun',
    'America/Merida',
    'America/Monterrey',
    'America/Matamoros',
    'America/Mazatlan',
    'America/Chihuahua',
    'America/Ojinaga',
    'America/Hermosillo',
    'America/Tijuana',
    'America/Bahia_Banderas',
    'Asia/Kuala_Lumpur',
    'Asia/Kuching',
    'Africa/Maputo',
    'Africa/Windhoek',
    'Pacific/Noumea',
    'Pacific/Norfolk',
    'Africa/Lagos',
    'America/Managua',
    'Europe/Amsterdam',
    'Europe/Oslo',
    'Asia/Kathmandu',
    'Pacific/Nauru',
    'Pacific/Niue',
    'Pacific/Auckland',
    'Pacific/Chatham',
    'America/Panama',
    'America/Lima',
    'Pacific/Tahiti',
    'Pacific/Marquesas',
    'Pacific/Gambier',
    'Pacific/Port_Moresby',
    'Pacific/Bougainville',
    'Asia/Manila',
    'Asia/Karachi',
    'Europe/Warsaw',
    'America/Miquelon',
    'Pacific/Pitcairn',
    'America/Puerto_Rico',
    'Asia/Gaza',
    'Asia/Hebron',
    'Europe/Lisbon',
    'Atlantic/Madeira',
    'Atlantic/Azores',
    'Pacific/Palau',
    'America/Asuncion',
    'Asia/Qatar',
    'Indian/Reunion',
    'Europe/Bucharest',
    'Europe/Belgrade',
    'Europe/Kaliningrad',
    'Europe/Moscow',
    'Europe/Simferopol',
    'Europe/Kirov',
    'Europe/Astrakhan',
    'Europe/Volgograd',
    'Europe/Saratov',
    'Europe/Ulyanovsk',
    'Europe/Samara',
    'Asia/Yekaterinburg',
    'Asia/Omsk',
    'Asia/Novosibirsk',
    'Asia/Barnaul',
    'Asia/Tomsk',
    'Asia/Novokuznetsk',
    'Asia/Krasnoyarsk',
    'Asia/Irkutsk',
    'Asia/Chita',
    'Asia/Yakutsk',
    'Asia/Khandyga',
    'Asia/Vladivostok',
    'Asia/Ust-Nera',
    'Asia/Magadan',
    'Asia/Sakhalin',
    'Asia/Srednekolymsk',
    'Asia/Kamchatka',
    'Asia/Anadyr',
    'Asia/Riyadh',
    'Pacific/Guadalcanal',
    'Indian/Mahe',
    'Africa/Khartoum',
    'Europe/Stockholm',
    'Asia/Singapore',
    'America/Paramaribo',
    'Africa/Juba',
    'Africa/Sao_Tome',
    'America/El_Salvador',
    'Asia/Damascus',
    'America/Grand_Turk',
    'Africa/Ndjamena',
    'Indian/Kerguelen',
    'Asia/Bangkok',
    'Asia/Dushanbe',
    'Pacific/Fakaofo',
    'Asia/Dili',
    'Asia/Ashgabat',
    'Africa/Tunis',
    'Pacific/Tongatapu',
    'Europe/Istanbul',
    'America/Port_of_Spain',
    'Pacific/Funafuti',
    'Asia/Taipei',
    'Europe/Kiev',
    'Europe/Uzhgorod',
    'Europe/Zaporozhye',
    'Pacific/Wake',
    'America/New_York',
    'America/Detroit',
    'America/Kentucky/Louisville',
    'America/Kentucky/Monticello',
    'America/Indiana/Indianapolis',
    'America/Indiana/Vincennes',
    'America/Indiana/Winamac',
    'America/Indiana/Marengo',
    'America/Indiana/Petersburg',
    'America/Indiana/Vevay',
    'America/Chicago',
    'America/Indiana/Tell_City',
    'America/Indiana/Knox',
    'America/Menominee',
    'America/North_Dakota/Center',
    'America/North_Dakota/New_Salem',
    'America/North_Dakota/Beulah',
    'America/Denver',
    'America/Boise',
    'America/Phoenix',
    'America/Los_Angeles',
    'America/Anchorage',
    'America/Juneau',
    'America/Sitka',
    'America/Metlakatla',
    'America/Yakutat',
    'America/Nome',
    'America/Adak',
    'Pacific/Honolulu',
    'America/Montevideo',
    'Asia/Samarkand',
    'Asia/Tashkent',
    'America/Caracas',
    'Asia/Ho_Chi_Minh',
    'Pacific/Efate',
    'Pacific/Wallis',
    'Pacific/Apia',
    'Africa/Johannesburg'
];

Regex how to match an optional character

You have to mark the single letter as optional too:

([A-Z]{1})? +.*? +

or make the whole part optional

(([A-Z]{1}) +.*? +)?

Convert a positive number to negative in C#

Maybe this?

int n;

.... some coding....

n = n<=0? n:0-n;

How can I get the last 7 characters of a PHP string?

Use substr() with a negative number for the 2nd argument.

$newstring = substr($dynamicstring, -7);

From the php docs:

string substr ( string $string , int $start [, int $length ] )

If start is negative, the returned string will start at the start'th character from the end of string.

jQuery: Wait/Delay 1 second without executing code

Javascript is an asynchronous programming language so you can't stop the execution for a of time; the only way you can [pseudo]stop an execution is using setTimeout() that is not a delay but a "delayed function callback".

How to bind Close command to a button

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

public class MyCommands
{
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

How to check undefined in Typescript

It actually is working, but there is difference between null and undefined. You are actually assigning to uemail, which would return a value or null in case it does not exists. As per documentation.

For more information about the difference between the both of them, see this answer.

For a solution to this Garfty's answer may work, depending on what your requirement is. You may also want to have a look here.

null terminating a string

From the comp.lang.c FAQ: http://c-faq.com/null/varieties.html

In essence: NULL (the preprocessor macro for the null pointer) is not the same as NUL (the null character).

Serializing and submitting a form with jQuery and PHP

You can add extra data with form data

use serializeArray and add the additional data:

var data = $('#myForm').serializeArray();
    data.push({name: 'tienn2t', value: 'love'});
    $.ajax({
      type: "POST",
      url: "your url.php",
      data: data,
      dataType: "json",
      success: function(data) {
          //var obj = jQuery.parseJSON(data); if the dataType is not     specified as json uncomment this
        // do what ever you want with the server response
     },
    error: function() {
        alert('error handing here');
    }
});

Correct way to handle conditional styling in React

The best way to handle styling is by using classes with set of css properties.

example:

<Component className={this.getColor()} />

getColor() {
    let class = "badge m2";
    class += this.state.count===0 ? "warning" : danger;
    return class;
}

How to compare objects by multiple fields

If there are multiple ways a user might order person, you could also have multiple Comparators setup as constants somewhere. Most of the sort operations and sorted collections take a comparator as a parameter.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

I would do something like this:

;WITH x 
 AS (SELECT *, 
            Row_number() 
              OVER( 
                partition BY employeeid 
                ORDER BY datestart) rn 
     FROM   employeehistory) 
SELECT * 
FROM   x x1 
   LEFT OUTER JOIN x x2 
                ON x1.rn = x2.rn + 1 

Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.

What is the difference between a pandas Series and a single-column DataFrame?

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. The basic method to create a Series is to call:

s = pd.Series(data, index=index)

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.

 d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
 two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
 df = pd.DataFrame(d)

How to convert numbers between hexadecimal and decimal

My solution is a bit like back to basics, but it works without using any built-in functions to convert between number systems.

    public static string DecToHex(long a)
    {
        int n = 1;
        long b = a;
        while (b > 15)
        {
            b /= 16;
            n++;
        }
        string[] t = new string[n];
        int i = 0, j = n - 1;
        do
        {
                 if (a % 16 == 10) t[i] = "A";
            else if (a % 16 == 11) t[i] = "B";
            else if (a % 16 == 12) t[i] = "C";
            else if (a % 16 == 13) t[i] = "D";
            else if (a % 16 == 14) t[i] = "E";
            else if (a % 16 == 15) t[i] = "F";
            else t[i] = (a % 16).ToString();
            a /= 16;
            i++;
        }
        while ((a * 16) > 15);
        string[] r = new string[n];
        for (i = 0; i < n; i++)
        {
            r[i] = t[j];
            j--;
        }
        string res = string.Concat(r);
        return res;
    }

Differences between C++ string == and compare()?

If you just want to check string equality, use the == operator. Determining whether two strings are equal is simpler than finding an ordering (which is what compare() gives,) so it might be better performance-wise in your case to use the equality operator.

Longer answer: The API provides a method to check for string equality and a method to check string ordering. You want string equality, so use the equality operator (so that your expectations and those of the library implementors align.) If performance is important then you might like to test both methods and find the fastest.

How to beautifully update a JPA entity in Spring Data?

So now assume the Customer wants to change his name in the webui - then there will be some controller action, where there will be the updated DTO with the old ID and the new name.

Normally, you have the following workflow:

  1. User requests his data from server and obtains them in UI;
  2. User corrects his data and sends it back to server with already present ID;
  3. On server you obtain DTO with updated data by user, find it in DB by ID (otherwise throw exception) and transform DTO -> Entity with all given data, foreign keys, etc...
  4. Then you just merge it, or if using Spring Data invoke save(), which in turn will merge it (see this thread);

P.S. This operation will inevitably issue 2 queries: select and update. Again, 2 queries, even if you wanna update a single field. However, if you utilize Hibernate's proprietary @DynamicUpdate annotation on top of entity class, it will help you not to include into update statement all the fields, but only those that actually changed.

P.S. If you do not wanna pay for first select statement and prefer to use Spring Data's @Modifying query, be prepared to lose L2C cache region related to modifiable entity; even worse situation with native update queries (see this thread) and also of course be prepared to write those queries manually, test them and support them in the future.

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

this worked:

    Date date = null;
    String dateStr = rs.getString("doc_date");
    if (dateStr != null) {
        date = dateFormat.parse(dateStr);
    }

using SimpleDateFormat.

Why is Thread.Sleep so harmful

For those of you who hasn't seen one valid argument against use of Thread.Sleep in SCENARIO 2, there really is one - application exit be held up by the while loop (SCENARIO 1/3 is just plain stupid so not worthy of more mentioning)

Many who pretend to be in-the-know, screaming Thread.Sleep is evil failed to mentioned a single valid reason for those of us who demanded a practical reason not to use it - but here it is, thanks to Pete - Thread.Sleep is Evil (can be easily avoided with a timer/handler)

    static void Main(string[] args)
    {
        Thread t = new Thread(new ThreadStart(ThreadFunc));
        t.Start();

        Console.WriteLine("Hit any key to exit.");
        Console.ReadLine();

        Console.WriteLine("App exiting");
        return;
    }

    static void ThreadFunc()
    {
        int i=0;
        try
        {
            while (true)
            {
                Console.WriteLine(Thread.CurrentThread.ThreadState.ToString() + " " + i);

                Thread.Sleep(1000 * 10);
                i++;
            }
        }
        finally
        {
            Console.WriteLine("Exiting while loop");
        }
        return;
    }

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

"Untrusted App Developer" message when installing enterprise iOS Application

In my case, i just change some step below with iOS 9.3 To solve this problem:

Settings -> General -> Device Management -> Developer app Choose your current developer account name. Taps Trust "Your developer account name" Taps "Trust" in pop up. Done

How to delete all rows from all tables in a SQL Server database?

--Load tables to delete from
SELECT 
DISTINCT
' Delete top 1000000 from <DBName>.<schema>.' + c.TABLE_NAME + ' WHERE <Filter Clause Here>' AS query,c.TABLE_NAME AS TableName, IsDeleted=0, '<InsertSomeDescriptorHere>' AS [Source]--,t.TABLE_TYPE, c.*
            INTO dbo.AllTablesToDeleteFrom
            FROM INFORMATION_SCHEMA.TABLES AS t
            INNER JOIN information_schema.columns c ON c.TABLE_NAME = t.TABLE_NAME 
    WHERE c.COLUMN_NAME = '<column name>'
           AND c.TABLE_SCHEMA = 'dbo'
           AND c.TABLE_CATALOG = '<DB Name here>'
           AND t.TABLE_TYPE='Base table'
           --AND t.TABLE_NAME LIKE '<put filter here>'

            DECLARE @TableSelect NVARCHAR(1000)= '';
            DECLARE @Table NVARCHAR(1000)= '';
            DECLARE @IsDeleted INT= 0;
            DECLARE @NumRows INT = 1000000;
            DECLARE @Source NVARCHAR(50)='';


            WHILE ( @IsDeleted = 0 )
                BEGIN
                --This grabs one table at a time to be deleted from. @TableSelect has the sql to execute. it is important to order by IsDeleted ASC
                --because it will pull tables to delete from by those that have a 0=IsDeleted first. Once the loop grabs a table with IsDeleted=1 then this will pop out of loop

                    SELECT TOP 1
                            @TableSelect = query,
                            @IsDeleted = IsDeleted,
                            @Table = TableName,
                            @Source=[a].[Source]
                    FROM    dbo.AllTablesToDeleteFrom a
                    WHERE a.[Source]='SomeDescriptorHere'--use only if needed
                    ORDER BY a.IsDeleted ASC;--this is required because only those records returned with IsDeleted=0 will run through loop

                    --SELECT  @Table; can add this in to  monitor what table is being deleted from

                    WHILE ( @NumRows = 1000000 )--only delete a million rows at a time?

                    BEGIN 
                    EXEC sp_executesql @TableSelect;
                    SET @NumRows = @@ROWCOUNT;
                    --IF @NumRows = 1000000 --can do something here if needed
                    --One wants this loop to continue as long as a million rows is deleted. Once < 1 million rows is deleted it pops out of loop
                    --and grabs next table to delete
                    --    BEGIN
                    --SELECT  @NumRows;--can add this in to see current number of deleted records for table
                            INSERT  INTO dbo.DeleteFromAllTables
                                    ( tableName,
                                      query,
                                      cnt,
                                      [Source]
                                    )
                            SELECT  @Table,
                                    @TableSelect,
                                    @NumRows,
                                    @Source;
                     --   END; 
                END; 



SET @NumRows = 1000000;

UPDATE  a
SET     a.IsDeleted = 1
FROM    dbo.AllTablesToDeleteFrom a
WHERE   a.TableName = @Table;
--flag this as deleted so you can move on to the next table to delete from

END; 

What is the HTML5 equivalent to the align attribute in table cells?

You can use inline css :
<td style = "text-align: center;">

Why is sed not recognizing \t as a tab?

I used this on Mac:

sed -i '' $'$i\\\n\\\thello\n' filename

Used this link for reference

No module named 'pymysql'

I tried installing pymysql on command prompt by typing

pip install pymysql

But it still dont work on my case, so I decided to try using the terminal IDE and it works.

Python 3 string.join() equivalent?

There are method join for string objects:

".".join(("a","b","c"))

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

both would work the same, its just two different methods to call the same function. Try the following:

<a href="javascript:history.back();">[Go Back]</a>

LINQ Contains Case Insensitive

Use String.Equals Method

public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
    return this.ObjectContext.FACILITY_ITEM
           .Where(fi => fi.DESCRIPTION
           .Equals(description, StringComparison.OrdinalIgnoreCase));
}

Why is there no xrange function in Python3?

Python3's range is Python2's xrange. There's no need to wrap an iter around it. To get an actual list in Python3, you need to use list(range(...))

If you want something that works with Python2 and Python3, try this

try:
    xrange
except NameError:
    xrange = range

Bash script prints "Command Not Found" on empty lines

If the script does its job (relatively) well, then it's running okay. Your problem is probably a single line in the file referencing a program that's either not on the path, not installed, misspelled, or something similar.

One way is to place a set -x at the top of your script or run it with bash -x instead of just bash - this will output the lines before executing them and you usually just need to look at the command output immediately before the error to see what's causing the problem

If, as you say, it's the blank lines causing the problems, you might want to check what's actaully in them. Run:

od -xcb testscript.sh

and make sure there's no "invisible" funny characters like the CTRL-M (carriage return) you may get by using a Windows-type editor.

Is Laravel really this slow?

I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync. I tried both cygwin and minGW. It seems like rsync is incompatible with git for windows's version of ssh.

Here is what worked for me: NFS.

Vagrant docs says:

NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.

This isn't true anymore. We can use vagrant-winnfsd plugin nowadays. It's really simple to install:

  1. Execute vagrant plugin install vagrant-winnfsd
  2. Change in your Vagrantfile: config.vm.synced_folder ".", "/vagrant", type: "nfs"
  3. Add to Vagrantfile: config.vm.network "private_network", type: "dhcp"

That's all I needed to make NFS work. Laravel response time decreased from 500ms to 100ms for me.

Calculate correlation for more than two variables?

If you would like to combine the matrix with some visualisations I can recommend (I am using the built in iris dataset):

library(psych)
pairs.panels(iris[1:4])  # select columns 1-4

enter image description here

The Performance Analytics basically does the same but includes significance indicators by default.

library(PerformanceAnalytics)
chart.Correlation(iris[1:4])

Correlation Chart

Or this nice and simple visualisation:

library(corrplot)
x <- cor(iris[1:4])
corrplot(x, type="upper", order="hclust")

corrplot

How to delete multiple rows in SQL where id = (x to y)

Please try this:

DELETE FROM `table` WHERE id >=163 and id<= 265

Read file from resources folder in Spring Boot

For me, the bug had two fixes.

  1. Xml file which was named as SAMPLE.XML which was causing even the below solution to fail when deployed to aws ec2. The fix was to rename it to new_sample.xml and apply the solution given below.
  2. Solution approach https://medium.com/@jonathan.henrique.smtp/reading-files-in-resource-path-from-jar-artifact-459ce00d2130

I was using Spring boot as jar and deployed to aws ec2 Java variant of the solution is as below :

package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;


public class XmlReader {

    private static Logger LOGGER = LoggerFactory.getLogger(XmlReader.class);

  public static void main(String[] args) {


      String fileLocation = "classpath:cbs_response.xml";
      String reponseXML = null;
      try (ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext()){

        Resource resource = appContext.getResource(fileLocation);
        if (resource.isReadable()) {
          BufferedReader reader =
              new BufferedReader(new InputStreamReader(resource.getInputStream()));
          Stream<String> lines = reader.lines();
          reponseXML = lines.collect(Collectors.joining("\n"));

        }      
      } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
      }
  }
}

Find something in column A then show the value of B for that row in Excel 2010

I figured out such data design:

Main sheet: Column A: Pump codes (numbers)

Column B: formula showing a corresponding row in sheet 'Ruhrpumpen'

=ROW(Pump_codes)+MATCH(A2;Ruhrpumpen!$I$5:$I$100;0)

Formulae have ";" instead of ",", it should be also German notation. If not, pleace replace.

Column C: formula showing data in 'Ruhrpumpen' column A from a row found by formula in col B

=INDIRECT("Ruhrpumpen!A"&$B2)

Column D: formula showing data in 'Ruhrpumpen' column B from a row found by formula in col B:

=INDIRECT("Ruhrpumpen!B"&$B2)

Sheet 'Ruhrpumpen':

Column A: some data about a certain pump

Column B: some more data

Column I: pump codes. Beginning of the list includes defined name 'Pump_codes' used by the formula in column B of the main sheet.

Spreadsheet example: http://www.bumpclub.ee/~jyri_r/Excel/Data_from_other_sheet_by_code_row.xls

Connect to network drive with user name and password

The best way to do this is to p/invoke WNetUseConnection.

[StructLayout(LayoutKind.Sequential)] 
private class NETRESOURCE
{ 
        public int dwScope = 0;
        public int dwType = 0;
        public int dwDisplayType = 0;
        public int dwUsage = 0;
        public string lpLocalName = "";
        public string lpRemoteName = "";
        public string lpComment = "";
        public string lpProvider = "";
}


[DllImport("Mpr.dll")] 
private static extern int WNetUseConnection(
            IntPtr hwndOwner,
            NETRESOURCE lpNetResource,
            string lpPassword,
            string lpUserID,
            int dwFlags,
            string lpAccessName,
            string lpBufferSize,
            string lpResult
        );

Example code here.

Node Express sending image files as API response

a proper solution with streams and error handling is below:

const fs = require('fs')
const stream = require('stream')

app.get('/report/:chart_id/:user_id',(req, res) => {
  const r = fs.createReadStream('path to file') // or any other way to get a readable stream
  const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
  stream.pipeline(
   r,
   ps, // <---- this makes a trick with stream error handling
   (err) => {
    if (err) {
      console.log(err) // No such file or any other kind of error
      return res.sendStatus(400); 
    }
  })
  ps.pipe(res) // <---- this makes a trick with stream error handling
})

with Node older then 10 you will need to use pump instead of pipeline.

How to use Monitor (DDMS) tool to debug application

1 use eclipse bar to install a Mat plug-in to analyze, is a good choice. Studio Memory provides the Monitor 2.Android studio to display the memory occupancy of the application in real time.

How do I install Python OpenCV through Conda?

You can install OpenCV by running these commands in the Anaconda command prompt:

conda config --add channels conda-forge

conda install libopencv opencv py-opencv

Source:

https://github.com/conda-forge/opencv-feedstock

Editing the git commit message in GitHub

You need to git push -f assuming that nobody has pulled the other commit before. Beware, you're changing history.

In javascript, how do you search an array for a substring match

Here's your expected snippet which gives you the array of all the matched values -

_x000D_
_x000D_
var windowArray = new Array ("item","thing","id-3-text","class");_x000D_
_x000D_
var result = [];_x000D_
windowArray.forEach(val => {_x000D_
  if(val && val.includes('id-')) {_x000D_
    result.push(val);_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

How can I determine browser window size on server side C#

Here's an Ajax, asxh handler and session variables approach:

Handler:

using System;
using System.Web;

public class windowSize : IHttpHandler , System.Web.SessionState.IRequiresSessionState  {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";

        var json = new System.Web.Script.Serialization.JavaScriptSerializer();
        var output = json.Serialize(new { isFirst = context.Session["BrowserWidth"] == null });
        context.Response.Write(output);

        context.Session["BrowserWidth"] =  context.Request.QueryString["Width"]; 
        context.Session["BrowserHeight"] = context.Request.QueryString["Height"];
    }

    public bool IsReusable
    {
        get { throw new NotImplementedException(); }
    }
}

Javascript:

window.onresize = function (event) {
    SetWidthHeight();
}
function SetWidthHeight() {
    var height = $(window).height();
    var width = $(window).width();
    $.ajax({
        url: "windowSize.ashx",
        data: {
            'Height': height,
            'Width': width
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (data) {     
        if (data.isFirst) {
            window.location.reload();
        };
    }).fail(function (xhr) {
        alert("Problem to retrieve browser size.");
    });

}
$(function () {
    SetWidthHeight();
});

On aspx file:

...
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/BrowserWindowSize.js"></script>
...
<asp:Label ID="lblDim" runat="server" Text=""></asp:Label>
...

Code behind:

protected void Page_Load(object sender, EventArgs e)
  {
      if (Session["BrowserWidth"] != null)
      {
          // Do all code here to avoid double execution first time
          // ....
          lblDim.Text = "Width: " + Session["BrowserWidth"] + " Height: " + Session["BrowserHeight"];
      }
  }

Source: https://techbrij.com/browser-height-width-server-responsive-design-asp-net

Execute a PHP script from another PHP script

you can use the backtick notation:

`php file.php`;

You can also put this at the top of the php file to indicate the interpreter:

#!/usr/bin/php

Change it to where you put php. Then give execute permission on the file and you can call the file without specifying php:

`./file.php`

If you want to capture the output of the script:

$output = `./file.php`;
echo $output;

how to check and set max_allowed_packet mysql variable

goto cpanel and login as Main Admin or Super Administrator

  1. find SSH/Shell Access ( you will find under the security tab of cpanel )

  2. now give the username and password of Super Administrator as root or whatyougave

    note: do not give any username, cos, it needs permissions
    
  3. once your into console type

    type ' mysql ' and press enter now you find youself in

    mysql> /* and type here like */

    mysql> set global net_buffer_length=1000000;

    Query OK, 0 rows affected (0.00 sec)

    mysql> set global max_allowed_packet=1000000000;

    Query OK, 0 rows affected (0.00 sec)

Now upload and enjoy!!!

Vertically align text next to an image?

Not sure as to why it doesn't render it on your navigation's browser, but I normally use an snippet like this when trying to display a header with an image and a centered text, hope it helps!

https://output.jsbin.com/jeqorahupo

            <hgroup style="display:block; text-align:center;  vertical-align:middle;  margin:inherit auto; padding:inherit auto; max-height:inherit">

            <header style="background:url('http://lorempixel.com/30/30/') center center no-repeat; background-size:auto; display:inner-block; vertical-align:middle; position:relative; position:absolute; top:inherit; left:inherit; display: -webkit-box; display: -webkit-flex;display: -moz-box;display: -ms-flexbox;display: flex;-webkit-flex-align: center;-ms-flex-align: center;-webkit-align-items: center;align-items: center;">

            <image src="http://lorempixel.com/60/60/" title="Img title" style="opacity:0.35"></img>
                    http://lipsum.org</header>
                    </hgroup>

Execute a shell script in current shell with sudo permission

Even the first answer is absolutely brilliant, you probably want to only run script under sudo.

You have to specify the absolute path like:

sudo /home/user/example.sh
sudo ~/example.sh

(both are working)

THIS WONT WORK!

sudo /bin/sh example.sh
sudo example.sh

It will always return

sudo: bin/sh: command not found
sudo: example.sh: command not found

Sending HTML Code Through JSON

All string data must be UTF-8 encoded.

$out = array(
   'render' => utf8_encode($renderOutput), 
   'text' => utf8_encode($textOutput)
);

$out = json_encode($out);
die($out);

JavaScript function to add X months to a date

addDateMonate : function( pDatum, pAnzahlMonate )
{
    if ( pDatum === undefined )
    {
        return undefined;
    }

    if ( pAnzahlMonate === undefined )
    {
        return pDatum;
    }

    var vv = new Date();

    var jahr = pDatum.getFullYear();
    var monat = pDatum.getMonth() + 1;
    var tag = pDatum.getDate();

    var add_monate_total = Math.abs( Number( pAnzahlMonate ) );

    var add_jahre = Number( Math.floor( add_monate_total / 12.0 ) );
    var add_monate_rest = Number( add_monate_total - ( add_jahre * 12.0 ) );

    if ( Number( pAnzahlMonate ) > 0 )
    {
        jahr += add_jahre;
        monat += add_monate_rest;

        if ( monat > 12 )
        {
            jahr += 1;
            monat -= 12;
        }
    }
    else if ( Number( pAnzahlMonate ) < 0 )
    {
        jahr -= add_jahre;
        monat -= add_monate_rest;

        if ( monat <= 0 )
        {
            jahr = jahr - 1;
            monat = 12 + monat;
        }
    }

    if ( ( Number( monat ) === 2 ) && ( Number( tag ) === 29 ) )
    {
        if ( ( ( Number( jahr ) % 400 ) === 0 ) || ( ( Number( jahr ) % 100 ) > 0 ) && ( ( Number( jahr ) % 4 ) === 0 ) )
        {
            tag = 29;
        }
        else
        {
            tag = 28;
        }
    }

    return new Date( jahr, monat - 1, tag );
}


testAddMonate : function( pDatum , pAnzahlMonate )
{
    var datum_js = fkDatum.getDateAusTTMMJJJJ( pDatum );
    var ergebnis = fkDatum.addDateMonate( datum_js, pAnzahlMonate );

    app.log( "addDateMonate( \"" + pDatum + "\", " + pAnzahlMonate + " ) = \"" + fkDatum.getStringAusDate( ergebnis ) + "\"" );
},


test1 : function()
{
    app.testAddMonate( "15.06.2010",    10 );
    app.testAddMonate( "15.06.2010",   -10 );
    app.testAddMonate( "15.06.2010",    37 );
    app.testAddMonate( "15.06.2010",   -37 );
    app.testAddMonate( "15.06.2010",  1234 );
    app.testAddMonate( "15.06.2010", -1234 );
    app.testAddMonate( "15.06.2010",  5620 );
    app.testAddMonate( "15.06.2010", -5120 );

}

Running a command in a new Mac OS X Terminal window

I call this script trun. I suggest putting it in a directory in your executable path. Make sure it is executable like this:

chmod +x ~/bin/trun

Then you can run commands in a new window by just adding trun before them, like this:

trun tail -f /var/log/system.log

Here's the script. It does some fancy things like pass your arguments, change the title bar, clear the screen to remove shell startup clutter, remove its file when its done. By using a unique file for each new window it can be used to create many windows at the same time.

#!/bin/bash
# make this file executable with chmod +x trun
# create a unique file in /tmp
trun_cmd=`mktemp`
# make it cd back to where we are now
echo "cd `pwd`" >$trun_cmd
# make the title bar contain the command being run
echo 'echo -n -e "\033]0;'$*'\007"' >>$trun_cmd
# clear window
echo clear >>$trun_cmd
# the shell command to execute
echo $* >>$trun_cmd
# make the command remove itself
echo rm $trun_cmd >>$trun_cmd
# make the file executable
chmod +x $trun_cmd

# open it in Terminal to run it in a new Terminal window
open -b com.apple.terminal $trun_cmd

Is there a way to make text unselectable on an HTML page?

For Firefox you can apply the CSS declaration "-moz-user-select" to "none". Check out their documentation, user-select.

It's a "preview" of the future "user-select" as they say, so maybe Opera or WebKit-based browsers will support that. I also recall finding something for Internet Explorer, but I don't remember what :).

Anyway, unless it's a specific situation where text-selecting makes some dynamic functionality fail, you shouldn't really override what users are expecting from a webpage, and that is being able to select any text they want.

How to change color in circular progress bar?

You can use a style for changing the color of progress like below

 <style name="AppTheme.anyName">
        <item name="colorAccent">YOUR_COLOR</item>
    </style>

and use it in the ProgressBar like below

<ProgressBar
            style="?android:attr/progressBarStyle"
            android:theme="@style/AppTheme.WhiteAccent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/dimen_30"
        />

Hope it helps.

Creating columns in listView and add items

You need to set property for the control:

listView1.View = View.Details;

How many parameters are too many?

If you start having to mentally count off the parameters in the signature and match them to the call, then it is time to refactor!

T-SQL split string based on delimiter

Try filtering out the rows that contain strings with the delimiter and work on those only like:

SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
       SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM   MyTable
WHERE CHARINDEX('/', myColumn) > 0

Or

SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
       SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM   MyTable
WHERE myColumn LIKE '%/%'

Determine what user created objects in SQL Server

The answer is "no, you probably can't".

While there is stuff in there that might say who created a given object, there are a lot of "ifs" behind them. A quick (and not necessarily complete) review:

sys.objects (and thus sys.tables, sys.procedures, sys.views, etc.) has column principal_id. This value is a foreign key that relates to the list of database users, which in turn can be joined with the list of SQL (instance) logins. (All of this info can be found in further system views.)

But.

A quick check on our setup here and a cursory review of BOL indicates that this value is only set (i.e. not null) if it is "different from the schema owner". In our development system, and we've got dbo + two other schemas, everything comes up as NULL. This is probably because everyone has dbo rights within these databases.

This is using NT authentication. SQL authentication probably works much the same. Also, does everyone have and use a unique login, or are they shared? If you have employee turnover and domain (or SQL) logins get dropped, once again the data may not be there or may be incomplete.

You can look this data over (select * from sys.objects), but if principal_id is null, you are probably out of luck.

How to make zsh run as a login shell on Mac OS X (in iTerm)?

The command to change the shell at startup is chsh -s <path_to_shell>. The default shells in mac OS X are installed inside the bin directory so if you want to change to the default zsh then you would use the following

chsh -s /bin/zsh

If you're using different version of zsh then you might have to add that version to /etc/shells to avoid the nonstandard shell message. For example if you want home-brew's version of zsh then you have to add /usr/local/bin/zsh to the aforementioned file which you can do in one command sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells" and then run

chsh -s /usr/local/bin/zsh

Or if you want to do the whole thing in one command just copy and paste this if you have zsh already installed

sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells" && chsh -s /usr/local/bin/zsh

Windows equivalent to UNIX pwd

C:\Documents and Settings\Scripter>echo %cd%
C:\Documents and Settings\Scripter

C:\Documents and Settings\Scripter>

for Unix use pwd command

Current working directory

how to stop Javascript forEach?

Array.forEach cannot be broken and using try...catch or hacky methods such as Array.every or Array.some will only make your code harder to understand. There are only two solutions of this problem:

1) use a old for loop: this will be the most compatible solution but can be very hard to read when used often in large blocks of code:

var testArray = ['a', 'b', 'c'];
for (var key = 0; key < testArray.length; key++) {
    var value = testArray[key];
    console.log(key); // This is the key;
    console.log(value); // This is the value;
}

2) use the new ECMA6 (2015 specification) in cases where compatibility is not a problem. Note that even in 2016, only a few browsers and IDEs offer good support for this new specification. While this works for iterable objects (e.g. Arrays), if you want to use this on non-iterable objects, you will need to use the Object.entries method. This method is scarcely available as of June 18th 2016 and even Chrome requires a special flag to enable it: chrome://flags/#enable-javascript-harmony. For Arrays, you won't need all this but compatibility remains a problem:

var testArray = ['a', 'b', 'c'];
for (let [key, value] of testArray.entries()) {
    console.log(key); // This is the key;
    console.log(value); // This is the value;
}

3) A lot of people would agree that neither the first or second option are good candidates. Until option 2 becomes the new standard, most popular libraries such as AngularJS and jQuery offer their own loop methods which can be superior to anything available in JavaScript. Also for those who are not already using these big libraries and that are looking for lightweight options, solutions like this can be used and will almost be on par with ECMA6 while keeping compatibility with older browsers.

Is it possible to simulate key press events programmatically?

The critical part of getting this to work is to realize that charCode, keyCode and which are all deprecated methods. Therefore if the code processing the key press event uses any of these three, then it'll receive a bogus answer (e.g. a default of 0).

As long as you access the key press event with a non-deprecated method, such as key, you should be OK.

For completion, I've added the basic Javascript code for triggering the event:

_x000D_
_x000D_
const rightArrowKey = 39
const event = new KeyboardEvent('keydown',{'key':rightArrowKey})
document.dispatchEvent(event)
_x000D_
_x000D_
_x000D_

How to change string into QString?

If by string you mean std::string you can do it with this method:

QString QString::fromStdString(const std::string & str)

std::string str = "Hello world";
QString qstr = QString::fromStdString(str);

If by string you mean Ascii encoded const char * then you can use this method:

QString QString::fromAscii(const char * str, int size = -1)

const char* str = "Hello world";
QString qstr = QString::fromAscii(str);

If you have const char * encoded with system encoding that can be read with QTextCodec::codecForLocale() then you should use this method:

QString QString::fromLocal8Bit(const char * str, int size = -1)

const char* str = "zazólc gesla jazn";      // latin2 source file and system encoding
QString qstr = QString::fromLocal8Bit(str);

If you have const char * that's UTF8 encoded then you'll need to use this method:

QString QString::fromUtf8(const char * str, int size = -1)

const char* str = read_raw("hello.txt"); // assuming hello.txt is UTF8 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const char*
QString qstr = QString::fromUtf8(str);

There's also method for const ushort * containing UTF16 encoded string:

QString QString::fromUtf16(const ushort * unicode, int size = -1)

const ushort* str = read_raw("hello.txt"); // assuming hello.txt is UTF16 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const ushort*
QString qstr = QString::fromUtf16(str);

python NameError: global name '__file__' is not defined

Are you using the interactive interpreter? You can use

sys.argv[0]

You should read: How do I get the path of the current executed file in Python?

How to set IntelliJ IDEA Project SDK

For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure enter image description here Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 enter image description here Now Just go Project under Project settings and select the project SDK. enter image description here

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

You could rather do a upsert, this operation in MongoDB is utilized to save document into collection. If document matches query criteria then it will perform update operation otherwise it will insert a new document into collection.

something similar as below

db.employees.update(
    {type:"FT"},
    {$set:{salary:200000}},
    {upsert : true}
 )

How to add a downloaded .box file to Vagrant?

F:\PuppetLab\src\boxes>vagrant box add precise32 file:///F:/PuppetLab/src/boxes/precise32.box
==> box: Adding box 'precise32' (v0) for provider:
    box: Downloading: file:///F:/PuppetLab/src/boxes/precise32.box
    box: Progress: 100% (Rate: 1200k/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'precise32' (v0) for 'virtualbox'!

Getting the application's directory from a WPF application

I tried this:

    label1.Content = Directory.GetCurrentDirectory();

and get also the directory.

phpmyadmin "Not Found" after install on Apache, Ubuntu

sudo dpkg-reconfigure -plow phpmyadmin 

Select No when asked to reconfigure the database. Then when asked to choose apache2, make sure to hit space while [ ] apache2 is highlighted. An asterisk should appear between the brackets. Then hit Enter. Phpmyadmin should reconfigure and now http://localhost/phpmyadmin should work. for further detail https://www.howtoforge.com/installing-apache2-with-php5-and-mysql-support-on-ubuntu-13.04-lamp

Difference between SurfaceView and View?

Views are all drawn on the same GUI thread which is also used for all user interaction.

So if you need to update GUI rapidly or if the rendering takes too much time and affects user experience then use SurfaceView.

SQL Order By Count

Below gives me opposite of what you have. (Notice Group column)

SELECT
    *
FROM
    myTable
GROUP BY
    Group_value,
    ID
ORDER BY
    count(Group_value)

Let me know if this is fine with you...

I am trying to get what you want too...

ImageView in circular through xml

As was described in Orhan Obut's answer but with the changes:

<ImageView
    android:layout_width="0dp"  //or use your own value
    android:layout_height="match_parent"
    android:src="@drawable/img"
    android:layout_weight="75" />// in case of use of weight

to avoid stretches of the image. And img.xml:

<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/profile" />
<item android:drawable="@drawable/circle" /></layer-list>

(without changes), and circle.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadiusRatio="2"
android:shape="ring"
android:thickness="300dp"
android:useLevel="false">
<solid android:color="@android:color/white"/>
<stroke
    android:width="2dp"
    android:color="@android:color/black"/>
</shape>
 

here the thickness of the ring gotten maximal - 1000dp
and radiusRatio is a half of image width(max ring width, yes?) - 2
and the stroke is for required border if needed.
I used square png image ( profile.png ), btw. With same width and height. This is correct for arbitrary ImageView dimentions. enter image description here

CSS get height of screen resolution

You can bind the current height and width of the screen to css variables: var(--screen-x) and var(--screen-y) with this javascript:

var root = document.documentElement;

document.addEventListener('resize', () => {
  root.style.setProperty('--screen-x', window.screenX)
  root.style.setProperty('--screen-y', window.screenY)
})

This was directly adapted from lea verou's example in her talk on css variables here: https://leaverou.github.io/css-variables/#slide31

How can you profile a Python script?

pprofile

line_profiler (already presented here) also inspired pprofile, which is described as:

Line-granularity, thread-aware deterministic and statistic pure-python profiler

It provides line-granularity as line_profiler, is pure Python, can be used as a standalone command or a module, and can even generate callgrind-format files that can be easily analyzed with [k|q]cachegrind.

vprof

There is also vprof, a Python package described as:

[...] providing rich and interactive visualizations for various Python program characteristics such as running time and memory usage.

heatmap

Cannot find control with name: formControlName in angular reactive form

I also had this error, and you helped me solve it. If formGroup or formGroupName are not written with the good case, then the name of the control is not found. Correct the case of formGroup or formGroupName and it is OK.

Styling the last td in a table with css

The :last-child selector should do it, but it's not supported in any version of IE.

I'm afraid you have no choice but to use a class.

How can I count the rows with data in an Excel sheet?

If you don't mind VBA, here is a function that will do it for you. Your call would be something like:

=CountRows(1:10) 
Function CountRows(ByVal range As range) As Long

Application.ScreenUpdating = False
Dim row As range
Dim count As Long

For Each row In range.Rows
    If (Application.WorksheetFunction.CountBlank(row)) - 256 <> 0 Then
        count = count + 1
    End If
Next

CountRows = count
Application.ScreenUpdating = True

End Function

How it works: I am exploiting the fact that there is a 256 row limit. The worksheet formula CountBlank will tell you how many cells in a row are blank. If the row has no cells with values, then it will be 256. So I just minus 256 and if it's not 0 then I know there is a cell somewhere that has some value.

What is the difference between Subject and BehaviorSubject?

It might help you to understand.

import * as Rx from 'rxjs';

const subject1 = new Rx.Subject();
subject1.next(1);
subject1.subscribe(x => console.log(x)); // will print nothing -> because we subscribed after the emission and it does not hold the value.

const subject2 = new Rx.Subject();
subject2.subscribe(x => console.log(x)); // print 1 -> because the emission happend after the subscription.
subject2.next(1);

const behavSubject1 = new Rx.BehaviorSubject(1);
behavSubject1.next(2);
behavSubject1.subscribe(x => console.log(x)); // print 2 -> because it holds the value.

const behavSubject2 = new Rx.BehaviorSubject(1);
behavSubject2.subscribe(x => console.log('val:', x)); // print 1 -> default value
behavSubject2.next(2) // just because of next emission will print 2 

How to define optional methods in Swift protocol?

Here is a concrete example with the delegation pattern.

Setup your Protocol:

@objc protocol MyProtocol:class
{
    func requiredMethod()
    optional func optionalMethod()
}

class MyClass: NSObject
{
    weak var delegate:MyProtocol?

    func callDelegate()
    {
        delegate?.requiredMethod()
        delegate?.optionalMethod?()
    }
}

Set the delegate to a class and implement the Protocol. See that the optional method does not need to be implemented.

class AnotherClass: NSObject, MyProtocol
{
    init()
    {
        super.init()

        let myInstance = MyClass()
        myInstance.delegate = self
    }

    func requiredMethod()
    {
    }
}

One important thing is that the optional method is optional and needs a "?" when calling. Mention the second question mark.

delegate?.optionalMethod?()

How to Round to the nearest whole number in C#

Just a reminder. Beware for double.

Math.Round(0.3 / 0.2 ) result in 1, because in double 0.3 / 0.2 = 1.49999999
Math.Round( 1.5 ) = 2

Javascript to display the current date and time

You can try the below:

function formatAMPM() {
    var date = new Date();
    var currDate = date.getDate();
    var hours = date.getHours();
    var dayName = getDayName(date.getDay());
    var minutes = date.getMinutes();
    var monthName = getMonthName(date.getMonth());
    var year = date.getFullYear();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = dayName + ' ' + monthName + ' ' + currDate + ' ' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
    alert(strTime);
}

function getMonthName(month) {
    var ar = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return ar[month];
}

function getDayName(day) {
    var ar1 = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    return ar1[day];
}

EDIT: Refer here for a working demo.

How to get file name from file path in android

I think you can use substring method to get name of the file from the path string.

String path=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg"; 
// it contains your image path...I'm using a temp string...
String filename=path.substring(path.lastIndexOf("/")+1);

How do you run CMD.exe under the Local System Account?

if you can write a batch file that does not need to be interactive, try running that batch file as a service, to do what needs to be done.

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

Set value of hidden input with jquery

You should use val instead of value.

<script type="text/javascript" language="javascript">
$(document).ready(function () { 
    $('input[name="testing"]').val('Work!');
});
</script>

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

How can you debug a CORS request with cURL?

Seems like just this works:

curl -I http://example.com

Look for Access-Control-Allow-Origin: * in the returned headers

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

PHP equivalent of .NET/Java's toString()

The documentation says that you can also do:

$str = "$foo";

It's the same as cast, but I think it looks prettier.

Source:

Passing arrays as url parameter

This is another way of solving this problem.

$data = array(
              1,
              4,
             'a' => 'b',
             'c' => 'd'
              );
$query = http_build_query(array('aParam' => $data));

Running EXE with parameters

System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

Can I have multiple :before pseudo-elements for the same element?

If your main element has some child elements or text, you could make use of it.

Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).

Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.

This element will start acting like his owner is your main element.

HTML

<div class="circle">
    <span>Some text</span>
</div>

CSS

.circle {
    position: relative; /* or absolute/fixed */
}

.circle:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle:after {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle span {
    /* not relative/absolute/fixed */
}

.circle span:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

Update Git submodule to latest commit on origin

The git submodule update command actually tells Git that you want your submodules to each check out the commit already specified in the index of the superproject. If you want to update your submodules to the latest commit available from their remote, you will need to do this directly in the submodules.

So in summary:

# Get the submodule initially
git submodule add ssh://bla submodule_dir
git submodule init

# Time passes, submodule upstream is updated
# and you now want to update

# Change to the submodule directory
cd submodule_dir

# Checkout desired branch
git checkout master

# Update
git pull

# Get back to your project root
cd ..

# Now the submodules are in the state you want, so
git commit -am "Pulled down update to submodule_dir"

Or, if you're a busy person:

git submodule foreach git pull origin master

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

None of the above worked for me but I came up with this and it worked:

function toggleChevron(el) {
  if ($(el).find('i').hasClass('icon-chevron-left'))
      $(el).find('.icon-chevron-left').removeClass("icon-chevron-left").addClass("icon-chevron-down");
  else 
      $(el).find('.icon-chevron-down').removeClass("icon-chevron-down").addClass("icon-chevron-left");
}

HTML implementation:

<div class="accordion" id="accordion-send">
  <div class="accordion-group">
    <div class="accordion-heading" onClick="toggleChevron(this)">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion-send" href="#collapse-refund">
        <i class="icon icon-chevron-right"></i> Send notice
      </a>
      ...

CSS way to horizontally align table

Steven is right, in theory:

the “correct” way to center a table using CSS. Conforming browsers ought to center tables if the left and right margins are equal. The simplest way to accomplish this is to set the left and right margins to “auto.” Thus, one might write in a style sheet:

table
{ 
    margin-left: auto;
    margin-right: auto;
}

But the article mentioned in the beginning of this answer gives you all the other way to center a table.

An elegant css cross-browser solution: This works in both MSIE 6 (Quirks and Standards), Mozilla, Opera and even Netscape 4.x without setting any explicit widths:

div.centered 
{
    text-align: center;
}

div.centered table 
{
    margin: 0 auto; 
    text-align: left;
}


<div class="centered">
    <table>
    …
    </table>
</div>

What is Unicode, UTF-8, UTF-16?

  • Unicode
    • is a set of characters used around the world
  • UTF-8
    • a character encoding capable of encoding all possible characters (called code points) in Unicode.
    • code unit is 8-bits
    • use one to four code units to encode Unicode
    • 00100100 for "$" (one 8-bits);11000010 10100010 for "¢" (two 8-bits);11100010 10000010 10101100 for "" (three 8-bits)
  • UTF-16
    • another character encoding
    • code unit is 16-bits
    • use one to two code units to encode Unicode
    • 00000000 00100100 for "$" (one 16-bits);11011000 01010010 11011111 01100010 for "" (two 16-bits)

How to find the socket buffer size of linux

If you want see your buffer size in terminal, you can take a look at:

  • /proc/sys/net/ipv4/tcp_rmem (for read)
  • /proc/sys/net/ipv4/tcp_wmem (for write)

They contain three numbers, which are minimum, default and maximum memory size values (in byte), respectively.

PHP - cannot use a scalar as an array warning

Make sure that you don't declare it as a integer, float, string or boolean before. http://php.net/manual/en/function.is-scalar.php

How to print a debug log?

I have used many of these, but since I usually need to debug when developing, and since I develop on localhost, I have followed the advice of others and now write to the browser's JavaScript debug console (see http://www.codeforest.net/debugging-php-in-browsers-javascript-console).

That means that I can look at the web page which my PHP is generating in my browser & press F12 to quickly show/hide any debug trace.

Since I am constantly looking at the developer tools for debugger, CSS layout, etc, it makes sense to look at my PHP loggon there.

If anyone does decide to us that code, I made one minor change. After

function debug($name, $var = null, $type = LOG) {

I added

$name = 'PHP: ' . $name;

This is because my server side PHP generates HTML conatining JavaScript & I find it useful to distinguish between output from PHP & JS.

(Note: I am currently updating this to allow me to switch on & off different output types: from PHP, from JS, and database access)

Laravel 5.2 - pluck() method returns array

laravel pluck returns an array

if your query is:

 $name = DB::table('users')->where('name', 'John')->pluck('name');

then the array is like this (key is the index of the item. auto incremented value):

[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

but if you do like this:

$name = DB::table('users')->where('name', 'John')->pluck('name','id');

then the key is actual index in the database.

key||value
[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

you can set any value as key.

Maven2 property that indicates the parent directory

So the problem as I see it is that you can't get the absolute path to a parent directory in maven.

<rant> I've heard this talked about as an anti-pattern, but for every anti-pattern there is real, legitimate use case for it, and I'm sick of maven telling me I can only follow their patterns.</rant>

So the work around I found was to use antrun. Try this in the child pom.xml:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.7</version>
    <executions>
        <execution>
            <id>getMainBaseDir</id>
            <phase>validate</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <exportAntProperties>true</exportAntProperties>
                <target>
                    <!--Adjust the location below to your directory structure -->
                    <property name="main.basedir" location="./.." />
                    <echo message="main.basedir=${main.basedir}"/>
                </target>
            </configuration>
        </execution>
    </executions>
</plugin>

If you run mvn verify you should see something like this:

main:
     [echo] main.basedir=C:\src\parent.project.dir.name

You can then use ${main.basedir} in any of the other plugins, etc. Took me a while to figure this out, so hope it helps someone else.

Easiest way to rotate by 90 degrees an image using OpenCV?

As of OpenCV3.2, life just got a bit easier, you can now rotate an image in a single line of code:

cv::rotate(image, image, cv::ROTATE_90_CLOCKWISE);

For the direction you can choose any of the following:

ROTATE_90_CLOCKWISE
ROTATE_180
ROTATE_90_COUNTERCLOCKWISE

ZIP file content type for HTTP request

If you want the MIME type for a file, you can use the following code:

- (NSString *)mimeTypeForPath:(NSString *)path
{
    // get a mime type for an extension using MobileCoreServices.framework

    CFStringRef extension = (__bridge CFStringRef)[path pathExtension];
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
    assert(UTI != NULL);

    NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType));
    assert(mimetype != NULL);

    CFRelease(UTI);

    return mimetype;
}

In the case of a ZIP file, this will return application/zip.

Returning an array using C

Your method will return a local stack variable that will fail badly. To return an array, create one outside the function, pass it by address into the function, then modify it, or create an array on the heap and return that variable. Both will work, but the first doesn't require any dynamic memory allocation to get it working correctly.

void returnArray(int size, char *retArray)
{
  // work directly with retArray or memcpy into it from elsewhere like
  // memcpy(retArray, localArray, size); 
}

#define ARRAY_SIZE 20

int main(void)
{
  char foo[ARRAY_SIZE];
  returnArray(ARRAY_SIZE, foo);
}

What's the best way to iterate an Android Cursor?

I'd just like to point out a third alternative which also works if the cursor is not at the start position:

if (cursor.moveToFirst()) {
    do {
        // do what you need with the cursor here
    } while (cursor.moveToNext());
}

How to generate a core dump in Linux on a segmentation fault?

To check where the core dumps are generated, run:

sysctl kernel.core_pattern

or:

cat /proc/sys/kernel/core_pattern

where %e is the process name and %t the system time. You can change it in /etc/sysctl.conf and reloading by sysctl -p.

If the core files are not generated (test it by: sleep 10 & and killall -SIGSEGV sleep), check the limits by: ulimit -a.

If your core file size is limited, run:

ulimit -c unlimited

to make it unlimited.

Then test again, if the core dumping is successful, you will see “(core dumped)” after the segmentation fault indication as below:

Segmentation fault: 11 (core dumped)

See also: core dumped - but core file is not in current directory?


Ubuntu

In Ubuntu the core dumps are handled by Apport and can be located in /var/crash/. However, it is disabled by default in stable releases.

For more details, please check: Where do I find the core dump in Ubuntu?.

macOS

For macOS, see: How to generate core dumps in Mac OS X?

Regex for not empty and not whitespace

In my understanding you want to match a non-blank and non-empty string, so the top answer is doing the opposite. I suggest:

(.|\s)*\S(.|\s)*

- this matches any string containing at least one non-whitespace character (the \S in the middle). It can be preceded and followed by anything, any char or whitespace sequence (including new lines) - (.|\s)*.

You can try it with explanation on https://regex101.com/.

Best place to insert the Google Analytics code

Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.

When restoring a backup, how do I disconnect all active connections?

Try this:

DECLARE UserCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT
    spid
FROM
    master.dbo.sysprocesses
WHERE DB_NAME(dbid) = 'dbname'--replace the dbname with your database
DECLARE @spid SMALLINT
DECLARE @SQLCommand VARCHAR(300)
OPEN UserCursor
FETCH NEXT FROM UserCursor INTO
    @spid
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SQLCommand = 'KILL ' + CAST(@spid AS VARCHAR)
    EXECUTE(@SQLCommand)
    FETCH NEXT FROM UserCursor INTO
        @spid
END
CLOSE UserCursor
DEALLOCATE UserCursor
GO

Adding to a vector of pair

You can use std::make_pair

revenue.push_back(std::make_pair("string",map[i].second));

Maven: add a dependency to a jar by relative path

Using the system scope. ${basedir} is the directory of your pom.

<dependency>
    <artifactId>..</artifactId>
    <groupId>..</groupId>
    <scope>system</scope>
    <systemPath>${basedir}/lib/dependency.jar</systemPath>
</dependency>

However it is advisable that you install your jar in the repository, and not commit it to the SCM - after all that's what maven tries to eliminate.

How to resolve the C:\fakepath?

Use

document.getElementById("file-id").files[0].name; 

instead of

document.getElementById('file-id').value

How to Calculate Jump Target Address and Branch Target Address?

(In the diagrams and text below, PC is the address of the branch instruction itself. PC+4 is the end of the branch instruction itself, and the start of the branch delay slot. Except in the absolute jump diagram.)

1. Branch Address Calculation

In MIPS branch instruction has only 16 bits offset to determine next instruction. We need a register added to this 16 bit value to determine next instruction and this register is actually implied by architecture. It is PC register since PC gets updated (PC+4) during the fetch cycle so that it holds the address of the next instruction.

We also limit the branch distance to -2^15 to +2^15 - 1 instruction from the (instruction after the) branch instruction. However, this is not real issue since most branches are local anyway.

So step by step :

  • Sign extend the 16 bit offset value to preserve its value.
  • Multiply resulting value with 4. The reason behind this is that If we are going to branch some address, and PC is already word aligned, then the immediate value has to be word-aligned as well. However, it makes no sense to make the immediate word-aligned because we would be wasting low two bits by forcing them to be 00.
  • Now we have a 32 bit relative offset. Add this value to PC + 4 and that is your branch address.

Branch address calculation


2. Jump Address Calculation

For Jump instruction MIPS has only 26 bits to determine Jump location. Jumps are relative to PC in MIPS. Like branch, immediate jump value needs to be word-aligned; therefore, we need to multiply 26 bit address with four.

Again step by step:

  • Multiply 26 bit value with 4.
  • Since we are jumping relative to PC+4 value, concatenate first four bits of PC+4 value to left of our jump address.
  • Resulting address is the jump value.

In other words, replace the lower 28 bits of the PC + 4 with the lower 26 bits of the fetched instruction shifted left by 2 bits.

enter image description here

Jumps are region-relative to the branch-delay slot, not necessarily the branch itself. In the diagram above, PC has already advanced to the branch delay slot before the jump calculation. (In a classic-RISC 5 stage pipeline, the BD was fetched in the same cycle the jump is decoded, so that PC+4 next instruction address is already available for jumps as well as branches, and calculating relative to the jump's own address would have required extra work to save that address.)

Source: Bilkent University CS 224 Course Slides

Regex for quoted string with escaping quotes

This one works perfect on PCRE and does not fall with StackOverflow.

"(.*?[^\\])??((\\\\)+)?+"

Explanation:

  1. Every quoted string starts with Char: " ;
  2. It may contain any number of any characters: .*? {Lazy match}; ending with non escape character [^\\];
  3. Statement (2) is Lazy(!) optional because string can be empty(""). So: (.*?[^\\])??
  4. Finally, every quoted string ends with Char("), but it can be preceded with even number of escape sign pairs (\\\\)+; and it is Greedy(!) optional: ((\\\\)+)?+ {Greedy matching}, bacause string can be empty or without ending pairs!

add new element in laravel collection object

As mentioned above if you wish to as a new element your queried collection you can use:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
        $product = DB::select(DB::raw(' select * from product
               where product_id = '. $id.';' ));

        $items->push($product);
        // or 
        // $items->put('products', $product);
    }

but if you wish to add new element to each queried element you need to do like:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
           $product = DB::select(DB::raw(' select * from product
                 where product_id = '. $id.';' ));

          $item->add_whatever_element_you_want = $product;
    }

add_whatever_element_you_want can be whatever you wish that your element is named (like product for example).