Programs & Examples On #Active users

How can you get the active users connected to a postgreSQL database via SQL?

Using balexandre's info:

SELECT usesysid, usename FROM pg_stat_activity;

Get current working directory in a Qt application

I'm running Qt 5.5 under Windows and the default constructor of QDir appears to pick up the current working directory, not the application directory.

I'm not sure if the getenv PWD will work cross-platform and I think it is set to the current working directory when the shell launched the application and doesn't include any working directory changes done by the app itself (which might be why the OP is seeing this behavior).

So I thought I'd add some other ways that should give you the current working directory (not the application's binary location):

// using where a relative filename will end up
QFileInfo fi("temp");
cout << fi.absolutePath() << endl;

// explicitly using the relative name of the current working directory
QDir dir(".");
cout << dir.absolutePath() << endl;

How to get the clicked link's href with jquery?

$(".testClick").click(function () {
         var value = $(this).attr("href");
         alert(value );     
}); 

When you use $(".className") you are getting the set of all elements that have that class. Then when you call attr it simply returns the value of the first item in the collection.

Get ID from URL with jQuery

Get a substring after the last index of /.

var url = 'http://www.site.com/234234234';
var id = url.substring(url.lastIndexOf('/') + 1);
alert(id); // 234234234

It's just basic JavaScript, no jQuery involved.

How to disable editing of elements in combobox for c#?

Use the ComboStyle property:

comboBox.DropDownStyle = ComboBoxStyle.DropDownList;

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

Use [^\p{L}\p{Nd}]+ - this matches all (Unicode) characters that are neither letters nor (decimal) digits.

In Java:

String resultString = subjectString.replaceAll("[^\\p{L}\\p{Nd}]+", "");

Edit:

I changed \p{N} to \p{Nd} because the former also matches some number symbols like ¼; the latter doesn't. See it on regex101.com.

System.Security.SecurityException when writing to Event Log

try below in web.config

 <system.web>

<trust level="Full"/>

</system.web>

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

No events get triggered when the element is having disabled attribute.

None of the below will get triggered.

$("[disabled]").click( function(){ console.log("clicked") });//No Impact
$("[disabled]").hover( function(){ console.log("hovered") });//No Impact
$("[disabled]").dblclick( function(){ console.log("double clicked") });//No Impact

While readonly will be triggered.

$("[readonly]").click( function(){ console.log("clicked") });//log - clicked
$("[readonly]").hover( function(){ console.log("hovered") });//log - hovered
$("[readonly]").dblclick( function(){ console.log("double clicked") });//log - double clicked

How to check if a network port is open on linux?

In case when you probing TCP ports with intention to listen on it, it’s better to actually call listen. The approach with tring to connect don’t 'see' client ports of established connections, because nobody listen on its. But these ports cannot be used to listen on its.

import socket


def check_port(port, rais=True):
    """ True -- it's possible to listen on this port for TCP/IPv4 or TCP/IPv6
    connections. False -- otherwise.
    """
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('127.0.0.1', port))
        sock.listen(5)
        sock.close()
        sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        sock.bind(('::1', port))
        sock.listen(5)
        sock.close()
    except socket.error as e:
        return False
        if rais:
            raise RuntimeError(
                "The server is already running on port {0}".format(port))
    return True

How do I restart a service on a remote machine in Windows?

One way would be to enable telnet server on the machin you want to control services on (add/remove windows components)

Open dos prompt
Type telnet yourmachineip/name
Log on
type net start &serviceName* e.g. w3svc

This will start IIS or you can use net stop to stop a service.

Depending on your setup you need to look at a way of securing the telnet connection as I think its unencrypted.

Read file-contents into a string in C++

There should be no \0 in text files.

#include<iostream>
#include<fstream>

using namespace std;

int main(){
  fstream f(FILENAME, fstream::in );
  string s;
  getline( f, s, '\0');

  cout << s << endl;
  f.close();
}

How to generate unique IDs for form labels in React?

You could use a library such as node-uuid for this to make sure you get unique ids.

Install using:

npm install node-uuid --save

Then in your react component add the following:

import {default as UUID} from "node-uuid";
import {default as React} from "react";

export default class MyComponent extends React.Component {   
  componentWillMount() {
    this.id = UUID.v4();
  }, 
  render() {
    return (
      <div>
        <label htmlFor={this.id}>My label</label>
        <input id={this.id} type="text"/>
      </div>
    );
  }   
}

Dump all tables in CSV format using 'mysqldump'

mysqldump has options for CSV formatting:

--fields-terminated-by=name
                  Fields in the output file are terminated by the given
--lines-terminated-by=name
                  Lines in the output file are terminated by the given

The name should contain one of the following:

`--fields-terminated-by`

\t or "\""

`--fields-enclosed-by=name`
   Fields in the output file are enclosed by the given

and

--lines-terminated-by

  • \r
  • \n
  • \r\n

Naturally you should mysqldump each table individually.

I suggest you gather all table names in a text file. Then, iterate through all tables running mysqldump. Here is a script that will dump and gzip 10 tables at a time:

MYSQL_USER=root
MYSQL_PASS=rootpassword
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
SQLSTMT="SELECT CONCAT(table_schema,'.',table_name)"
SQLSTMT="${SQLSTMT} FROM information_schema.tables WHERE table_schema NOT IN "
SQLSTMT="${SQLSTMT} ('information_schema','performance_schema','mysql')"
mysql ${MYSQL_CONN} -ANe"${SQLSTMT}" > /tmp/DBTB.txt
COMMIT_COUNT=0
COMMIT_LIMIT=10
TARGET_FOLDER=/path/to/csv/files
for DBTB in `cat /tmp/DBTB.txt`
do
    DB=`echo "${DBTB}" | sed 's/\./ /g' | awk '{print $1}'`
    TB=`echo "${DBTB}" | sed 's/\./ /g' | awk '{print $2}'`
    DUMPFILE=${DB}-${TB}.csv.gz
    mysqldump ${MYSQL_CONN} -T ${TARGET_FOLDER} --fields-terminated-by="," --fields-enclosed-by="\"" --lines-terminated-by="\r\n" ${DB} ${TB} | gzip > ${DUMPFILE}
    (( COMMIT_COUNT++ ))
    if [ ${COMMIT_COUNT} -eq ${COMMIT_LIMIT} ]
    then
        COMMIT_COUNT=0
        wait
    fi
done
if [ ${COMMIT_COUNT} -gt 0 ]
then
    wait
fi

Jquery- Get the value of first td in table

$(".hit").click(function(){
   var values = [];
   var table = $(this).closest("table");
   table.find("tr").each(function() {
      values.push($(this).find("td:first").html());
   });

   alert(values);    
});

You should avoid $(".hit") it's really inefficient. Try using event delegation instead.

CSS float right not working correctly

LIke this

final answer

css

h2 {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    margin: 0;
    padding: 0;
}
.edit_button {
    float: right;
}

demo1

css

h2 {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: gray;
    float: left;
    margin: 0;
    padding: 0;
}
.edit_button {
    float: right;
}

html

<h2>
Contact Details</h2>
<button type="button" class="edit_button" >My Button</button>

demo

html

<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray; float:left;">
Contact Details



</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>

Simple PHP form: Attachment to email (code golf)

This article "How to create PHP based email form with file attachment" presents step-by-step instructions how to achieve your requirement.

Quote:

This article shows you how to create a PHP based email form that supports file attachment. The article will also show you how to validate the type and size of the uploaded file.

It consists of the following steps:

  • The HTML form with file upload box
  • Getting the uploaded file in the PHP script
  • Validating the size and extension of the uploaded file
  • Copy the uploaded file
  • Sending the Email

The entire example code can be downloaded here

How to export DataTable to Excel

Try this function pass the datatable and file path where you want to export

public void CreateCSVFile(ref DataTable dt, string strFilePath)
{            
    try
    {
        // Create the CSV file to which grid data will be exported.
        StreamWriter sw = new StreamWriter(strFilePath, false);
        // First we will write the headers.
        //DataTable dt = m_dsProducts.Tables[0];
        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);

        // Now write all the rows.

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }

            sw.Write(sw.NewLine);
        }
        sw.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

How to properly add 1 month from now to current date in moment.js

According to the latest doc you can do the following-

Add a day

moment().add(1, 'days').calendar();

Add Year

moment().add(1, 'years').calendar();

Add Month

moment().add(1, 'months').calendar();

How to convert numbers to words without using num2word library?

I know that this is a very old post and I am probably very late to the party, but hopefully this will help someone else. This has worked for me.

phone_words = input('Phone: ')
numbered_words = {
    '0': 'zero',
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    '5': 'five',
    '6': 'six',
    '7': 'seven',
    '8': 'eight',
    '9': 'nine'
}
output = ""
for ch in phone_words:
    output += numbered_words.get(ch, "!") + " "
phone_words = numbered_words

print(output)

Unix command to check the filesize

ls -l --block-size=M 

will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB. If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use --block-size=MB instead.

Or

ls -lah 

-h When used with the -l option, use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte in order to reduce the number of digits to three or less using base 2 for sizes.

man ls

http://unixhelp.ed.ac.uk/CGI/man-cgi?ls

Access parent URL from iframe

var url = (window.location != window.parent.location) ? document.referrer: document.location;

I found that the above example suggested previously worked when the script was being executed in an iframe however it did not retrieve the url when the script was executed outside of an iframe, a slight adjustment was required:

var url = (window.location != window.parent.location) ? document.referrer: document.location.href;

Convert string to buffer Node

Note: Just reposting John Zwinck's comment as answer.

One issue might be that you are using a older version of Node (for the moment, I cannot upgrade, codebase struck with v4.3.1). Simple solution here is, using the deprecated way:

new Buffer(bufferStr)

Note #2: This is for people struck in older version, for whom Buffer.from does not work

Java Replacing multiple different substring in a string at once (or in the most efficient way)

StringBuilder will perform replace more efficiently, since its character array buffer can be specified to a required length.StringBuilder is designed for more than appending!

Of course the real question is whether this is an optimisation too far ? The JVM is very good at handling creation of multiple objects and the subsequent garbage collection, and like all optimisation questions, my first question is whether you've measured this and determined that it's a problem.

How to check if a string contains a substring in Bash

Exact word match:

string='My long string'
exactSearch='long'

if grep -E -q "\b${exactSearch}\b" <<<${string} >/dev/null 2>&1
  then
    echo "It's there"
  fi

Calculate row means on subset of columns

rowMeans is nice, but if you are still trying to wrap your head around the apply family of functions, this is a good opprotunity to begin understanding it.

DF['Mean'] <- apply(DF[,2:4], 1, mean)

Notice I'm doing a slightly different assignment than the first example. This approach makes it easier to incorporate it into for loops.

Git merge master into feature branch

In Eclipse -

1)Checkout master branch

Git Repositories ->Click on your repository -> click on Local ->double click master branch
->Click on yes for check out

2)Pull master branch

Right click on project ->click on Team -> Click on Pull

3)Checkout your feature branch(follow same steps mentioned in 1 point)

4)Merge master into feature

Git Repositories ->Click on your repository -> click on Local ->Right Click on your selected feature branch ->Click on merge ->Click on Local ->Click on Master ->Click on Merge.

5)Now you will get all changes of Master branch in feature branch. Remove conflict if any.

For conflict if any exists ,follow this -
Changes mentioned as Head(<<<<<< HEAD) is your change, Changes mentioned in branch(>>>>>>> branch) is other person change, you can update file accordingly.

Note - You need to do add to index for conflicts files

6)commit and push your changes in feature branch.

Right click on project ->click on Team -> Click on commit -> Commit and Push.

OR

Git Repositories ->Click on your repository -> click on Local ->Right Click on your selected feature branch ->Click on Push Branch ->Preview ->Push

Get exit code of a background process

This may be extending beyond your question, however if you're concerned about the length of time processes are running for, you may be interested in checking the status of running background processes after an interval of time. It's easy enough to check which child PIDs are still running using pgrep -P $$, however I came up with the following solution to check the exit status of those PIDs that have already expired:

cmd1() { sleep 5; exit 24; }
cmd2() { sleep 10; exit 0; }

pids=()
cmd1 & pids+=("$!")
cmd2 & pids+=("$!")

lasttimeout=0
for timeout in 2 7 11; do
  echo -n "interval-$timeout: "
  sleep $((timeout-lasttimeout))

  # you can only wait on a pid once
  remainingpids=()
  for pid in ${pids[*]}; do
     if ! ps -p $pid >/dev/null ; then
        wait $pid
        echo -n "pid-$pid:exited($?); "
     else
        echo -n "pid-$pid:running; "
        remainingpids+=("$pid")
     fi
  done
  pids=( ${remainingpids[*]} )

  lasttimeout=$timeout
  echo
done

which outputs:

interval-2: pid-28083:running; pid-28084:running; 
interval-7: pid-28083:exited(24); pid-28084:running; 
interval-11: pid-28084:exited(0); 

Note: You could change $pids to a string variable rather than array to simplify things if you like.

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

Two submit buttons in one form

Maybe the suggested solutions here worked in 2009, but ive tested all of this upvoted answers and nobody is working in any browsers.

only solution i found working is this: (but its a bit ugly to use i think)

<form method="post" name="form">
<input type="submit" value="dosomething" onclick="javascript: form.action='actionurl1';"/>
<input type="submit" value="dosomethingelse" onclick="javascript: form.action='actionurl2';"/>

Random state (Pseudo-random number) in Scikit learn

train_test_split splits arrays or matrices into random train and test subsets. That means that everytime you run it without specifying random_state, you will get a different result, this is expected behavior. For example:

Run 1:

>>> a, b = np.arange(10).reshape((5, 2)), range(5)
>>> train_test_split(a, b)
[array([[6, 7],
        [8, 9],
        [4, 5]]),
 array([[2, 3],
        [0, 1]]), [3, 4, 2], [1, 0]]

Run 2

>>> train_test_split(a, b)
[array([[8, 9],
        [4, 5],
        [0, 1]]),
 array([[6, 7],
        [2, 3]]), [4, 2, 0], [3, 1]]

It changes. On the other hand if you use random_state=some_number, then you can guarantee that the output of Run 1 will be equal to the output of Run 2, i.e. your split will be always the same. It doesn't matter what the actual random_state number is 42, 0, 21, ... The important thing is that everytime you use 42, you will always get the same output the first time you make the split. This is useful if you want reproducible results, for example in the documentation, so that everybody can consistently see the same numbers when they run the examples. In practice I would say, you should set the random_state to some fixed number while you test stuff, but then remove it in production if you really need a random (and not a fixed) split.

Regarding your second question, a pseudo-random number generator is a number generator that generates almost truly random numbers. Why they are not truly random is out of the scope of this question and probably won't matter in your case, you can take a look here form more details.

How to get file path in iPhone app

Since it is your files in your app bundle, I think you can use pathForResource:ofType: to get the full pathname of your file.

Here is an example:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"your_file_name" 
                                            ofType:@"the_file_extension"];

How do I calculate percentiles with python/numpy?

You might be interested in the SciPy Stats package. It has the percentile function you're after and many other statistical goodies.

percentile() is available in numpy too.

import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) # return 50th percentile, e.g median.
print p
3.0

This ticket leads me to believe they won't be integrating percentile() into numpy anytime soon.

Cannot make a static reference to the non-static method

for others that find this in the search:

I often get this one when I accidentally call a function using the class name rather than the object name. This typically happens because i give them too similar names : P

ie:

MyClass myclass = new MyClass();

// then later

MyClass.someFunction();

This is obviously a static method. (good for somethings) But what i really wanted to do (in most cases was)

myclass.someFunction();

It's such a silly mistake, but every couple of months, i waste about 30 mins messing with vars in the "MyClass" definitions to work out what im doing wrong when really, its just a typo.

Funny note: stack overflow highlights the syntax to make the mistake really obvious here.

Conditional formatting using AND() function

I had a similar problem with a less complicated formula:

= If (x > A & x <= B) 

and found that I could Remove the AND and join the two comparisons with +

  = (x > A1) + (x <= B1)        [without all the spaces]

Hope this helps others with less complex comparisons.

How to find event listeners on a DOM node when debugging or from the JavaScript code?

To get all eventListeners on a page printed alongside their elements

Array.from(document.querySelectorAll("*")).forEach(e => {
    const ev = getEventListeners(e)
    if (Object.keys(ev).length !== 0) console.log(e, ev)
})

Jquery insert new row into table at a certain index

You can use .eq() and .after() like this:

$('#my_table > tbody > tr').eq(i-1).after(html);

The indexes are 0 based, so to be the 4th row, you need i-1, since .eq(3) would be the 4th row, you need to go back to the 3rd row (2) and insert .after() that.

HTML/Javascript change div content

$('#content').html('whatever');

Find unique lines

uniq -u < file will do the job.

Getting the length of two-dimensional array

int secondDimensionSize = nir[0].length;

Each element of the first dimension is actually another array with the length of the second dimension.

how to set active class to nav menu from twitter bootstrap

You could add a diffrent class onto the BODY tag on each page e.g. on the homepage you could have this:

<body class="nav-1-on">

Then this css:

.nav-1-on .nav-1 a, .nav-2-on .nav-2 a, .nav-3-on .nav-3 a, .nav-4-on .nav-4 a {
     // set your styles here
}

The NAV element:

<ul>
  <li class="nav-1"><a href="#">Home</a></li>
  <li class="nav-2"><a href="#">Services</a></li>
  <li class="nav-3"><a href="#">About</a></li>
  <li class="nav-4"><a href="#">Contact</a></li>
</ul>
#

Alternatively you could place a class on the BODY on each page and then grab that via jQuery and add the .active class to the correct nav item based on that tag.

How to make jQuery UI nav menu horizontal?

You can do this:

/* Clearfix for the menu */
.ui-menu:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

and also set:

.ui-menu .ui-menu-item {
    display: inline-block;
    float: left;
    margin: 0;
    padding: 0;
    width: auto;
}

How do I apply CSS3 transition to all properties except background-position?

Try:

-webkit-transition: all .2s linear, background-position 0;

This worked for me on something similar..

Does Java have an exponential operator?

There is the Math.pow(double a, double b) method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b).

How to retrieve JSON Data Array from ExtJS Store

A one-line approach:

var jsonData = Ext.encode(Ext.pluck(store.data.items, 'data'));

Not very pretty, but quite short.

iPhone - Get Position of UIView within entire UIWindow

Swift 3, with extension:

extension UIView{
    var globalPoint :CGPoint? {
        return self.superview?.convert(self.frame.origin, to: nil)
    }

    var globalFrame :CGRect? {
        return self.superview?.convert(self.frame, to: nil)
    }
}

Get the current year in JavaScript

Instantiate the class Date and call upon its getFullYear method to get the current year in yyyy format. Something like this:

let currentYear = new Date().getFullYear;

The currentYear variable will hold the value you are looking out for.

Compare dates with javascript

you can done this way also.

if (dateFormat(first, "yyyy-mm-dd") > dateFormat(second, "yyyy-mm-dd")) {
        console.log("done");
}

OR

if (dateFormat(first, "mm-dd-yyyy") >  dateFormat(second, "mm-dd-yyyy")) {
        console.log("done");
}

i use following plugin for dateFormat()

        var dateFormat = function () {
        var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
            timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
            timezoneClip = /[^-+\dA-Z]/g,
            pad = function (val, len) {
                val = String(val);
                len = len || 2;
                while (val.length < len) val = "0" + val;
                return val;
            };

        // Regexes and supporting functions are cached through closure
        return function (date, mask, utc) {
            var dF = dateFormat;

            // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
            if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
                mask = date;
                date = undefined;
            }

            // Passing date through Date applies Date.parse, if necessary
            date = date ? new Date(date) : new Date;
            if (isNaN(date)) throw SyntaxError("invalid date");

            mask = String(dF.masks[mask] || mask || dF.masks["default"]);

            // Allow setting the utc argument via the mask
            if (mask.slice(0, 4) == "UTC:") {
                mask = mask.slice(4);
                utc = true;
            }

            var _ = utc ? "getUTC" : "get",
                d = date[_ + "Date"](),
                D = date[_ + "Day"](),
                m = date[_ + "Month"](),
                y = date[_ + "FullYear"](),
                H = date[_ + "Hours"](),
                M = date[_ + "Minutes"](),
                s = date[_ + "Seconds"](),
                L = date[_ + "Milliseconds"](),
                o = utc ? 0 : date.getTimezoneOffset(),
                flags = {
                    d:    d,
                    dd:   pad(d),
                    ddd:  dF.i18n.dayNames[D],
                    dddd: dF.i18n.dayNames[D + 7],
                    m:    m + 1,
                    mm:   pad(m + 1),
                    mmm:  dF.i18n.monthNames[m],
                    mmmm: dF.i18n.monthNames[m + 12],
                    yy:   String(y).slice(2),
                    yyyy: y,
                    h:    H % 12 || 12,
                    hh:   pad(H % 12 || 12),
                    H:    H,
                    HH:   pad(H),
                    M:    M,
                    MM:   pad(M),
                    s:    s,
                    ss:   pad(s),
                    l:    pad(L, 3),
                    L:    pad(L > 99 ? Math.round(L / 10) : L),
                    t:    H < 12 ? "a"  : "p",
                    tt:   H < 12 ? "am" : "pm",
                    T:    H < 12 ? "A"  : "P",
                    TT:   H < 12 ? "AM" : "PM",
                    Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                    o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                    S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
                };

            return mask.replace(token, function ($0) {
                return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
            });
        };
    }();

    // Some common format strings
    dateFormat.masks = {
        "default":      "ddd mmm dd yyyy HH:MM:ss",
        shortDate:      "m/d/yy",
        mediumDate:     "mmm d, yyyy",
        longDate:       "mmmm d, yyyy",
        fullDate:       "dddd, mmmm d, yyyy",
        shortTime:      "h:MM TT",
        mediumTime:     "h:MM:ss TT",
        longTime:       "h:MM:ss TT Z",
        isoDate:        "yyyy-mm-dd",
        isoTime:        "HH:MM:ss",
        isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
        isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
    };

    // Internationalization strings
    dateFormat.i18n = {
        dayNames: [
            "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
            "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
        ],
        monthNames: [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
            "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
        ]
    };

    // For convenience...
    Date.prototype.format = function (mask, utc) {
        return dateFormat(this, mask, utc);
    };

How can I clone a private GitLab repository?

It looks like there's not a straightforward solution for HTTPS-based cloning regarding GitLab. Therefore if you want a SSH-based cloning, you should take account these three forthcoming steps:

  • Create properly an SSH key using your email used to sign up. I would use the default filename to key for Windows. Don't forget to introduce a password!

    $ ssh-keygen -t rsa -C "[email protected]" -b 4096
    
    Generating public/private rsa key pair.
    Enter file in which to save the key ($PWD/.ssh/id_rsa): [\n]
    Enter passphrase (empty for no passphrase):[your password]
    Enter same passphrase again: [your password]
    Your identification has been saved in $PWD/.ssh/id_rsa.
    Your public key has been saved in $PWD/.ssh/id_rsa.pub.
    
  • Copy and paste all content from the recently id_rsa.pub generated into Setting>SSH keys>Key from your GitLab profile.

  • Get locally connected:

    $ ssh -i $PWD/.ssh/id_rsa [email protected]
    
    Enter passphrase for key "$PWD/.ssh/id_rsa": [your password]
    PTY allocation request failed on channel 0
    Welcome to GitLab, you!
    Connection to gitlab.com closed.
    

Finally, clone any private or internal GitLab repository!

$ git clone https://git.metabarcoding.org/obitools/ROBIBarcodes.git

Cloning into 'ROBIBarcodes'...
remote: Counting objects: 69, done.
remote: Compressing objects: 100% (65/65), done.
remote: Total 69 (delta 14), reused 0 (delta 0)
Unpacking objects: 100% (69/69), done.

Does WhatsApp offer an open API?

1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.

2) No. See the whatsapp security white paper.

3) See #1.

RestTemplate: How to send URL and query parameters together

One simple way to do that is:

String url = "http://test.com/Services/rest/{id}/Identifier"

UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
uriComponents = uriComponents.expand(Collections.singletonMap("id", "1234"));

and then adds the query params.

How do you get the width and height of a multi-dimensional array?

ary.GetLength(0) 
ary.GetLength(1)

for 2 dimensional array

Generate a heatmap in MatPlotLib using a scatter data set

If you are using 1.2.x

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(100000)
y = np.random.randn(100000)
plt.hist2d(x,y,bins=100)
plt.show()

gaussian_2d_heat_map

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

You can put the jQuery's Ajax setup in synchronous mode by calling

jQuery.ajaxSetup({async:false});

And then perform your Ajax calls using jQuery.get( ... );

Then just turning it on again once

jQuery.ajaxSetup({async:true});

I guess it works out the same thing as suggested by @Adam, but it might be helpful to someone that does want to reconfigure their jQuery.get() or jQuery.post() to the more elaborate jQuery.ajax() syntax.

Setting width of spreadsheet cell using PHPExcel

hi i got the same problem.. add 0.71 to excel cell width value and give that value to the

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);

eg: A Column width = 3.71 (excel value)

give column width = 4.42

will give the output file with same cell width.

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(4.42);

hope this help

Getting Date or Time only from a DateTime Object

Sometimes you want to have your GridView as simple as:

  <asp:GridView ID="grid" runat="server" />

You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.

protected void Page_Load(object sender, EventArgs e)
{
  grid.RowDataBound += grid_RowDataBound;
  // Your DB access code here...
  // grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  // grid.DataBind();
}

void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType != DataControlRowType.DataRow)
    return;
  var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
  e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}

The results shown here. DateTime Formatting

Skip to next iteration in loop vba

I use Goto

  For x= 1 to 20

       If something then goto continue

       skip this code

  Continue:

  Next x

How to subtract n days from current date in java?

this will subtract ten days of the current date (before Java 8):

int x = -10;
Calendar cal = GregorianCalendar.getInstance();
cal.add( Calendar.DAY_OF_YEAR, x);
Date tenDaysAgo = cal.getTime();

If you're using Java 8 you can make use of the new Date & Time API (http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html):

LocalDate tenDaysAgo = LocalDate.now().minusDays(10);

For converting the new to the old types and vice versa see: Converting between java.time.LocalDateTime and java.util.Date

How can I combine flexbox and vertical scroll in a full-height app?

Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.

The solution is setting a height to the vertical scrollable element. For example:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 0px;
}

The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px; that it is exactly the same as: min-height: 100px;

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 100px; /* == min-height: 100px*/
}

So the best solution if you want a min-height in the vertical scroll:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 100px;
}

If you just want full vertical scroll in case there is no enough space to see the article:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 0px;
}

The final code: http://jsfiddle.net/ch7n6/867/

Combining COUNT IF AND VLOOK UP EXCEL

Try this:

=IF(NOT(ISERROR(MATCH(A3,worksheet2!A:A,0))),COUNTIF(worksheet2!A:A,A3),"No Match Found")

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

iPhone SDK on Windows (alternative solutions)

No one has brought up the hackintosh. If you have supported hardware it might be the best option.

Associating existing Eclipse project with existing SVN repository

I'm asked this question very frequently, if it's smart to use "Share project..." if a eclipse project has been disconnected from it SVN counterpart in the repository. So, I append my answer to this thread.

The SVN-Team option "Share project ..." is totally fine for projects that exist in SVN and in your Eclipse workspace, even if the Eclipse project is missing the hidden .svn configuration. You can still connect them. Eclipse SVN-implementation (Subclipse/Subversive) will verify if the provided SVN http(s) source is populated. If yes, all existing files will be copied and linked (checked out in SVN terms) to your very personal Eclipse workspace.

Word of caution:

  • Do a backup if you depend on you local files. The SVN implementation may vary its behaviour with every release.
  • If you have multiple projects encapsulated within each other, make sure you point the SVN path to the correct local path.

regards, Feder

Difference between clean, gradlew clean

You can also use

./gradlew clean build (Mac and Linux) -With ./

gradlew clean build (Windows) -Without ./

it removes build folder, as well configure your modules and then build your project.

i use it before release any new app on playstore.

Solving Quadratic Equation

Below is the Program to Solve Quadratic Equation.

For Example: Solve x2 + 3x – 4 = 0

This quadratic happens to factor:

x2 + 3x – 4 = (x + 4)(x – 1) = 0

we already know that the solutions are x = –4 and x = 1.

enter image description here

    # import complex math module
    import cmath

    a = 1
    b = 5
    c = 6

    # To take coefficient input from the users
    # a = float(input('Enter a: '))
    # b = float(input('Enter b: '))
    # c = float(input('Enter c: '))

    # calculate the discriminant
    d = (b**2) - (4*a*c)

    # find two solutions
    sol1 = (-b-cmath.sqrt(d))/(2*a)
    sol2 = (-b+cmath.sqrt(d))/(2*a)

    print('The solution are {0} and {1}'.format(sol1,sol2))

Source: Python Program to Solve Quadratic Equation

nginx showing blank PHP pages

I had a similar error , but in combination with Nextcloud. So in case this did not work, try: Having a look at the Nginx manual.

What is the use of adding a null key or value to a HashMap in Java?

The answers so far only consider the worth of have a null key, but the question also asks about any number of null values.

The benefit of storing the value null against a key in a HashMap is the same as in databases, etc - you can record a distinction between having a value that is empty (e.g. string ""), and not having a value at all (null).

Program to find largest and second largest number in array

The question is ambiguous: if the array may contain duplicate values, are you supposed to find the 2 largest distinct values or the two largest possibly identical values?

Your code seems to indicate you want the first approach, but you have a problem if the largest value is a[0]. You should use an extra boolean to keep track of whether you have found a different value yet.

You should also test the return value of the different scanf() calls and return 0 from main().

Here is a modified version:

#include <stdio.h>

int main(void) {
    int a[10], n, i;
    int largest1, largest2, has_largest2;

    printf("enter number of elements you want in array: ");
    if (scanf("%d", &n) != 1)
        return 1;
    if (n < 2) {
        printf("need at least 2 elements\n");
        return 1;
    }
    printf("enter elements: ");
    for (i = 0; i < n; i++) {
        if (scanf("%d", &a[i]) != 1) {
            printf("input error\n");
            return 1;
        }
    }
    largest1 = a[0];
    for (i = 1; i < n; i++) {
        if (a[i] > largest1) {
            largest1 = a[i];
        }
    }
    has_largest2 = largest2 = 0;
    for (i = 0; i < n; i++) {
        if (a[i] < largest1) {
            if (!has_largest2) {
                has_largest2 = 1;
                largest2 = a[i];
            } else
            if (a[i] > largest2) {
                largest2 = a[i];
            }
        }
    }
    if (has_largest2) {
        printf("First and second largest number is %d and %d\n",
               largest1, largest2);
    } else {
        printf("All values are identical to %d\n", largest1);
    }
    return 0;
}

Docker-compose: node_modules not present in a volume after npm install succeeds

You can also ditch your Dockerfile, because of its simplicity, just use a basic image and specify the command in your compose file:

version: '3.2'

services:
  frontend:
    image: node:12-alpine
    volumes:
      - ./frontend/:/app/
    command: sh -c "cd /app/ && yarn && yarn run start"
    expose: [8080]
    ports:
      - 8080:4200

This is particularly useful for me, because I just need the environment of the image, but operate on my files outside the container and I think this is what you want to do too.

Where is svcutil.exe in Windows 7?

Type in the Microsoft Visual Studio Command Prompt: where svcutil.exe. On my machine it is in: C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\SvcUtil.exe

Given two directory trees, how can I find out which files differ by content?

You can also use Rsync and find. For find:

find $FOLDER -type f | cut -d/ -f2- | sort > /tmp/file_list_$FOLDER

But files with the same names and in the same subfolders, but with different content, will not be shown in the lists.

If you are a fan of GUI, you may check Meld that @Alexander mentioned. It works fine in both windows and linux.

Regular Expression to get a string between parentheses in Javascript

Alternative:

var str = "I expect five hundred dollars ($500) ($1).";
str.match(/\(.*?\)/g).map(x => x.replace(/[()]/g, ""));
? (2) ["$500", "$1"]

It is possible to replace brackets with square or curly brackets if you need

Declare an empty two-dimensional array in Javascript?

// for 3 x 5 array

new Array(3).fill(new Array(5).fill(0))

How to delete empty folders using windows command prompt?

It will be worked fine. This is best way to delete old files and remove empty directories recursively. following .bat file is,

forfiles /p [PATH] /s /m [FILE-PATTERN] /d -[DAYS] /c "cmd /c del @path"
for /f "delims=" %%d in ('dir [PATH] /s /b /ad ^| sort /r') do rd "%%d"

The placeholders needs to be replaced as follows (without the quotation marks):

[DAYS] = Max. age of the files in days, e.g. “10”
[PATH] = Path to search for old files and empty folders, e.g. “C:\Backup\”
[FILE-PATTERN] = Pattern that matches files to delete, e.g. “*.bkp”

The script has been successfully tested under Windows 7 and Windows Server 2003.

jQuery ui dialog change title after load-callback

An enhancement of the hacky idea by Nick Craver to put custom HTML in a jquery dialog title:

var newtitle= '<b>HTML TITLE</b>';
$(".selectorUsedToCreateTheDialog").parent().find("span.ui-dialog-title").html(newtitle);

Compile to a stand-alone executable (.exe) in Visual Studio

I've never had problems with deploying small console application made in C# as-is. The only problem you can bump into would be a dependency on the .NET framework, but even that shouldn't be a major problem. You could try using version 2.0 of the framework, which should already be on most PCs.

Using native, unmanaged C++, you should not have any dependencies on the .NET framework, so you really should be safe. Just grab the executable and any accompanying files (if there are any) and deploy them as they are; there's no need to install them if you don't want to.

How to open a web page from my application?

I've been using this line to launch the default browser:

System.Diagnostics.Process.Start("http://www.google.com"); 

How to enter quotes in a Java string?

In Java, you can use char value with ":

char quotes ='"';

String strVar=quotes+"ROM"+quotes;

Android Studio gradle takes too long to build

@AndroidDev solution worked for me. I had included the whole lib in gradle.

compile 'com.google.android.gms:play-services:8.4.0'

Changing to solved the problem. From 4 min to 1 min.

compile 'com.google.android.gms:play-services-ads:8.4.0'
compile 'com.google.android.gms:play-services-analytics:8.4.0'

Thnx

Why is it that "No HTTP resource was found that matches the request URI" here?

You need to map the unique route to specify your parameters as query elements. In RouteConfig.cs (or WebApiConfig.cs) add:

config.Routes.MapHttpRoute(
            name: "MyPagedQuery",
            routeTemplate:     "api/{controller}/{action}/{firstId}/{countToFetch}",
            defaults: new { action = "GetNDepartmentsFromID" }
        );

How to filter array when object key value is in array

In case you have key value pairs in your input array, I used:

.filter(
          this.multi_items[0] != null && store.state.isSearchBox === false
            ? item =>
                _.map(this.multi_items, "value").includes(item["wijknaam"])
            : item => item["wijknaam"].includes("")
        );

where the input array is multi_items as: [{"text": "bla1", "value": "green"}, {"text": etc. etc.}]

_.map is a lodash function.

How to stop EditText from gaining focus at Activity startup in Android

add below line in Manifest file where you have mentioned your activity

android:windowSoftInputMode="stateAlwaysHidden"

Setting button text via javascript

The value of a button element isn't the displayed text, contrary to what happens to input elements of type button.

You can do this :

 b.appendChild(document.createTextNode('test value'));

Demonstration

Can you do greater than comparison on a date in a Rails 3 search?

You can try to use:

where(date: p[:date]..Float::INFINITY)

equivalent in sql

WHERE (`date` >= p[:date])

The result is:

Note.where(user_id: current_user.id, notetype: p[:note_type], date: p[:date]..Float::INFINITY).order(:fecha, :created_at)

And I have changed too

order('date ASC, created_at ASC')

For

order(:fecha, :created_at)

Convert JS Object to form data

Recursively

_x000D_
_x000D_
const toFormData = (f => f(f))(h => f => f(x => h(h)(f)(x)))(f => fd => pk => d => {_x000D_
  if (d instanceof Object) {_x000D_
    Object.keys(d).forEach(k => {_x000D_
      const v = d[k]_x000D_
      if (pk) k = `${pk}[${k}]`_x000D_
      if (v instanceof Object && !(v instanceof Date) && !(v instanceof File)) {_x000D_
        return f(fd)(k)(v)_x000D_
      } else {_x000D_
        fd.append(k, v)_x000D_
      }_x000D_
    })_x000D_
  }_x000D_
  return fd_x000D_
})(new FormData())()_x000D_
_x000D_
let data = {_x000D_
  name: 'John',_x000D_
  age: 30,_x000D_
  colors: ['red', 'green', 'blue'],_x000D_
  children: [_x000D_
    { name: 'Max', age: 3 },_x000D_
    { name: 'Madonna', age: 10 }_x000D_
  ]_x000D_
}_x000D_
console.log('data', data)_x000D_
document.getElementById("data").insertAdjacentHTML('beforeend', JSON.stringify(data))_x000D_
_x000D_
let formData = toFormData(data)_x000D_
_x000D_
for (let key of formData.keys()) {_x000D_
  console.log(key, formData.getAll(key).join(','))_x000D_
  document.getElementById("item").insertAdjacentHTML('beforeend', `<li>${key} = ${formData.getAll(key).join(',')}</li>`)_x000D_
}
_x000D_
<p id="data"></p>_x000D_
<ul id="item"></ul>
_x000D_
_x000D_
_x000D_

Functional, Declarative, and Imperative Programming

At the time of writing this, the top voted answers on this page are imprecise and muddled on the declarative vs. imperative definition, including the answer that quotes Wikipedia. Some answers are conflating the terms in different ways.

Refer also to my explanation of why spreadsheet programming is declarative, regardless that the formulas mutate the cells.

Also, several answers claim that functional programming must be a subset of declarative. On that point it depends if we differentiate "function" from "procedure". Lets handle imperative vs. declarative first.

Definition of declarative expression

The only attribute that can possibly differentiate a declarative expression from an imperative expression is the referential transparency (RT) of its sub-expressions. All other attributes are either shared between both types of expressions, or derived from the RT.

A 100% declarative language (i.e. one in which every possible expression is RT) does not (among other RT requirements) allow the mutation of stored values, e.g. HTML and most of Haskell.

Definition of RT expression

RT is often referred to as having "no side-effects". The term effects does not have a precise definition, so some people don't agree that "no side-effects" is the same as RT. RT has a precise definition:

An expression e is referentially transparent if for all programs p every occurrence of e in p can be replaced with the result of evaluating e, without affecting the observable result of p.

Since every sub-expression is conceptually a function call, RT requires that the implementation of a function (i.e. the expression(s) inside the called function) may not access the mutable state that is external to the function (accessing the mutable local state is allowed). Put simply, the function (implementation) should be pure.

Definition of pure function

A pure function is often said to have "no side-effects". The term effects does not have a precise definition, so some people don't agree.

Pure functions have the following attributes.

  • the only observable output is the return value.
  • the only output dependency is the arguments.
  • arguments are fully determined before any output is generated.

Remember that RT applies to expressions (which includes function calls) and purity applies to (implementations of) functions.

An obscure example of impure functions that make RT expressions is concurrency, but this is because the purity is broken at the interrupt abstraction layer. You don't really need to know this. To make RT expressions, you call pure functions.

Derivative attributes of RT

Any other attribute cited for declarative programming, e.g. the citation from 1999 used by Wikipedia, either derives from RT, or is shared with imperative programming. Thus proving that my precise definition is correct.

Note, immutability of external values is a subset of the requirements for RT.

  • Declarative languages don't have looping control structures, e.g. for and while, because due to immutability, the loop condition would never change.

  • Declarative languages don't express control-flow other than nested function order (a.k.a logical dependencies), because due to immutability, other choices of evaluation order do not change the result (see below).

  • Declarative languages express logical "steps" (i.e. the nested RT function call order), but whether each function call is a higher level semantic (i.e. "what to do") is not a requirement of declarative programming. The distinction from imperative is that due to immutability (i.e. more generally RT), these "steps" cannot depend on mutable state, rather only the relational order of the expressed logic (i.e. the order of nesting of the function calls, a.k.a. sub-expressions).

For example, the HTML paragraph <p> cannot be displayed until the sub-expressions (i.e. tags) in the paragraph have been evaluated. There is no mutable state, only an order dependency due to the logical relationship of tag hierarchy (nesting of sub-expressions, which are analogously nested function calls).

  • Thus there is the derivative attribute of immutability (more generally RT), that declarative expressions, express only the logical relationships of the constituent parts (i.e. of the sub-expression function arguments) and not mutable state relationships.

Evaluation order

The choice of evaluation order of sub-expressions can only give a varying result when any of the function calls are not RT (i.e. the function is not pure), e.g. some mutable state external to a function is accessed within the function.

For example, given some nested expressions, e.g. f( g(a, b), h(c, d) ), eager and lazy evaluation of the function arguments will give the same results if the functions f, g, and h are pure.

Whereas, if the functions f, g, and h are not pure, then the choice of evaluation order can give a different result.

Note, nested expressions are conceptually nested functions, since expression operators are just function calls masquerading as unary prefix, unary postfix, or binary infix notation.

Tangentially, if all identifiers, e.g. a, b, c, d, are immutable everywhere, state external to the program cannot be accessed (i.e. I/O), and there is no abstraction layer breakage, then functions are always pure.

By the way, Haskell has a different syntax, f (g a b) (h c d).

Evaluation order details

A function is a state transition (not a mutable stored value) from the input to the output. For RT compositions of calls to pure functions, the order-of-execution of these state transitions is independent. The state transition of each function call is independent of the others, due to lack of side-effects and the principle that an RT function may be replaced by its cached value. To correct a popular misconception, pure monadic composition is always declarative and RT, in spite of the fact that Haskell's IO monad is arguably impure and thus imperative w.r.t. the World state external to the program (but in the sense of the caveat below, the side-effects are isolated).

Eager evaluation means the functions arguments are evaluated before the function is called, and lazy evaluation means the arguments are not evaluated until (and if) they are accessed within the function.

Definition: function parameters are declared at the function definition site, and function arguments are supplied at the function call site. Know the difference between parameter and argument.

Conceptually, all expressions are (a composition of) function calls, e.g. constants are functions without inputs, unary operators are functions with one input, binary infix operators are functions with two inputs, constructors are functions, and even control statements (e.g. if, for, while) can be modeled with functions. The order that these argument functions (do not confuse with nested function call order) are evaluated is not declared by the syntax, e.g. f( g() ) could eagerly evaluate g then f on g's result or it could evaluate f and only lazily evaluate g when its result is needed within f.

Caveat, no Turing complete language (i.e. that allows unbounded recursion) is perfectly declarative, e.g. lazy evaluation introduces memory and time indeterminism. But these side-effects due to the choice of evaluation order are limited to memory consumption, execution time, latency, non-termination, and external hysteresis thus external synchronization.

Functional programming

Because declarative programming cannot have loops, then the only way to iterate is functional recursion. It is in this sense that functional programming is related to declarative programming.

But functional programming is not limited to declarative programming. Functional composition can be contrasted with subtyping, especially with respect to the Expression Problem, where extension can be achieved by either adding subtypes or functional decomposition. Extension can be a mix of both methodologies.

Functional programming usually makes the function a first-class object, meaning the function type can appear in the grammar anywhere any other type may. The upshot is that functions can input and operate on functions, thus providing for separation-of-concerns by emphasizing function composition, i.e. separating the dependencies among the subcomputations of a deterministic computation.

For example, instead of writing a separate function (and employing recursion instead of loops if the function must also be declarative) for each of an infinite number of possible specialized actions that could be applied to each element of a collection, functional programming employs reusable iteration functions, e.g. map, fold, filter. These iteration functions input a first-class specialized action function. These iteration functions iterate the collection and call the input specialized action function for each element. These action functions are more concise because they no longer need to contain the looping statements to iterate the collection.

However, note that if a function is not pure, then it is really a procedure. We can perhaps argue that functional programming that uses impure functions, is really procedural programming. Thus if we agree that declarative expressions are RT, then we can say that procedural programming is not declarative programming, and thus we might argue that functional programming is always RT and must be a subset of declarative programming.

Parallelism

This functional composition with first-class functions can express the depth in the parallelism by separating out the independent function.

Brent’s Principle: computation with work w and depth d can be implemented in a p-processor PRAM in time O(max(w/p, d)).

Both concurrency and parallelism also require declarative programming, i.e. immutability and RT.

So where did this dangerous assumption that Parallelism == Concurrency come from? It’s a natural consequence of languages with side-effects: when your language has side-effects everywhere, then any time you try to do more than one thing at a time you essentially have non-determinism caused by the interleaving of the effects from each operation. So in side-effecty languages, the only way to get parallelism is concurrency; it’s therefore not surprising that we often see the two conflated.

FP evaluation order

Note the evaluation order also impacts the termination and performance side-effects of functional composition.

Eager (CBV) and lazy (CBN) are categorical duels[10], because they have reversed evaluation order, i.e. whether the outer or inner functions respectively are evaluated first. Imagine an upside-down tree, then eager evaluates from function tree branch tips up the branch hierarchy to the top-level function trunk; whereas, lazy evaluates from the trunk down to the branch tips. Eager doesn't have conjunctive products ("and", a/k/a categorical "products") and lazy doesn't have disjunctive coproducts ("or", a/k/a categorical "sums")[11].

Performance

  • Eager

As with non-termination, eager is too eager with conjunctive functional composition, i.e. compositional control structure does unnecessary work that isn't done with lazy. For example, eager eagerly and unnecessarily maps the entire list to booleans, when it is composed with a fold that terminates on the first true element.

This unnecessary work is the cause of the claimed "up to" an extra log n factor in the sequential time complexity of eager versus lazy, both with pure functions. A solution is to use functors (e.g. lists) with lazy constructors (i.e. eager with optional lazy products), because with eager the eagerness incorrectness originates from the inner function. This is because products are constructive types, i.e. inductive types with an initial algebra on an initial fixpoint[11]

  • Lazy

As with non-termination, lazy is too lazy with disjunctive functional composition, i.e. coinductive finality can occur later than necessary, resulting in both unnecessary work and non-determinism of the lateness that isn't the case with eager[10][11]. Examples of finality are state, timing, non-termination, and runtime exceptions. These are imperative side-effects, but even in a pure declarative language (e.g. Haskell), there is state in the imperative IO monad (note: not all monads are imperative!) implicit in space allocation, and timing is state relative to the imperative real world. Using lazy even with optional eager coproducts leaks "laziness" into inner coproducts, because with lazy the laziness incorrectness originates from the outer function (see the example in the Non-termination section, where == is an outer binary operator function). This is because coproducts are bounded by finality, i.e. coinductive types with a final algebra on an final object[11].

Lazy causes indeterminism in the design and debugging of functions for latency and space, the debugging of which is probably beyond the capabilities of the majority of programmers, because of the dissonance between the declared function hierarchy and the runtime order-of-evaluation. Lazy pure functions evaluated with eager, could potentially introduce previously unseen non-termination at runtime. Conversely, eager pure functions evaluated with lazy, could potentially introduce previously unseen space and latency indeterminism at runtime.

Non-termination

At compile-time, due to the Halting problem and mutual recursion in a Turing complete language, functions can't generally be guaranteed to terminate.

  • Eager

With eager but not lazy, for the conjunction of Head "and" Tail, if either Head or Tail doesn't terminate, then respectively either List( Head(), Tail() ).tail == Tail() or List( Head(), Tail() ).head == Head() is not true because the left-side doesn't, and right-side does, terminate.

Whereas, with lazy both sides terminate. Thus eager is too eager with conjunctive products, and non-terminates (including runtime exceptions) in those cases where it isn't necessary.

  • Lazy

With lazy but not eager, for the disjunction of 1 "or" 2, if f doesn't terminate, then List( f ? 1 : 2, 3 ).tail == (f ? List( 1, 3 ) : List( 2, 3 )).tail is not true because the left-side terminates, and right-side doesn't.

Whereas, with eager neither side terminates so the equality test is never reached. Thus lazy is too lazy with disjunctive coproducts, and in those cases fails to terminate (including runtime exceptions) after doing more work than eager would have.

[10] Declarative Continuations and Categorical Duality, Filinski, sections 2.5.4 A comparison of CBV and CBN, and 3.6.1 CBV and CBN in the SCL.

[11] Declarative Continuations and Categorical Duality, Filinski, sections 2.2.1 Products and coproducts, 2.2.2 Terminal and initial objects, 2.5.2 CBV with lazy products, and 2.5.3 CBN with eager coproducts.

The calling thread cannot access this object because a different thread owns it

For some reason Candide's answer didn't build. It was helpful, though, as it led me to find this, which worked perfectly:

System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke((Action)(() =>
{
   //your code here...
}));

how to read all files inside particular folder

using System.IO;
...
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
    string contents = File.ReadAllText(file);
}

Note the above uses a .NET 4.0 feature; in previous versions replace EnumerateFiles with GetFiles). Also, replace File.ReadAllText with your preferred way of reading xml files - perhaps XDocument, XmlDocument or an XmlReader.

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

In my case my Build Tools version in my build.gradle for the app module was outdated on an old project. Updating it fixed the issue:

android {
    ...
    buildToolsVersion "19.0.1"
    ...

Updated to the latest build tools version (25.0.1) and sync'd the project and all was well again.

Can you 'exit' a loop in PHP?

You can use the break keyword.

How do I automatically resize an image for a mobile site?

img
{
    max-width: 100%;
    min-width: 300px;
    height: auto;
}

RecyclerView onClick

For kotlin handle click on recyclerview anser based on Jacobs anser

kotlin RecyclerViewClick #RecyclerViewClick # Kotlin

1) CREATE CLASS RecyclerItemClickListener

class RecyclerItemClickListener(context: Context, recyclerView: RecyclerView, listner: OnItemClickListener) : RecyclerView.OnItemTouchListener {
    var mGestureDetector: GestureDetector
    var mListner: OnItemClickListener
    interface OnItemClickListener {
        fun onItemClick(view: View, position: Int)
        fun onLongItemClick(view: View, position: Int)
    }
    init {
        this.mListner = listner
        mGestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
            override fun onSingleTapUp(e: MotionEvent?): Boolean {
                return true
            }
            override fun onLongPress(e: MotionEvent?) {
                val child: View? = recyclerView.findChildViewUnder(e!!.getX(), e.getY())
                if (child != null && mListner != null) {
                    mListner.onLongItemClick(child, recyclerView.getChildAdapterPosition(child))
                }

            }

        })
    }
    override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
    }

    override fun onInterceptTouchEvent(view: RecyclerView, e: MotionEvent): Boolean {
        val childView: View? = view.findChildViewUnder(e!!.getX(), e.getY())
        if (childView != null && mListner != null && mGestureDetector.onTouchEvent(e)) {
            mListner.onItemClick(childView, view.getChildAdapterPosition(childView))
            return true
        }
        return false
    }

    override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
    }

}

2) get Click on Any Recyclerview (activity/fragment)

 recyclerView.addOnItemTouchListener(
            RecyclerItemClickListener(
                this, recyclerView, object : RecyclerItemClickListener.OnItemClickListener {
                    override fun onItemClick(view: View, position: Int) {

                    }

                    override fun onLongItemClick(view: View, position: Int) {
                    }
                })
        )

Setting environment variables on OS X

On Mountain Lion all the /etc/paths and /etc/launchd.conf editing doesn't make any effect!

Apple's Developer Forums say:

"Change the Info.plist of the .app itself to contain an "LSEnvironment" dictionary with the environment variables you want.

~/.MacOSX/environment.plist is no longer supported."

So I directly edited the application's Info.plist (right click on "AppName.app" (in this case SourceTree) and then "Show package contents").

Show Package Contents

And I added a new key/dict pair called:

<key>LSEnvironment</key>
<dict>
     <key>PATH</key>
     <string>/Users/flori/.rvm/gems/ruby-1.9.3-p362/bin:/Users/flori/.rvm/gems/ruby-1.9.3-p362@global/bin:/Users/flori/.rvm/rubies/ruby-1.9.3-p326/bin:/Users/flori/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:</string>
</dict>

(see: LaunchServicesKeys Documentation at Apple)

Enter image description here

Now the application (in my case Sourcetree) uses the given path and works with Git 1.9.3 :-)

PS: Of course you have to adjust the Path entry to your specific path needs.

What is the JavaScript version of sleep()?

In JavaScript, I rewrite every function so that it can end as soon as possible. You want the browser back in control so it can make your DOM changes.

Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout().

Edit

The infamous sleep, or delay, function within any language is much debated. Some will say that there should always be a signal or callback to fire a given functionality, others will argue that sometimes an arbitrary moment of delay is useful. I say that to each their own and one rule can never dictate anything in this industry.

Writing a sleep function is simple and made even more usable with JavaScript Promises:

// sleep time expects milliseconds
function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

// Usage!
sleep(500).then(() => {
    // Do something after the sleep!
});

javascript object max size limit

There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.

The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.

To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.

Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:

var items = $.map(keys, function(item, i) {
  var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
  return
    '{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
    '" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
});
var jsonObj =
  '{"code":"' + code + '",'+
  '"defaultfile":"' + defaultfile + '",'+
  '"filename":"' + currentFile + '",'+
  '"lstResDef":[' + items.join(',') + ']}';

Strange Jackson exception being thrown when serializing Hibernate object

You can use jackson-datatype-hibernate module to solve this problem. It work for me. reference: https://github.com/FasterXML/jackson-datatype-hibernate

How do I break out of a loop in Perl?

Oh, I found it. You use last instead of break

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

Exporting the values in List to excel

I know, I am late to this party, however I think it could be helpful for others.

Already posted answers are for csv and other one is by Interop dll where you need to install excel over the server, every approach has its own pros and cons. Here is an option which will give you

  1. Perfect excel output [not csv]
  2. With perfect excel and your data type match
  3. Without excel installation
  4. Pass list and get Excel output :)

you can achieve this by using NPOI DLL, available for both .net as well as for .net core

Steps :

  1. Import NPOI DLL
  2. Add Section 1 and 2 code provided below
  3. Good to go

Section 1

This code performs below task :

  1. Creating New Excel object - _workbook = new XSSFWorkbook();
  2. Creating New Excel Sheet object - _sheet =_workbook.CreateSheet(_sheetName);
  3. Invokes WriteData() - explained later Finally, creating and
  4. returning MemoryStream object

=============================================================================

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

namespace GenericExcelExport.ExcelExport
{
    public interface IAbstractDataExport
    {
        HttpResponseMessage Export(List exportData, string fileName, string sheetName);
    }

    public abstract class AbstractDataExport : IAbstractDataExport
    {
        protected string _sheetName;
        protected string _fileName;
        protected List _headers;
        protected List _type;
        protected IWorkbook _workbook;
        protected ISheet _sheet;
        private const string DefaultSheetName = "Sheet1";

        public HttpResponseMessage Export
              (List exportData, string fileName, string sheetName = DefaultSheetName)
        {
            _fileName = fileName;
            _sheetName = sheetName;

            _workbook = new XSSFWorkbook(); //Creating New Excel object
            _sheet = _workbook.CreateSheet(_sheetName); //Creating New Excel Sheet object

            var headerStyle = _workbook.CreateCellStyle(); //Formatting
            var headerFont = _workbook.CreateFont();
            headerFont.IsBold = true;
            headerStyle.SetFont(headerFont);

            WriteData(exportData); //your list object to NPOI excel conversion happens here

            //Header
            var header = _sheet.CreateRow(0);
            for (var i = 0; i < _headers.Count; i++)
            {
                var cell = header.CreateCell(i);
                cell.SetCellValue(_headers[i]);
                cell.CellStyle = headerStyle;
            }

            for (var i = 0; i < _headers.Count; i++)
            {
                _sheet.AutoSizeColumn(i);
            }

            using (var memoryStream = new MemoryStream()) //creating memoryStream
            {
                _workbook.Write(memoryStream);
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(memoryStream.ToArray())
                };

                response.Content.Headers.ContentType = new MediaTypeHeaderValue
                       ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.Content.Headers.ContentDisposition = 
                       new ContentDispositionHeaderValue("attachment")
                {
                    FileName = $"{_fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
                };

                return response;
            }
        }

        //Generic Definition to handle all types of List
        public abstract void WriteData(List exportData);
    }
}

=============================================================================

Section 2

In section 2, we will be performing below steps :

  1. Converts List to DataTable Reflection to read property name, your
  2. Column header will be coming from here
  3. Loop through DataTable to Create excel Rows

=============================================================================

using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text.RegularExpressions;

namespace GenericExcelExport.ExcelExport
{
    public class AbstractDataExportBridge : AbstractDataExport
    {
        public AbstractDataExportBridge()
        {
            _headers = new List<string>();
            _type = new List<string>();
        }

        public override void WriteData<T>(List<T> exportData)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

            DataTable table = new DataTable();

            foreach (PropertyDescriptor prop in properties)
            {
                var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                _type.Add(type.Name);
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? 
                                  prop.PropertyType);
                string name = Regex.Replace(prop.Name, "([A-Z])", " $1").Trim(); //space separated 
                                                                           //name by caps for header
                _headers.Add(name);
            }

            foreach (T item in exportData)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }

            IRow sheetRow = null;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                sheetRow = _sheet.CreateRow(i + 1);
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    ICell Row1 = sheetRow.CreateCell(j);

                    string type = _type[j].ToLower();
                    var currentCellValue = table.Rows[i][j];

                    if (currentCellValue != null && 
                        !string.IsNullOrEmpty(Convert.ToString(currentCellValue)))
                    {
                        if (type == "string")
                        {
                            Row1.SetCellValue(Convert.ToString(currentCellValue));
                        }
                        else if (type == "int32")
                        {
                            Row1.SetCellValue(Convert.ToInt32(currentCellValue));
                        }
                        else if (type == "double")
                        {
                            Row1.SetCellValue(Convert.ToDouble(currentCellValue));
                        }
                    }
                    else
                    {
                        Row1.SetCellValue(string.Empty);
                    }
                }
            }
        }
    }
}

=============================================================================

Now you just need to call WriteData() function by passing your list, and it will provide you your excel.

I have tested it in WEB API and WEB API Core, works like a charm.

Passing a String by Reference in Java?

java.lang.String is immutable.

I hate pasting URLs but https://docs.oracle.com/javase/10/docs/api/java/lang/String.html is essential for you to read and understand if you're in java-land.

How to flush output of print function?

Also as suggested in this blog one can reopen sys.stdout in unbuffered mode:

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Each stdout.write and print operation will be automatically flushed afterwards.

Inheriting constructors

How about using a template function to bind all constructors?

template <class... T> Derived(T... t) : Base(t...) {}

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

How to create named and latest tag in Docker?

Here is my bash script

docker build -t ${IMAGE}:${VERSION} .
docker tag ${IMAGE}:${VERSION} ${IMAGE}:latest

You can then remove untagged images if you rebuilt the same version with

docker rmi $(docker images | grep "^<none>" | awk "{print $3}")

link

or

docker rmi $(docker images | grep "^<none>" | tr -s " " | cut -d' ' -f3 | tr '\n' ' ')

or

Clean up commands:

Docker 1.13 introduces clean-up commands. To remove all unused containers, images, networks and volumes:

docker system prune

or individually:

docker container prune
docker image prune
docker network prune
docker volume prune

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I had the same problem on Windows XP just recently. I tried to chmod 700 on my ~/.ssh/id_rsa file but it did not seem to work. When I had a look at the permissions using ls -l on the ~/.ssh/id_rsa I could see that my effective permissions still was 644.

Then I remembered that windows permissions also inherit permissions from the folders, and the folder was still open to everyone. A solution could be to set permissions for the folder as well, but I think a better way would be to tell the system to ignore inheritance for this file. This can be done using the advanced option on the security tab in the properties of the file, and unchecking "inherit from parent permissions..."

This might be helpful for others with the same problem.

Running a cron job at 2:30 AM everyday

crontab -e

add:

30 2 * * * /your/command

How to kill a running SELECT statement

This is what I use. I do this first query to find the sessions and the users:

select s.sid, s.serial#, p.spid, s.username, s.schemaname
     , s.program, s.terminal, s.osuser
  from v$session s
  join v$process p
    on s.paddr = p.addr
 where s.type != 'BACKGROUND';

This will let me know if there are multiple sessions for the same user. Then I usually check to verify if a session is blocking the database.

SELECT SID, SQL_ID, USERNAME, BLOCKING_SESSION, COMMAND, MODULE, STATUS FROM v$session WHERE BLOCKING_SESSION IS NOT NULL;  

Then I run an ALTER statement to kill a specific session in this format:

ALTER SYSTEM KILL SESSION 'sid,serial#'; 

For example:

ALTER SYSTEM KILL SESSION '314, 2643';

How do I select a sibling element using jQuery?

$(this).siblings(".bidbutton")

How to create a foreign key in phpmyadmin

To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab. Storage Engine Configuration

Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.

Index list

Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.

enter image description here

See attachments. I hope this could be useful for anyone.

JSON: why are forward slashes escaped?

Ugly PHP!

The JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES must be default, not an (strange) option... How to say it to php-developers?

The default MUST be the most frequent use, and the (current) most widely used standards as UTF8. How many PHP-code fragments in the Github or other place need this exoctic "embedded in HTML" feature?

How can I use the apply() function for a single column?

If you are really concerned about the execution speed of your apply function and you have a huge dataset to work on, you could use swifter to make faster execution, here is an example for swifter on pandas dataframe:

import pandas as pd
import swifter

def fnc(m):
    return m*3+4

df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})

# apply a self created function to a single column in pandas
df["y"] = df.m.swifter.apply(fnc)

This will enable your all CPU cores to compute the result hence it will be much faster than normal apply functions. Try and let me know if it become useful for you.

JSONResult to String

json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";            
return new MemoryStream(Encoding.UTF8.GetBytes(json));

Angular: How to download a file from HttpClient?

After spending much time searching for a response to this answer: how to download a simple image from my API restful server written in Node.js into an Angular component app, I finally found a beautiful answer in this web Angular HttpClient Blob. Essentially it consist on:

API Node.js restful:

   /* After routing the path you want ..*/
  public getImage( req: Request, res: Response) {

    // Check if file exist...
    if (!req.params.file) {
      return res.status(httpStatus.badRequest).json({
        ok: false,
        msg: 'File param not found.'
      })
    }
    const absfile = path.join(STORE_ROOT_DIR,IMAGES_DIR, req.params.file);

    if (!fs.existsSync(absfile)) {
      return res.status(httpStatus.badRequest).json({
        ok: false,
        msg: 'File name not found on server.'
      })
    }
    res.sendFile(path.resolve(absfile));
  }

Angular 6 tested component service (EmployeeService on my case):

  downloadPhoto( name: string) : Observable<Blob> {
    const url = environment.api_url + '/storer/employee/image/' + name;

    return this.http.get(url, { responseType: 'blob' })
      .pipe(
        takeWhile( () => this.alive),
        filter ( image => !!image));
  }

Template

 <img [src]="" class="custom-photo" #photo>

Component subscriber and use:

@ViewChild('photo') image: ElementRef;

public LoadPhoto( name: string) {
    this._employeeService.downloadPhoto(name)
          .subscribe( image => {
            const url= window.URL.createObjectURL(image);
            this.image.nativeElement.src= url;
          }, error => {
            console.log('error downloading: ', error);
          })    
}

How to copy and edit files in Android shell?

You can do it without root permissions:

cat srcfile > /mnt/sdcard/dstfile

How can I center text (horizontally and vertically) inside a div block?

_x000D_
_x000D_
.cell-row {display: table; width: 100%; height: 100px; background-color: lightgrey; text-align: center}_x000D_
.cell {display: table-cell}_x000D_
.cell-middle {vertical-align: middle}
_x000D_
<div class="cell-row">_x000D_
  <div class="cell cell-middle">Center</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to pass parameters using ui-sref in ui-router to controller

You don't necessarily need to have the parameters inside the URL.

For instance, with:

$stateProvider
.state('home', {
  url: '/',
  views: {
    '': {
      templateUrl: 'home.html',
      controller: 'MainRootCtrl'

    },
  },
  params: {
    foo: null,
    bar: null
  }
})

You will be able to send parameters to the state, using either:

$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>

Of course, if you reload the page once on the home state, you will loose the state parameters, as they are not stored anywhere.

A full description of this behavior is documented here, under the params row in the state(name, stateConfig) section.

Node.js: Gzip compression?

Even if you're not using express, you can still use their middleware. The compression module is what I'm using:

var http = require('http')
var fs = require('fs')
var compress = require("compression")
http.createServer(function(request, response) {
  var noop = function(){}, useDefaultOptions = {}
  compress(useDefaultOptions)(request,response,noop) // mutates the response object

  response.writeHead(200)
  fs.createReadStream('index.html').pipe(response)
}).listen(1337)

Clearing _POST array fully

You can use a combination of both unset() and initialization:

unset($_POST);
$_POST = array();

Or in a single statement:

unset($_POST) ? $_POST = array() : $_POST = array();

But what is the reason you want to do this?

How can I recover the return value of a function passed to multiprocessing.Process?

Use shared variable to communicate. For example like this:

import multiprocessing


def worker(procnum, return_dict):
    """worker function"""
    print(str(procnum) + " represent!")
    return_dict[procnum] = procnum


if __name__ == "__main__":
    manager = multiprocessing.Manager()
    return_dict = manager.dict()
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i, return_dict))
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()
    print(return_dict.values())

MySql server startup error 'The server quit without updating PID file '

I recently came across this issue, however it was working before, then stopped.

This was because I initially started mysql.server as root instead of myself.

The fix was to delete the err log file (which was owned by _mysql). Starting it again got it passed.

app.config for a class library

You do want to add App.config to your tests class library, if you're using a tracer/logger. Otherwise nothing gets logged when you run the test through a test runner such as TestDriven.Net.

For example, I use TraceSource in my programs, but running tests doesn't log anything unless I add an App.config file with the trace/log configuration to the test class library too.

Otherwise, adding App.config to a class library doesn't do anything.

How to output an Excel *.xls file from classic ASP

You can always just export the HTML table to an XLS document. Excel does a pretty good job understanding HTML tables.

Another possiblitly is to export the HTML tables as a CSV or TSV file, but you would need to setup the formatting in your code. This isn't too difficult to accomplish.

There's some classes in the Microsoft.Office.Interop that allow you to create an Excel file programatically, but I have always found them to be a little clumsy. You can find a .NET version of creating a spreadsheet here, which should be pretty easy to modify for classic ASP.

As for .NET, I've always liked CarlosAG's Excel XML Writer Library. It has a nice generator so you can setup your Excel file, save it as an XML spreadsheet and it generates the code to do all the formatting and everything. I know it's not classic ASP, but I thought that I would throw it out there.


With what you're trying above, try adding the header:

"Content-Disposition", "attachment; filename=excelTest.xls"

See if that works. Also, I always use this for the content type:

  Response.ContentType = "application/octet-stream"
    Response.ContentType = "application/vnd.ms-excel"

JavaScript/jQuery to download file via POST with JSON data

I've been playing around with another option that uses blobs. I've managed to get it to download text documents, and I've downloaded PDF's (However they are corrupted).

Using the blob API you will be able to do the following:

$.post(/*...*/,function (result)
{
    var blob=new Blob([result]);
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="myFileName.txt";
    link.click();

});

This is IE 10+, Chrome 8+, FF 4+. See https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL

It will only download the file in Chrome, Firefox and Opera. This uses a download attribute on the anchor tag to force the browser to download it.

How to create an Array with AngularJS's ng-model

First thing is first. You need to define $scope.telephone as an array in your controller before you can start using it in your view.

$scope.telephone = [];

To address the issue of ng-model not being recognised when you append a new input - for that to work you have to use the $compile Angular service.

From the Angular.js API reference on $compile:

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

// I'm using Angular syntax. Using jQuery will have the same effect
// Create input element
var input = angular.element('<div><input type="text" ng-model="telephone[' + $scope.inputCounter + ']"></div>');
// Compile the HTML and assign to scope
var compile = $compile(input)($scope);

Have a look on JSFiddle

How do I view the Explain Plan in Oracle Sql developer?

We use Oracle PL/SQL Developer(Version 12.0.7). And we use F5 button to view the explain plan.

js window.open then print()

As most of browsers has been updated, So print and close do not any more as It worked before. So you should add onafterprint event listener in order to close print window.

    var printWindow = window.open('https://stackoverflow.com/');
    printWindow.print();

    //Close window once print is finished
    printWindow.onafterprint = function(){
       printWindow.close()
    };

Play local (hard-drive) video file with HTML5 video tag?

Ran in to this problem a while ago. Website couldn't access video file on local PC due to security settings (understandable really) ONLY way I could get around it was to run a webserver on the local PC (server2Go) and all references to the video file from the web were to the localhost/video.mp4

<div id="videoDiv">
     <video id="video" src="http://127.0.0.1:4001/videos/<?php $videoFileName?>" width="70%" controls>
    </div>
<!--End videoDiv-->

Not an ideal solution but worked for me.

How can I update window.location.hash without jumping the document?

This solution worked for me

// store the currently selected tab in the hash value
    if(history.pushState) {
        window.history.pushState(null, null, '#' + id);
    }
    else {
        window.location.hash = id;
    }

// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');

And my full js code is

$('#myTab a').click(function(e) {
  e.preventDefault();
  $(this).tab('show');
});

// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
  var id = $(e.target).attr("href").substr(1);
    if(history.pushState) {
        window.history.pushState(null, null, '#' + id);
    }
    else {
        window.location.hash = id;
    }
   // window.location.hash = '#!' + id;
});

// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
// console.log(hash);
$('#myTab a[href="' + hash + '"]').tab('show');

docker run <IMAGE> <MULTIPLE COMMANDS>

You can do this a couple of ways:

  1. Use the -w option to change the working directory:

    -w, --workdir="" Working directory inside the container

    https://docs.docker.com/engine/reference/commandline/run/#set-working-directory--w

  2. Pass the entire argument to /bin/bash:

    docker run image /bin/bash -c "cd /path/to/somewhere; python a.py"
    

Difference between readFile() and readFileSync()

'use strict'
var fs = require("fs");

/***
 * implementation of readFileSync
 */
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");

/***
 * implementation of readFile 
 */
fs.readFile('input.txt', function (err, data) {
    if (err) return console.error(err);
   console.log(data.toString());
});

console.log("Program Ended");

For better understanding run the above code and compare the results..

How to create an ArrayList from an Array in PowerShell?

I can't get that constructor to work either. This however seems to work:

# $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)

You can also pass an integer in the constructor to set an initial capacity.

What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?

Edit:

It seems that you can use the array constructor like this:

$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)

Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.

Simplest JQuery validation rules example

The examples contained in this blog post do the trick.

Firebase FCM notifications click_action payload

there is dual method for fcm fcm messaging notification and app notification in first your app reciever only message notification with body ,title and you can add color ,vibration not working,sound default. in 2nd you can full control what happen when you recieve message example onMessageReciever(RemoteMessage rMessage){ notification.setContentTitle(rMessage.getData().get("yourKey")); } you will recieve data with(yourKey) but that not from fcm message that from fcm cloud functions reguard

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

Thank you "Rob"....I had same problem with UICollectionView and your answer help me to solved my problem. Here is my code :

 if ([Dict valueForKey:@"ImageURL"] != [NSNull null])
    {
        cell.coverImageView.image = nil;
        cell.coverImageView.imageURL=nil;

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            if ([Dict valueForKey:@"ImageURL"] != [NSNull null] )
            {
                dispatch_async(dispatch_get_main_queue(), ^{

                    myCell *updateCell = (id)[collectionView cellForItemAtIndexPath:indexPath];

                    if (updateCell)
                    {
                        cell.coverImageView.image = nil;
                        cell.coverImageView.imageURL=nil;

                        cell.coverImageView.imageURL=[NSURL URLWithString:[Dict valueForKey:@"ImageURL"]];

                    }
                    else
                    {
                        cell.coverImageView.image = nil;
                        cell.coverImageView.imageURL=nil;
                    }


                });
            }
        });

    }
    else
    {
        cell.coverImageView.image=[UIImage imageNamed:@"default_cover.png"];
    }

How to remove old and unused Docker images

There is sparrow plugin docker-remove-dangling-images you can use to clean up stopped containers and unused (dangling) images:

$ sparrow plg run docker-remove-dangling-images

It works both for Linux and Windows OS.

Which Eclipse version should I use for an Android app?

Get the full Android-SDK plus the dependencies at http://developer.android.com/sdk/index.html.

Do have Java installed :)

Make a dictionary with duplicate keys in Python

You can't have a dict with duplicate keys for definition! Instead you can use a single key and, as value, a list of elements that had that key.

So you can follow these steps:

  1. See if the current element's (of your initial set) key is in the final dict. If it is, go to step 3
  2. Update dict with key
  3. Append the new value to the dict[key] list
  4. Repeat [1-3]

The request failed or the service did not respond in a timely fashion?

If you are running SQL Server in a local environment and not over a TCP/IP connection. Go to Protocols under SQL Server Configuration Manager, Properties, and disable TCP/IP. Once this is done then the error message will go away when restarting the service.

How can I search for a commit message on GitHub?

Update (2017/01/05):

GitHub has published an update that allows you now to search within commit messages from within their UI. See blog post for more information.


I had the same question and contacted someone GitHub yesterday:

Since they switched their search engine to Elasticsearch it's not possible to search for commit messages using the GitHub UI. But that feature is on the team's wishlist.

Unfortunately there's no release date for that function right now.

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

You can also try turning off the SSL option in settings, in case you are sending it through POSTMAN

Find which commit is currently checked out in Git

You have at least 5 different ways to view the commit you currently have checked out into your working copy during a git bisect session (note that options 1-4 will also work when you're not doing a bisect):

  1. git show.
  2. git log -1.
  3. Bash prompt.
  4. git status.
  5. git bisect visualize.

I'll explain each option in detail below.

Option 1: git show

As explained in this answer to the general question of how to determine which commit you currently have checked-out (not just during git bisect), you can use git show with the -s option to suppress patch output:

$ git show --oneline -s
a9874fd Merge branch 'epic-feature'

Option 2: git log -1

You can also simply do git log -1 to find out which commit you're currently on.

$ git log -1 --oneline
c1abcde Add feature-003

Option 3: Bash prompt

In Git version 1.8.3+ (or was it an earlier version?), if you have your Bash prompt configured to show the current branch you have checked out into your working copy, then it will also show you the current commit you have checked out during a bisect session or when you're in a "detached HEAD" state. In the example below, I currently have c1abcde checked out:

# Prompt during a bisect
user ~ (c1abcde...)|BISECTING $

# Prompt at detached HEAD state 
user ~ (c1abcde...) $

Option 4: git status

Also as of Git version 1.8.3+ (and possibly earlier, again not sure), running git status will also show you what commit you have checked out during a bisect and when you're in detached HEAD state:

$ git status
# HEAD detached at c1abcde <== RIGHT HERE

Option 5: git bisect visualize

Finally, while you're doing a git bisect, you can also simply use git bisect visualize or its built-in alias git bisect view to launch gitk, so that you can graphically view which commit you are on, as well as which commits you have marked as bad and good so far. I'm pretty sure this existed well before version 1.8.3, I'm just not sure in which version it was introduced:

git bisect visualize 
git bisect view # shorter, means same thing

enter image description here

What does the explicit keyword mean?

Constructors append implicit conversion. To suppress this implicit conversion it is required to declare a constructor with a parameter explicit.

In C++11 you can also specify an "operator type()" with such keyword http://en.cppreference.com/w/cpp/language/explicit With such specification you can use operator in terms of explicit conversions, and direct initialization of object.

P.S. When using transformations defined BY USER (via constructors and type conversion operator) it is allowed only one level of implicit conversions used. But you can combine this conversions with other language conversions

  • up integral ranks (char to int, float to double);
  • standart conversions (int to double);
  • convert pointers of objects to base class and to void*;

Can't change table design in SQL Server 2008

The answer is on the MSDN site:

The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.

The following actions might require a table to be re-created:

  • Adding a new column to the middle of the table
  • Dropping a column
  • Changing column nullability
  • Changing the order of the columns
  • Changing the data type of a column

EDIT 1:

Additional useful informations from here:

To change the Prevent saving changes that require the table re-creation option, follow these steps:

  1. Open SQL Server Management Studio (SSMS).
  2. On the Tools menu, click Options.
  3. In the navigation pane of the Options window, click Designers.
  4. Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.

Risk of turning off the "Prevent saving changes that require table re-creation" option

Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.

Settings, screen shot

How to format date string in java?

package newpckg;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StrangeDate {

    public static void main(String[] args) {

        // string containing date in one format
        // String strDate = "2012-05-20T09:00:00.000Z";
        String strDate = "2012-05-20T09:00:00.000Z";

        try {
            // create SimpleDateFormat object with source string date format
            SimpleDateFormat sdfSource = new SimpleDateFormat(
                    "yyyy-MM-dd'T'hh:mm:ss'.000Z'");

            // parse the string into Date object
            Date date = sdfSource.parse(strDate);

            // create SimpleDateFormat object with desired date format
            SimpleDateFormat sdfDestination = new SimpleDateFormat(
                    "dd/MM/yyyy, ha");

            // parse the date into another format
            strDate = sdfDestination.format(date);

            System.out
                    .println("Date is converted from yyyy-MM-dd'T'hh:mm:ss'.000Z' format to dd/MM/yyyy, ha");
            System.out.println("Converted date is : " + strDate.toLowerCase());

        } catch (ParseException pe) {
            System.out.println("Parse Exception : " + pe);
        }
    }
}

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark - NSSecureCoding

The main purpose of "pragma" is for developer reference.enter image description here

You can easily find a method/Function in a vast thousands of coding lines.

Xcode 11+:

Marker Line in Top

// MARK: - Properties

Marker Line in Top and Bottom

// MARK: - Properties - 

Marker Line only in bottom

// MARK: Properties -

WPF Binding to parent DataContext

I dont know about XamGrid but that's what i'll do with a standard wpf DataGrid:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Since the TextBlock and the TextBox specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.

How to determine the version of android SDK installed in computer?

Android Studio is now (early 2015) out of beta. If you're using it as your development platform, the SDK Manager is probably the easiest way to see what's available. To start the SDK Manager from within Android Studio, use the menu bar: Tools > Android > SDK Manager.

This will provide not only the SDK version, but the versions of SDK Build Tools and SDK Platform Tools. It also works if you've installed them somewhere other than in Program Files.

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

The code below can solve the NullPointerException.

@Id
@GeneratedValue
@Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
    return this.stockId;
}
public void setStockId(Integer stockId) {
    this.stockId = stockId;
}

If you add @Id, then you can declare some more like as above declared method.

What is the difference between bool and Boolean types in C#

bool is an alias for the Boolean class. I use the alias when declaring a variable and the class name when calling a method on the class.

Which version of MVC am I using?

Select the System.Web.Mvc assembly in the "References" folder in the solution explorer. Bring up the properties window (F4) and check the Version

Reference Properties

How can I validate a string to only allow alphanumeric characters in it?

Use the following expression:

^[a-zA-Z0-9]*$

ie:

using System.Text.RegularExpressions;

Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(SomeString)) {
  ...
}

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

why are there two different kinds of for loops in java?

The new for-each loop is just a short hand for the older loop. The new loop is easier to use for arrays and some iterators, but not as flexible, so the old loop has to be using in some situations, like counting from 0 to 9.

Simple parse JSON from URL on Android and display in listview

try as:

 // your get json request to server.. 
 HttpResponse response = httpClient.execute(httpPost);
 HttpEntity entity = response.getEntity();

 if(entity != null){
    JSONObject respObject = new JSONObject(EntityUtils.toString(entity));
    String active = respObject.getString("active");   
    String name = respObject.getString("name");  
    String tab1_text = respObject.getString("tab1_text");  
    //.... 
  }
else{
       //Do something here...
    }

see this example for Getting and parsing json response from server :

http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/

How do I import the javax.servlet API in my Eclipse project?

Little bit difference from Hari:

Right click on project ---> Properties ---> Java Build Path ---> Add Library... ---> Server Runtime ---> Apache Tomcat ----> Finish.

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this one -

"SELECT 
       ID, Salt, password, BannedEndDate
     , (
          SELECT COUNT(1)
          FROM dbo.LoginFails l
          WHERE l.UserName = u.UserName
               AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
      ) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"

Error: Cannot pull with rebase: You have unstaged changes

Pulling with rebase is a good practice in general.

However you cannot do that if your index is not clean, i.e. you have made changes that have not been committed.

You can do this to work around, assuming you want to keep your changes:

  1. stash your changes with: git stash
  2. pull from master with rebase
  3. reapply the changes you stashed in (1) with: git stash apply stash@{0} or the simpler git stash pop

Simple WPF RadioButton Binding?

Actually, using the converter like that breaks two-way binding, plus as I said above, you can't use that with enumerations either. The better way to do this is with a simple style against a ListBox, like this:

Note: Contrary to what DrWPF.com stated in their example, do not put the ContentPresenter inside the RadioButton or else if you add an item with content such as a button or something else, you will not be able to set focus or interact with it. This technique solves that. Also, you need to handle the graying of the text as well as removing of margins on labels or else it will not render correctly. This style handles both for you as well.

<Style x:Key="RadioButtonListItem" TargetType="{x:Type ListBoxItem}" >

    <Setter Property="Template">
        <Setter.Value>

            <ControlTemplate TargetType="ListBoxItem">

                <DockPanel LastChildFill="True" Background="{TemplateBinding Background}" HorizontalAlignment="Stretch" VerticalAlignment="Center" >

                    <RadioButton IsChecked="{TemplateBinding IsSelected}" Focusable="False" IsHitTestVisible="False" VerticalAlignment="Center" Margin="0,0,4,0" />

                    <ContentPresenter
                        Content             = "{TemplateBinding ContentControl.Content}"
                        ContentTemplate     = "{TemplateBinding ContentControl.ContentTemplate}"
                        ContentStringFormat = "{TemplateBinding ContentControl.ContentStringFormat}"
                        HorizontalAlignment = "{TemplateBinding Control.HorizontalContentAlignment}"
                        VerticalAlignment   = "{TemplateBinding Control.VerticalContentAlignment}"
                        SnapsToDevicePixels = "{TemplateBinding UIElement.SnapsToDevicePixels}" />

                </DockPanel>

            </ControlTemplate>

        </Setter.Value>

    </Setter>

</Style>

<Style x:Key="RadioButtonList" TargetType="ListBox">

    <Style.Resources>
        <Style TargetType="Label">
            <Setter Property="Padding" Value="0" />
        </Style>
    </Style.Resources>

    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Background"      Value="Transparent" />

    <Setter Property="ItemContainerStyle" Value="{StaticResource RadioButtonListItem}" />

    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBox}">
                <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="TextBlock.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
        </Trigger>
    </Style.Triggers>

</Style>

<Style x:Key="HorizontalRadioButtonList" BasedOn="{StaticResource RadioButtonList}" TargetType="ListBox">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Background="Transparent" Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>

You now have the look and feel of radio buttons, but you can do two-way binding, and you can use an enumeration. Here's how...

<ListBox Style="{StaticResource RadioButtonList}"
    SelectedValue="{Binding SomeVal}"
    SelectedValuePath="Tag">

    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOption}"     >Some option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOtherOption}">Some other option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.YetAnother}"     >Yet another option</ListBoxItem>

</ListBox>

Also, since we explicitly separated out the style that tragets the ListBoxItem rather than putting it inline, again as the other examples have shown, you can now create a new style off of it to customize things on a per-item basis such as spacing. (This will not work if you simply try to target ListBoxItem as the keyed style overrides generic control targets.)

Here's an example of putting a margin of 6 above and below each item. (Note how you have to explicitly apply the style via the ItemContainerStyle property and not simply targeting ListBoxItem in the ListBox's resource section for the reason stated above.)

<Window.Resources>
    <Style x:Key="SpacedRadioButtonListItem" TargetType="ListBoxItem" BasedOn="{StaticResource RadioButtonListItem}">
        <Setter Property="Margin" Value="0,6" />
    </Style>
</Window.Resources>

<ListBox Style="{StaticResource RadioButtonList}"
    ItemContainerStyle="{StaticResource SpacedRadioButtonListItem}"
    SelectedValue="{Binding SomeVal}"
    SelectedValuePath="Tag">

    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOption}"     >Some option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOtherOption}">Some other option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.YetAnother}"     >Ter another option</ListBoxItem>

</ListBox>

How do you Sort a DataTable given column and direction?

Actually got the same problem. For me worked this easy way:

Adding the data to a Datatable and sort it:

dt.DefaultView.Sort = "columnname";
dt = dt.DefaultView.ToTable();

How do I compare two string variables in an 'if' statement in Bash?

I suggest this one:

if [ "$a" = "$b" ]

Notice the white space between the openning/closing brackets and the variables and also the white spaces wrapping the '=' sign.

Also, be careful of your script header. It's not the same thing whether you use

#!/bin/bash

or

#!/bin/sh

Here's the source.

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

Based on the clarifying comment by @user2989027, I think a good solution is the following:

definition = ['apple', 'ball']
data = {'orange':1, 'pear':2, 'apple':3, 'ball':4}
my_data = {}
for k in definition:
  try:
    my_data[k]=data[k]
  except KeyError:
    pass
print my_data

I tried not to do anything fancy here. I setup my data and an empty dictionary. I then loop through a list of strings that represent potential keys in my data dictionary. I copy each value from data to my_data, but consider the case where data may not have the key that I want.

How to wrap text using CSS?

If you type "AAAAAAAAAAAAAAAAAAAAAARRRRRRRRRRRRRRRRRRRRRRGGGGGGGGGGGGGGGGGGGGG" this will produce:

AARRRRRRRRRRRRRRRRRRRR
RRGGGGGGGGGGGGGGGGGGGG
G

I have taken my example from a couple different websites on google. I have tested this on ff 5.0, IE 8.0, and Chrome 10. It works on all of them.

.wrapword {
    white-space: -moz-pre-wrap !important;  /* Mozilla, since 1999 */
    white-space: -pre-wrap;      /* Opera 4-6 */
    white-space: -o-pre-wrap;    /* Opera 7 */
    white-space: pre-wrap;       /* css-3 */
    word-wrap: break-word;       /* Internet Explorer 5.5+ */
    white-space: -webkit-pre-wrap; /* Newer versions of Chrome/Safari*/
    word-break: break-all;
    white-space: normal;
}

<table style="table-layout:fixed; width:400px">
    <tr>
        <td class="wrapword"></td>
    </tr>
</table>

How can I get the root domain URI in ASP.NET?

I know this is older but the correct way to do this now is

string Domain = HttpContext.Current.Request.Url.Authority

That will get the DNS or ip address with port for a server.

How do I accomplish an if/else in mustache.js?

This is how you do if/else in Mustache (perfectly supported):

{{#repo}}
  <b>{{name}}</b>
{{/repo}}
{{^repo}}
  No repos :(
{{/repo}}

Or in your case:

{{#author}}
  {{#avatar}}
    <img src="{{avatar}}"/>
  {{/avatar}}
  {{^avatar}}
    <img src="/images/default_avatar.png" height="75" width="75" />
  {{/avatar}}
{{/author}}

Look for inverted sections in the docs: https://github.com/janl/mustache.js

JSP tricks to make templating easier?

Add dependecies for use <%@tag description="User Page template" pageEncoding="UTF-8"%>

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp.jstl</groupId>
        <artifactId>javax.servlet.jsp.jstl-api</artifactId>
        <version>1.2.1</version>
    </dependency>
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>
</dependencies>

Set cellpadding and cellspacing in CSS?

This worked for me:

table {border-collapse: collapse}
table th, table td {padding: 0}

YYYY-MM-DD format date in shell script

Whenever I have a task like this I end up falling back to

$ man strftime

to remind myself of all the possibilities for time formatting options.

Filter df when values matches part of a string in pyspark

Spark 2.2 onwards

df.filter(df.location.contains('google.com'))

Spark 2.2 documentation link


Spark 2.1 and before

You can use plain SQL in filter

df.filter("location like '%google.com%'")

or with DataFrame column methods

df.filter(df.location.like('%google.com%'))

Spark 2.1 documentation link

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

Timestamp in saving workbook path, the ":" needs to be changed. I used ":" -> "." which implies that I need to add the extension back "xlsx".

wb(x).SaveAs ThisWorkbook.Path & "\" & unique(x) & " - " & Format(Now(), "mm-dd-yy, hh.mm.ss") & ".xlsx"

Separation of business logic and data access in django

First of all, Don't repeat yourself.

Then, please be careful not to overengineer, sometimes it is just a waste of time, and makes someone lose focus on what is important. Review the zen of python from time to time.

Take a look at active projects

  • more people = more need to organize properly
  • the django repository they have a straightforward structure.
  • the pip repository they have a straigtforward directory structure.
  • the fabric repository is also a good one to look at.

    • you can place all your models under yourapp/models/logicalgroup.py
  • e.g User, Group and related models can go under yourapp/models/users.py
  • e.g Poll, Question, Answer ... could go under yourapp/models/polls.py
  • load what you need in __all__ inside of yourapp/models/__init__.py

More about MVC

  • model is your data
    • this includes your actual data
    • this also includes your session / cookie / cache / fs / index data
  • user interacts with controller to manipulate the model
    • this could be an API, or a view that saves/updates your data
    • this can be tuned with request.GET / request.POST ...etc
    • think paging or filtering too.
  • the data updates the view
    • the templates take the data and format it accordingly
    • APIs even w/o templates are part of the view; e.g. tastypie or piston
    • this should also account for the middleware.

Take advantage of middleware / templatetags

  • If you need some work to be done for each request, middleware is one way to go.
    • e.g. adding timestamps
    • e.g. updating metrics about page hits
    • e.g. populating a cache
  • If you have snippets of code that always reoccur for formatting objects, templatetags are good.
    • e.g. active tab / url breadcrumbs

Take advantage of model managers

  • creating User can go in a UserManager(models.Manager).
  • gory details for instances should go on the models.Model.
  • gory details for queryset could go in a models.Manager.
  • you might want to create a User one at a time, so you may think that it should live on the model itself, but when creating the object, you probably don't have all the details:

Example:

class UserManager(models.Manager):
   def create_user(self, username, ...):
      # plain create
   def create_superuser(self, username, ...):
      # may set is_superuser field.
   def activate(self, username):
      # may use save() and send_mail()
   def activate_in_bulk(self, queryset):
      # may use queryset.update() instead of save()
      # may use send_mass_mail() instead of send_mail()

Make use of forms where possible

A lot of boilerplate code can be eliminated if you have forms that map to a model. The ModelForm documentation is pretty good. Separating code for forms from model code can be good if you have a lot of customization (or sometimes avoid cyclic import errors for more advanced uses).

Use management commands when possible

  • e.g. yourapp/management/commands/createsuperuser.py
  • e.g. yourapp/management/commands/activateinbulk.py

if you have business logic, you can separate it out

  • django.contrib.auth uses backends, just like db has a backend...etc.
  • add a setting for your business logic (e.g. AUTHENTICATION_BACKENDS)
  • you could use django.contrib.auth.backends.RemoteUserBackend
  • you could use yourapp.backends.remote_api.RemoteUserBackend
  • you could use yourapp.backends.memcached.RemoteUserBackend
  • delegate the difficult business logic to the backend
  • make sure to set the expectation right on the input/output.
  • changing business logic is as simple as changing a setting :)

backend example:

class User(db.Models):
    def get_present_name(self): 
        # property became not deterministic in terms of database
        # data is taken from another service by api
        return remote_api.request_user_name(self.uid) or 'Anonymous' 

could become:

class User(db.Models):
   def get_present_name(self):
      for backend in get_backends():
         try:
            return backend.get_present_name(self)
         except: # make pylint happy.
            pass
      return None

more about design patterns

more about interface boundaries

  • Is the code you want to use really part of the models? -> yourapp.models
  • Is the code part of business logic? -> yourapp.vendor
  • Is the code part of generic tools / libs? -> yourapp.libs
  • Is the code part of business logic libs? -> yourapp.libs.vendor or yourapp.vendor.libs
  • Here is a good one: can you test your code independently?
    • yes, good :)
    • no, you may have an interface problem
    • when there is clear separation, unittest should be a breeze with the use of mocking
  • Is the separation logical?
    • yes, good :)
    • no, you may have trouble testing those logical concepts separately.
  • Do you think you will need to refactor when you get 10x more code?
    • yes, no good, no bueno, refactor could be a lot of work
    • no, that's just awesome!

In short, you could have

  • yourapp/core/backends.py
  • yourapp/core/models/__init__.py
  • yourapp/core/models/users.py
  • yourapp/core/models/questions.py
  • yourapp/core/backends.py
  • yourapp/core/forms.py
  • yourapp/core/handlers.py
  • yourapp/core/management/commands/__init__.py
  • yourapp/core/management/commands/closepolls.py
  • yourapp/core/management/commands/removeduplicates.py
  • yourapp/core/middleware.py
  • yourapp/core/signals.py
  • yourapp/core/templatetags/__init__.py
  • yourapp/core/templatetags/polls_extras.py
  • yourapp/core/views/__init__.py
  • yourapp/core/views/users.py
  • yourapp/core/views/questions.py
  • yourapp/core/signals.py
  • yourapp/lib/utils.py
  • yourapp/lib/textanalysis.py
  • yourapp/lib/ratings.py
  • yourapp/vendor/backends.py
  • yourapp/vendor/morebusinesslogic.py
  • yourapp/vendor/handlers.py
  • yourapp/vendor/middleware.py
  • yourapp/vendor/signals.py
  • yourapp/tests/test_polls.py
  • yourapp/tests/test_questions.py
  • yourapp/tests/test_duplicates.py
  • yourapp/tests/test_ratings.py

or anything else that helps you; finding the interfaces you need and the boundaries will help you.

How to find out the MySQL root password

I solved this a different way, this may be easier for some.

I did it this way because I tried starting in safe mode but cannot connect with the error: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

What I did was to connect normally as root:

$ sudo mysql -u root

Then I created a new super user:

mysql> grant all privileges on *.* to 'myuser'@'%' identified by 'mypassword' with grant option;
mysql> quit

Then log in as myuser

$ mysql -u myuser -p -h localhost

Trying to change the password gave me no errors but did nothing for me so I dropped and re-created the root user

mysql> drop user 'root'@'localhost;
mysql> mysql> grant all privileges on *.* to 'root'@'localhost' identified by 'mypassword' with grant option;

The root user is now working with the new password

How do I collapse sections of code in Visual Studio Code for Windows?

v1.42 is adding some nice refinements to how folds look and function. See https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_42.md#folded-range-highlighting:

Folded Range Highlighting

Folded ranges now are easier to discover thanks to a background color for all folded ranges.

fold highlight

Fold highlight color Theme: Dark+

The feature is controled by the setting editor.foldingHighlight and the color can be customized with the color editor.foldBackground.

"workbench.colorCustomizations": { "editor.foldBackground": "#355000" }

Folding Refinements

Shift + Click on the folding indicator first only folds the inner ranges. Shift + Click again (when all inner ranges are already folded) will also fold the parent. Shift + Click again unfolds all.

fold shift click

When using the Fold command (kb(editor.fold))] on an already folded range, the next unfolded parent range will be folded.

Genymotion Android emulator - adb access?

I know it's way too late to answer this question, but I'll just post the solution that worked for me, in case someone runs into trouble again in the future.

I tried using genymotion's own adb tools and the original Android SDK ones, and even purging and reinstalling adb from my system, but nothing worked. I kept getting the error:

adb server is out of date. killing... cannot bind 'tcp:5037' ADB server didn't ACK *failed to start daemon* error:
So I tried adb connect [ip] as suggested here, but I didn't work either, the same error came up.

What finally worked for me was downloading ADT, and running adb directly from the downloaded folder, instead of the system-wide command. So adb devices will give me the error above, but /yourdownloadpath/adb devices works just fine for me.

Hope it helped.

jquery datatables default sort

You can use the fnSort function, see the details here:

http://datatables.net/api#fnSort

Convert JSON format to CSV format for MS Excel

Using Python will be one easy way to achieve what you want.

I found one using Google.

"convert from json to csv using python" is an example.

how to set radio button checked in edit mode in MVC razor view

Here is how I do it and works both for create and edit:

//How to do it with enums
<div class="editor-field">
   @Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
   @Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>

//And with Booleans
<div class="editor-field">
   @Html.RadioButtonFor(x => x.IsMale, true) Male
   @Html.RadioButtonFor(x => x.IsMale, false) Female
</div>

the provided values (true and false) are the values that the engine will render as the values for the html element i.e.:

<input id="IsMale" type="radio" name="IsMale" value="True">
<input id="IsMale" type="radio" name="IsMale" value="False">

And the checked property is dependent on the Model.IsMale value.

Razor engine seems to internally match the set radio button value to your model value, if a proper from and to string convert exists for it. So there is no need to add it as an html attribute in the helper method.

Cannot read property 'addEventListener' of null

I encountered the same problem and checked for null but it did not help. Because the script was loading before page load. So just by placing the script before the end body tag solved the problem.

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

Built-in support since Handlebars 1.0rc1

Support for this functionality has been added to Handlebars.js, so there is no more need for external helpers.

How to use it

For arrays:

{{#each myArray}}
    Index: {{@index}} Value = {{this}}
{{/each}}

For objects:

{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}

Note that only properties passing the hasOwnProperty test will be enumerated.

Why is lock(this) {...} bad?

Imagine that you have a skilled secretary at your office that's a shared resource in the department. Once in a while, you rush towards them because you have a task, only to hope that another one of your co-workers has not already claimed them. Usually you only have to wait for a brief period of time.

Because caring is sharing, your manager decides that customers can use the secretary directly as well. But this has a side effect: A customer might even claim them while you're working for this customer and you also need them to execute part of the tasks. A deadlock occurs, because claiming is no longer a hierarchy. This could have been avoided all together by not allowing customers to claim them in the first place.

lock(this) is bad as we've seen. An outside object might lock on the object and since you don't control who's using the class, anyone can lock on it... Which is the exact example as described above. Again, the solution is to limit exposure of the object. However, if you have a private, protected or internal class you could already control who is locking on your object, because you're sure that you've written your code yourself. So the message here is: don't expose it as public. Also, ensuring that a lock is used in similar scenario's avoids deadlocks.

The complete opposite of this is to lock on resources that are shared throughout the app domain -- the worst case scenario. It's like putting your secretary outside and allowing everyone out there to claim them. The result is utter chaos - or in terms of source code: it was a bad idea; throw it away and start over. So how do we do that?

Types are shared in the app domain as most people here point out. But there are even better things we can use: strings. The reason is that strings are pooled. In other words: if you have two strings that have the same contents in an app domain, there's a chance that they have the exact same pointer. Since the pointer is used as the lock key, what you basically get is a synonym for "prepare for undefined behavior".

Similarly, you shouldn't lock on WCF objects, HttpContext.Current, Thread.Current, Singletons (in general), etc. The easiest way to avoid all of this? private [static] object myLock = new object();

Difference between uint32 and uint32_t

uint32_t is standard, uint32 is not. That is, if you include <inttypes.h> or <stdint.h>, you will get a definition of uint32_t. uint32 is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Update: My original answer involved having the controller contain DOM-aware code, which breaks Angular conventions in favor of HTML. @dmackerman mentioned directives in a comment on my answer, and I completely missed that until just now. With that input, here's the right way to do this without breaking Angular or HTML conventions:


There's also a way to get both - grab the value of the element and use that to update the model in a directive:

<div ng-controller="Main">
    <input type="text" id="rootFolder" ng-model="rootFolders" disabled="disabled" value="Bob" size="40" />
</div>

and then:

app.directive('input', ['$parse', function ($parse) {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, element, attrs) {
            if(attrs.value) {
                $parse(attrs.ngModel).assign(scope, attrs.value);
            }
        }
    };
}]);

You can of course modify the above directive to do more with the value attribute before setting the model to its value, including using $parse(attrs.value, scope) to treat the value attribute as an Angular expression (though I'd probably use a different [custom] attribute for that, personally, so the standard HTML attributes are consistently treated as constants).

Also, there is a similar question over at Making data templated in available to ng-model which may also be of interest.

Is it possible to access an SQLite database from JavaScript?

One of the most interesting features in HTML5 is the ability to store data locally and to allow the application to run offline. There are three different APIs that deal with these features and choosing one depends on what exactly you want to do with the data you're planning to store locally:

  1. Web storage: For basic local storage with key/value pairs
  2. Offline storage: Uses a manifest to cache entire files for offline use
  3. Web database: For relational database storage

For more reference see Introducing the HTML5 storage APIs

And how to use

http://cookbooks.adobe.com/post_Store_data_in_the_HTML5_SQLite_database-19115.html

Bytes of a string in Java

There's a method called getBytes(). Use it wisely .

How do you UrlEncode without using System.Web?

There's a client profile usable version, System.Net.WebUtility class, present in client profile System.dll. Here's the MSDN Link:

WebUtility

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

Is there a wikipedia API just for retrieve content summary?

Since 2017 Wikipedia provides a REST API with better caching. In the documentation you can find the following API which perfectly fits your use case. (as it is used by the new Page Previews feature)

https://en.wikipedia.org/api/rest_v1/page/summary/Stack_Overflow returns the following data which can be used to display a summery with a small thumbnail:

{
  "type": "standard",
  "title": "Stack Overflow",
  "displaytitle": "Stack Overflow",
  "extract": "Stack Overflow is a question and answer site for professional and enthusiast programmers. It is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange. The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.",
  "extract_html": "<p><b>Stack Overflow</b> is a question and answer site for professional and enthusiast programmers. It is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange. The name for the website was chosen by voting in April 2008 by readers of <i>Coding Horror</i>, Atwood's popular programming blog.</p>",
  "namespace": {
    "id": 0,
    "text": ""
  },
  "wikibase_item": "Q549037",
  "titles": {
    "canonical": "Stack_Overflow",
    "normalized": "Stack Overflow",
    "display": "Stack Overflow"
  },
  "pageid": 21721040,
  "thumbnail": {
    "source": "https://upload.wikimedia.org/wikipedia/en/thumb/f/fa/Stack_Overflow_homepage%2C_Feb_2017.png/320px-Stack_Overflow_homepage%2C_Feb_2017.png",
    "width": 320,
    "height": 149
  },
  "originalimage": {
    "source": "https://upload.wikimedia.org/wikipedia/en/f/fa/Stack_Overflow_homepage%2C_Feb_2017.png",
    "width": 462,
    "height": 215
  },
  "lang": "en",
  "dir": "ltr",
  "revision": "902900099",
  "tid": "1a9cdbc0-949b-11e9-bf92-7cc0de1b4f72",
  "timestamp": "2019-06-22T03:09:01Z",
  "description": "website hosting questions and answers on a wide range of topics in computer programming",
  "content_urls": {
    "desktop": {
      "page": "https://en.wikipedia.org/wiki/Stack_Overflow",
      "revisions": "https://en.wikipedia.org/wiki/Stack_Overflow?action=history",
      "edit": "https://en.wikipedia.org/wiki/Stack_Overflow?action=edit",
      "talk": "https://en.wikipedia.org/wiki/Talk:Stack_Overflow"
    },
    "mobile": {
      "page": "https://en.m.wikipedia.org/wiki/Stack_Overflow",
      "revisions": "https://en.m.wikipedia.org/wiki/Special:History/Stack_Overflow",
      "edit": "https://en.m.wikipedia.org/wiki/Stack_Overflow?action=edit",
      "talk": "https://en.m.wikipedia.org/wiki/Talk:Stack_Overflow"
    }
  },
  "api_urls": {
    "summary": "https://en.wikipedia.org/api/rest_v1/page/summary/Stack_Overflow",
    "metadata": "https://en.wikipedia.org/api/rest_v1/page/metadata/Stack_Overflow",
    "references": "https://en.wikipedia.org/api/rest_v1/page/references/Stack_Overflow",
    "media": "https://en.wikipedia.org/api/rest_v1/page/media/Stack_Overflow",
    "edit_html": "https://en.wikipedia.org/api/rest_v1/page/html/Stack_Overflow",
    "talk_page_html": "https://en.wikipedia.org/api/rest_v1/page/html/Talk:Stack_Overflow"
  }
}

By default, it follows redirects (so that /api/rest_v1/page/summary/StackOverflow also works), but this can be disabled with ?redirect=false

If you need to access the API from another domain you can set the CORS header with &origin= (e.g. &origin=*)

Update 2019: The API seems to return more useful information about the page.

Converting NSString to NSDate (and back again)

NSString *dateStr = @"Tue, 25 May 2010 12:53:58 +0000";

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss Z"];
NSDate *date = [dateFormat dateFromString:dateStr]; 
[dateFormat release];

problem with <select> and :after with CSS in WebKit

This post may help http://bavotasan.com/2011/style-select-box-using-only-css/

He is using a outside div with a class for resolving this issue.

<div class="styled-select">
  <select>
    <option>Here is the first option</option>
    <option>The second option</option>
  </select>
</div>

How to loop and render elements in React-native?

render() {
  return (
    <View style={...}>
       {initialArr.map((prop, key) => {
         return (
           <Button style={{borderColor: prop[0]}}  key={key}>{prop[1]}</Button>
         );
      })}
     </View>
  )
}

should do the trick

Error during SSL Handshake with remote server

Faced the same problem as OP:

  • Tomcat returned response when accessing directly via SOAP UI
  • Didn't load html files
  • When used Apache properties mentioned by the previous answer, web-page appeared but AngularJS couldn't get HTTP response

Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.

round up to 2 decimal places in java?

I just modified your code. It works fine in my system. See if this helps

class round{
    public static void main(String args[]){

    double a = 123.13698;
    double roundOff = Math.round(a*100)/100.00;

    System.out.println(roundOff);
}
}

Taking pictures with camera on Android programmatically

Take and store image in desired folder

 //Global Variables
   private static final int CAMERA_IMAGE_REQUEST = 101;
    private String imageName;

Take picture function

 public void captureImage() {

            // Creating folders for Image
            String imageFolderPath = Environment.getExternalStorageDirectory().toString()
                    + "/AutoFare";
            File imagesFolder = new File(imageFolderPath);
            imagesFolder.mkdirs();

            // Generating file name
            imageName = new Date().toString() + ".png";

            // Creating image here
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imageFolderPath, imageName)));
            startActivityForResult(takePictureIntent,
                    CAMERA_IMAGE_REQUEST);

        }

Broadcast new image added otherwise pic will not be visible in image gallery

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
                // TODO Auto-generated method stub
                super.onActivityResult(requestCode, resultCode, data);

                if (resultCode == Activity.RESULT_OK && requestCode == CAMERA_IMAGE_REQUEST) {

                    Toast.makeText(getActivity(), "Success",
                            Toast.LENGTH_SHORT).show();

 //Scan new image added
                    MediaScannerConnection.scanFile(getActivity(), new String[]{new File(Environment.getExternalStorageDirectory()
                            + "/AutoFare/" + imageName).getPath()}, new String[]{"image/png"}, null);


 // Work in few phones
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

                        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(Environment.getExternalStorageDirectory()
                                + "/AutoFare/" + imageName)));

                    } else {
                        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(Environment.getExternalStorageDirectory()
                                + "/AutoFare/" + imageName)));
                    }
                } else {
                    Toast.makeText(getActivity(), "Take Picture Failed or canceled",
                            Toast.LENGTH_SHORT).show();
                }
            }

Permissions

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android widget: How to change the text of a button

This is very easy

Button btn = (Button) findViewById(R.id.btn);
btn.setText("MyText");

Clearing the terminal screen?

I have found that ASCII 12 make a Form feed, that is a new page. here is a wikipedia definition

"Form feed is a page-breaking ASCII control character. It forces the printer to eject the current page and to continue printing at the top of another"

The code is

Serial.write(12);

Arduino Terminate doesn't support the character but Putty a light open source telnet client can do it

An Example of the code

void setup() {
  Serial.begin(9600);//Initializase the serial transmiter speed

}

void loop() {
    //Code tested with Putty terminal

    Serial.write(12);//ASCII for a Form feed
    Serial.println("This is the title of a new page");// your code

    delay(500);//delay for visual
    }

CRON command to run URL address every 5 minutes

I find this solution to run a URL every 5 minutes from cPanel you can execute any task by this command.

*/5 * * * * This on run At every 5th minute. so it only runs once in one hour

Here is an example that i use to run my URL every second

*/5 * * * * curl http://www.example.com/;
sleep 5m; curl http://www.example.com/; 
sleep 5m; curl http://www.example.com/; 
sleep 5m; curl http://www.example.com/; 
sleep 5m; curl http://www.example.com/; 
sleep 5m; curl http://www.example.com/; 
sleep 5m; curl http://www.example.com/; 
sleep 5m; curl http://www.example.com/; 
sleep 5m; curl http://www.example.com/; 
sleep 5m; curl http://www.example.com/; 
sleep 5m; curl http://www.example.com/; 
sleep 5m; curl http://www.example.com/; 

To sleep for 5 seconds, use:

sleep 5

Want to sleep for 5 minutes, use:

sleep 5m

Halt or sleep for 5 hours, use:

sleep 5h

If you do not want any email of cron job just add this to end of the command

 >/dev/null 2>&1

How to uninstall Eclipse?

Look for an installation subdirectory, likely named eclipse. Under that subdirectory, if you see files like eclipse.ini, icon.xpm and subdirectories like plugins and dropins, remove the subdirectory parent (the one named eclipse).

That will remove your installation except for anything you've set up yourself (like workspaces, projects, etc.).

Hope this helps.

Named placeholders in string formatting

StrSubstitutor of jakarta commons lang is a light weight way of doing this provided your values are already formatted correctly.

http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/text/StrSubstitutor.html

Map<String, String> values = new HashMap<String, String>();
values.put("value", x);
values.put("column", y);
StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");

The above results in:

"There's an incorrect value '1' in column # 2"

When using Maven you can add this dependency to your pom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>