Programs & Examples On #Mutt

Mutt is an open-source CLI email client. It is highly customizable and fast. Lots of sorting and filtering criteria allow for highly efficient mail handling.

How to change the sender's name or e-mail address in mutt?

If you just want to change it once, you can specify the 'from' header in command line, eg:

mutt -e 'my_hdr From:[email protected]'

my_hdr is mutt's command of providing custom header value.

One last word, don't be evil!

Is there a replacement for unistd.h for Windows (Visual C)?

Try including the io.h file. It seems to be the Visual Studio's equivalent of unistd.h.

I hope this helps.

retrieve links from web page using python and BeautifulSoup

Why not use regular expressions:

import urllib2
import re
url = ""
page = urllib2.urlopen(url)
page =
links = re.findall(r"<a.*?\s*href=\"(.*?)\".*?>(.*?)</a>", page)
for link in links:
    print('href: %s, HTML text: %s' % (link[0], link[1]))

Dynamically generating a QR code with PHP

I have been using google qrcode api for sometime, but I didn't quite like this because it requires me to be on the Internet to access the generated image.

I did a little comand-line research and found out that linux has a command line tool qrencode for generating qr-codes.

I wrote this little script. And the good part is that the generated image is less than 1KB in size. Well the supplied data is simply a url.

$url = ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST'].'/profile.php?id='.$_GET['pid'];
$img = shell_exec('qrencode --output=- -m=1 '.escapeshellarg($url));

$imgData = "data:image/png;base64,".base64_encode($img);

Then in the html I load the image:

<img class="emrQRCode" src="<?=$imgData ?>" />

You just need to have installed it. [most imaging apps on linux would have installed it under the hood without you realizing.

Bootstrap Modal sitting behind backdrop

Many times , you cannot move the modal outside as this affects your design structure.

The reason the backdrop comes above your modal is id the parent has any position set.

A very simple way to solve the problem other then moving your modal outside is move the backdrop inside structure were you have your modal. In your case, it could be


Note that this solution is applicable if you have a definite strucure for your application and you cant just move the modal outside as it will go against the design structure

JSON Post with Customized HTTPHeader Field

What you posted has a syntax error, but it makes no difference as you cannot pass HTTP headers via $.post().

Provided you're on jQuery version >= 1.5, switch to $.ajax() and pass the headers (docs) option. (If you're on an older version of jQuery, I will show you how to do it via the beforeSend option.)

    url: '',
    type: 'post',
    data: {
        access_token: 'XXXXXXXXXXXXXXXXXXX'
    headers: {
        Header_Name_One: 'Header Value One',   //If your header name has spaces or any other char not appropriate
        "Header Name Two": 'Header Value Two'  //for object property name, use quoted notation shown in second
    dataType: 'json',
    success: function (data) {;

Why does Oracle not find oci.dll?

I had this issue, I run 64 bit Windows and had downloaded the 64 bit TOAD package. I finally arrived at the conclusion that it was because I unzipped the package in a windows share using cygwin command line unzip. Turned out TOAD wasn't liking the permissions on some files. When I unzipped using windows File Explorer everything worked as expected.

What's the difference between SHA and AES encryption?

SHA doesn't require anything but an input to be applied, while AES requires at least 3 things - what you're encrypting/decrypting, an encryption key, and the initialization vector.

How do I tar a directory of files and folders without including the directory itself?

I would propose the following Bash function (first argument is the path to the dir, second argument is the basename of resulting archive):

function tar_dir_contents ()
    local DIRPATH="$1"
    local TARARCH="$2.tar.gz"
    local ORGIFS="$IFS"
    tar -C "$DIRPATH" -czf "$TARARCH" $( ls -a "$DIRPATH" | grep -v '\(^\.$\)\|\(^\.\.$\)' )

You can run it in this way:

$ tar_dir_contents /path/to/some/dir my_archive

and it will generate the archive my_archive.tar.gz within current directory. It works with hidden (.*) elements and with elements with spaces in their filename.

How remove border around image in css?

Also, in your html, remember to delete all blanks / line feeds / tabs between the closing tag and the opening tag.

<img src='a.png' /> <img src='b.png' /> will always display a space between the images even if the border attribute is set to 0, whereas <img src='a.png' /><img src='b.png' /> will not.

How can I find the maximum value and its index in array in MATLAB?

For a matrix you can use this:

[M,I] = max(A(:))

I is the index of A(:) containing the largest element.

Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.

[I_row, I_col] = ind2sub(size(A),I)


ADB Driver and Windows 8.1

UPDATE: Post with images ? English Version | Versión en Español

If Windows fails to enumerate the device which is reported in Device Manager as error code 43:

  • Install this Compatibility update from Windows.
  • If you already have this update but you get this error, restart your PC (unfortunately, it happened to me, I tried everything until I thought what if I restart...).

If the device is listed in Device Manager as Other devices -> Android but reports an error code 28:

  • Google USB Driver didn't work for me. You could try your corresponding OEM USB Drivers, but in my case my device is not listed there.
  • So, install the latest Samsung drivers: SAMSUNG USB Driver v1.7.23.0
  • Restart the computer (very important)
  • Go to Device Manager, find the Android device, and select Update Driver Software.
  • Select Browse my computer for driver software
  • Select Let me pick from a list of device drivers on my computer
  • Select ADB Interface from the list
  • Select SAMSUNG Android ADB Interface (this is a signed driver). If you get a warning, select Yes to continue.
  • Done!

By doing this I was able to use my tablet for development under Windows 8.1.

Note: This solution uses Samsung drivers but works for other devices.

Post with images => English Version | Versión en Español

How to retrieve absolute path given relative

Similar to @ernest-a's answer but without affecting $OLDPWD or define a new function you could fire a subshell (cd <path>; pwd)

$ pwd
$ cd ../cups 
$ cd -
$ (cd ~/..; pwd)
$ cd -

cannot redeclare block scoped variable (typescript)

In my case the following tsconfig.json solved problem:

  "compilerOptions": {
    "esModuleInterop": true,
    "target": "ES2020",
    "moduleResolution": "node"

There should be no type: module in package.json.

What is difference between sleep() method and yield() method of multi threading?

sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).

yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.

How do I bind a WPF DataGrid to a variable number of columns?

I have found a blog article by Deborah Kurata with a nice trick how to show variable number of columns in a DataGrid:

Populating a DataGrid with Dynamic Columns in a Silverlight Application using MVVM

Basically, she creates a DataGridTemplateColumn and puts ItemsControl inside that displays multiple columns.

How to make a floated div 100% height of its parent?

This helped me.

#outer {
#inner {

Change right: and left: to set preferable #inner width.

How to check the version of scipy

From the python command prompt:

import scipy
print scipy.__version__

In python 3 you'll need to change it to:

print (scipy.__version__)

Difference between $(this) and states:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to if the event has bubbled from a descendant element.)

To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

If we have

<input type="button" class="btn" value ="btn1">
<input type="button" class="btn" value ="btn2">
<input type="button" class="btn" value ="btn3">

<div id="outer">
    <input type="button"  value ="OuterB" id ="OuterB">
    <div id="inner">
        <input type="button" class="btn" value ="InnerB" id ="InnerB">

Check the below output:



Note that I use $ to wrap the dom element in order to create a jQuery object, which is how we always do.

You would find that for the first case, this ,event.currentTarget, are all referenced to the same element.

While in the second case, when the event delegate to some wrapped element are triggered, would be referenced to the triggered element, while this and event.currentTarget are referenced to where the event is delivered.

For this and event.currentTarget, they are exactly the same thing according to

How to prevent the "Confirm Form Resubmission" dialog?

I found an unorthodox way to accomplish this.

Just put the script page in an iframe. Doing so allows the page to be refreshed, seemingly even on older browsers without the "confirm form resubmission" message ever appearing.

Return in Scala

This topic is actually a little more complicated as described in the answers so far. This blogpost by Rob Norris explains it in more detail and gives examples on when using return will actually break your code (or at least have non-obvious effects).

At this point let me just quote the essence of the post. The most important statement is right in the beginning. Print this as a poster and put it to your wall :-)

The return keyword is not “optional” or “inferred”; it changes the meaning of your program, and you should never use it.

It gives one example, where it actually breaks something, when you inline a function

// Inline add and addR
def sum(ns: Int*): Int = ns.foldLeft(0)((n, m) => n + m) // inlined add

scala> sum(33, 42, 99)
res2: Int = 174 // alright

def sumR(ns: Int*): Int = ns.foldLeft(0)((n, m) => return n + m) // inlined addR

scala> sumR(33, 42, 99)
res3: Int = 33 // um.


A return expression, when evaluated, abandons the current computation and returns to the caller of the method in which return appears.

This is only one of the examples given in the linked post and it's the easiest to understand. There're more and I highly encourage you, to go there, read and understand.

When you come from imperative languages like Java, this might seem odd at first, but once you get used to this style it will make sense. Let me close with another quote:

If you find yourself in a situation where you think you want to return early, you need to re-think the way you have defined your computation.

OS X Terminal shortcut: Jump to beginning/end of line

As setup in the terminal using vi:

The Home button on a Macbook Pro keyboard: Fn + Left Arrow.

The End button on a Macbook Pro keyboard: Fn + Right Arrow.

Adding a y-axis label to secondary y-axis in matplotlib

For everyone stumbling upon this post because pandas gets mentioned, you now have the very elegant and straighforward option of directly accessing the secondary_y axis in pandas with ax.right_ax

So paraphrasing the example initially posted, you would write:

table = sql.read_frame(query,connection)

ax = table[[0, 1]].plot(ylim=(0,100), secondary_y=table[1])
ax.right_ax.set_ylabel('Your second Y-Axis Label goes here!')

(this is already mentioned in these posts as well: 1 2)

Using relative URL in CSS file, what location is it relative to?

It's relative to the stylesheet, but I'd recommend making the URLs relative to your URL:

div#header { 
  background-image: url(/images/header-background.jpg);

That way, you can move your files around without needing to refactor them in the future.

What is 0x10 in decimal?

0x means the number is hexadecimal, or base 16.

0x10 is 16.

OnItemCLickListener not working in listview

if you have textviews, buttons or stg clickable or selectable in your row view only


is not enough. You have to set


to your textviews and


to your buttons and other focusable items.

Should functions return null or an empty object?

Forgive my pseudo-php/code.

I think it really depends on the intended use of the result.

If you intend to edit/modify the return value and save it, then return an empty object. That way, you can use the same function to populate data on a new or existing object.

Say I have a function that takes a primary key and an array of data, fills the row with data, then saves the resulting record to the db. Since I'm intending to populate the object with my data either way, it can be a huge advantage to get an empty object back from the getter. That way, I can perform identical operations in either case. You use the result of the getter function no matter what.


function saveTheRow($prim_key, $data) {
    $row = getRowByPrimKey($prim_key);

    // Populate the data here


Here we can see that the same series of operations manipulates all records of this type.

However, if the ultimate intent of the return value is to read and do something with the data, then I would return null. This way, I can very quickly determine if there was no data returned and display the appropriate message to the user.

Usually, I'll catch exceptions in my function that retrieves the data (so I can log error messages, etc...) then return null straight from the catch. It generally doesn't matter to the end user what the problem is, so I find it best to encapsulate my error logging/processing directly in the function that gets the data. If you're maintaining a shared codebase in any large company this is especially beneficial because you can force proper error logging/handling on even the laziest programmer.


function displayData($row_id) {
    // Logging of the error would happen in this function
    $row = getRow($row_id);
    if($row === null) {
        // Handle the error here

    // Do stuff here with data

function getRow($row_id) {
 $row = null;
     if(!$db->connected()) {
   throw excpetion("Couldn't Connect");

  $result = $db->query($some_query_using_row_id);

  if(count($result) == 0 ) {
   throw new exception("Couldn't find a record!");

  $row = $db->nextRow();

 } catch (db_exception) {
  //Log db conn error, alert admin, etc...
  return null; // This way I know that null means an error occurred
 return $row;

That's my general rule. It's worked well so far.

Can I set state inside a useEffect hook

? 1. Can I set state inside a useEffect hook?

In principle, you can set state freely where you need it - including inside useEffect and even during rendering. Just make sure to avoid infinite loops by settting Hook deps properly and/or state conditionally.

? 2. Lets say I have some state that is dependent on some other state. Is it appropriate to create a hook that observes A and sets B inside the useEffect hook?

You just described the classic use case for useReducer:

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. (React docs)

When setting a state variable depends on the current value of another state variable, you might want to try replacing them both with useReducer. [...] When you find yourself writing setSomething(something => ...), it’s a good time to consider using a reducer instead. (Dan Abramov, Overreacted blog)

let MyComponent = () => {_x000D_
  let [state, dispatch] = useReducer(reducer, { a: 1, b: 2 });_x000D_
  useEffect(() => {_x000D_
    console.log("Some effect with B");_x000D_
  }, [state.b]);_x000D_
  return (_x000D_
      <p>A: {state.a}, B: {state.b}</p>_x000D_
      <button onClick={() => dispatch({ type: "SET_A", payload: 5 })}>_x000D_
        Set A to 5 and Check B_x000D_
      <button onClick={() => dispatch({ type: "INCREMENT_B" })}>_x000D_
        Increment B_x000D_
// B depends on A. If B >= A, then reset B to 1._x000D_
function reducer(state, { type, payload }) {_x000D_
  const someCondition = state.b >= state.a;_x000D_
  if (type === "SET_A")_x000D_
    return someCondition ? { a: payload, b: 1 } : { ...state, a: payload };_x000D_
  else if (type === "INCREMENT_B") return { ...state, b: state.b + 1 };_x000D_
  return state;_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
<script src="" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect } = React</script>

? 3. Will the effects cascade such that, when I click the button, the first effect will fire, causing b to change, causing the second effect to fire, before the next render?

useEffect always runs after the render is committed and DOM changes are applied. The first effect fires, changes b and causes a re-render. After this render has completed, second effect will run due to b changes.

let MyComponent = props => {_x000D_
  let [a, setA] = useState(1);_x000D_
  let [b, setB] = useState(2);_x000D_
  let isFirstRender = useRef(true);_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect a, value:", a);_x000D_
    if (isFirstRender.current) isFirstRender.current = false;_x000D_
    else setB(3);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect a, value:", a);_x000D_
  }, [a]);_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect b, value:", b);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect b, value:", b);_x000D_
  }, [b]);_x000D_
  return (_x000D_
      <p>a: {a}, b: {b}</p>_x000D_
        onClick={() => {_x000D_
        click me_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
<script src="" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>

? 4. Are there any performance downsides to structuring code like this?

Yes. By wrapping the state change of b in a separate useEffect for a, the browser has an additional layout/paint phase - these effects are potentially visible for the user. If there is no way you want give useReducer a try, you could change b state together with a directly:

let MyComponent = () => {_x000D_
  let [a, setA] = useState(1);_x000D_
  let [b, setB] = useState(2);_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect b, value:", b);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect b, value:", b);_x000D_
  }, [b]);_x000D_
  const handleClick = () => {_x000D_
    b >= 5 ? setB(1) : setB(b + 1);_x000D_
  return (_x000D_
        a: {a}, b: {b}_x000D_
      <button onClick={handleClick}>click me</button>_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
<script src="" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

In order to be independent of the language and locale settings, you should use the ISO 8601 YYYYMMDD format - this will work on any SQL Server system with any language and regional setting in effect:

      CAST(year AS VARCHAR(4)) +
      RIGHT('0' + CAST(month AS VARCHAR(2)), 2) +
      RIGHT('0' + CAST(day AS VARCHAR(2)), 2) 

applying css to specific li class

The CSS you have applies color #c1c1c1 to all <a> elements.

And it also applies color #c1c1c1 to the first <li> element.

Perhaps the code you posted is missing something because I don't see any other colors being defined.

File upload from <input type="file">

Another way using template reference variable and ViewChild, as proposed by Frelseren:

import { ViewChild } from '@angular/core';

  selector: 'my-app',
  template: `
      <input type="file" #fileInput/>
export class AppComponent {
  @ViewChild("fileInput") fileInputVariable: any;
  randomMethod() {
    const files = this.fileInputVariable.nativeElement.files;

Also see

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

I can offer you some general algorithms...

  • O(1): Accessing an element in an array (i.e. int i = a[9])
  • O(n log n): quick or mergesort (On average)
  • O(log n): Binary search

These would be the gut responses as this sounds like homework/interview kind of question. If you are looking for something more concrete it's a little harder as the public in general would have no idea of the underlying implementation (Sparing open source of course) of a popular application, nor does the concept in general apply to an "application"

Sorting std::map using value

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

    int main(){

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

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

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

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("&saddr=");// from
    urlString.append("&daddr=");// to
    return urlString.toString();

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code


class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
    protected void onUiEngineAttached(boolean attached) {
        if (attached) {
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection);
            is = urlConnection.openInputStream();
        } catch (IOException e) {
        return is;

See full code on J2MEMapRouteBlackBerryEx on Google Code


Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    public void onCreate(Bundle savedInstanceState) {
        mapView = (MapView) findViewById(;
        new Thread() {
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(;
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        return is;
    protected boolean isRouteDisplayed() {
        return false;

See full code on J2MEMapRouteAndroidEx on Google Code

python: [Errno 10054] An existing connection was forcibly closed by the remote host

This can be caused by the two sides of the connection disagreeing over whether the connection timed out or not during a keepalive. (Your code tries to reused the connection just as the server is closing it because it has been idle for too long.) You should basically just retry the operation over a new connection. (I'm surprised your library doesn't do this automatically.)

Best place to insert the Google Analytics code

If you want your scripts to load after page has been rendered, you can use:

function getScript(a, b) {
    var c = document.createElement("script");
    c.src = a;
    var d = document.getElementsByTagName("head")[0],
        done = false;
    c.onload = c.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
            done = true;
            c.onload = c.onreadystatechange = null;

//call the function
getScript("", function() {
    // do stuff after the script has loaded

Is there a printf converter to print in binary format?

Quick and easy solution:

void printbits(my_integer_type x)
    for(int i=sizeof(x)<<3; i; i--)

Works for any size type and for signed and unsigned ints. The '&1' is needed to handle signed ints as the shift may do sign extension.

There are so many ways of doing this. Here's a super simple one for printing 32 bits or n bits from a signed or unsigned 32 bit type (not putting a negative if signed, just printing the actual bits) and no carriage return. Note that i is decremented before the bit shift:

#define printbits_n(x,n) for (int i=n;i;i--,putchar('0'|(x>>i)&1))
#define printbits_32(x) printbits_n(x,32)

What about returning a string with the bits to store or print later? You either can allocate the memory and return it and the user has to free it, or else you return a static string but it will get clobbered if it's called again, or by another thread. Both methods shown:

char *int_to_bitstring_alloc(int x, int count)
    count = count<1 ? sizeof(x)*8 : count;
    char *pstr = malloc(count+1);
    for(int i = 0; i<count; i++)
        pstr[i] = '0' | ((x>>(count-1-i))&1);
    return pstr;

#define BITSIZEOF(x)    (sizeof(x)*8)

char *int_to_bitstring_static(int x, int count)
    static char bitbuf[BITSIZEOF(x)+1];
    count = (count<1 || count>BITSIZEOF(x)) ? BITSIZEOF(x) : count;
    for(int i = 0; i<count; i++)
        bitbuf[i] = '0' | ((x>>(count-1-i))&1);
    return bitbuf;

Call with:

// memory allocated string returned which needs to be freed
char *pstr = int_to_bitstring_alloc(0x97e50ae6, 17);
printf("bits = 0b%s\n", pstr);

// no free needed but you need to copy the string to save it somewhere else
char *pstr2 = int_to_bitstring_static(0x97e50ae6, 17);
printf("bits = 0b%s\n", pstr2);

Python dictionary: Get list of values for list of keys

A little speed comparison:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[1]: l = [0,1,2,3,2,3,1,2,0]
In[2]: m = {0:10, 1:11, 2:12, 3:13}
In[3]: %timeit [m[_] for _ in l]  # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: %timeit map(lambda _: m[_], l)  # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: %timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: %timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 853 ns per loop
In[7]: %timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator import itemgetter
In[34]: %timeit list(itemgetter(*l)(m))
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 739 ns per loop

So list comprehension and itemgetter are the fastest ways to do this.

UPDATE: For large random lists and maps I had a bit different results:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[2]: import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit map(m.__getitem__, l)
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit map(m.get, l)
%timeit map(lambda _: m[_], l)
1000 loops, best of 3: 1.14 ms per loop
1000 loops, best of 3: 1.68 ms per loop
100 loops, best of 3: 2 ms per loop
100 loops, best of 3: 2.05 ms per loop
100 loops, best of 3: 2.19 ms per loop
100 loops, best of 3: 2.53 ms per loop
100 loops, best of 3: 2.9 ms per loop

So in this case the clear winner is f = operator.itemgetter(*l); f(m), and clear outsider: map(lambda _: m[_], l).

UPDATE for Python 3.6.4:

import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit list(map(m.__getitem__, l))
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit list(map(m.get, l))
%timeit list(map(lambda _: m[_], l)
1.66 ms ± 74.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2.1 ms ± 93.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 ms ± 88.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.36 ms ± 60.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.98 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.7 ms ± 284 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
3.14 ms ± 62.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

So, results for Python 3.6.4 is almost the same.

define() vs. const

No one says anything about php-doc, but for me that is also a very significant argument for the preference of const:

 * My foo-bar const
 * @var string
const FOO = 'BAR';

What is the difference between & vs @ and = in angularJS

Not my fiddle, but shows the difference. The key piece is:

            /* NOTE: Normally I would set my attributes and bindings
            to be the same name but I wanted to delineate between 
            parent and isolated scope. */                

Fetch first element which matches criteria

When you write a lambda expression, the argument list to the left of -> can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus: s-> s.getStation().getName().equals(name));

is incorrect syntax; but s)-> s.getStation().getName().equals(name));

is correct. Or: -> s.getStation().getName().equals(name));

is also correct if the compiler has enough information to figure out the types.

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

I'm using intelliJ 15 community edition and I'm able to right click a file and select 'add to .gitignore'

SCRIPT5: Access is denied in IE9 on xmlhttprequest

I think that the issue is that the file is on your local computer, and IE is denying access because if it let scripts have access to files on the comp that the browser is running on, that would be a HUGE security hole.
If you have access to a server or another comp that you could use as one, maybe you could try putting the files on the that, and then running the scripts as you would from a website.

#1071 - Specified key was too long; max key length is 1000 bytes

As @Devart says, the total length of your index is too long.

The short answer is that you shouldn't be indexing such long VARCHAR columns anyway, because the index will be very bulky and inefficient.

The best practice is to use prefix indexes so you're only indexing a left substring of the data. Most of your data will be a lot shorter than 255 characters anyway.

You can declare a prefix length per column as you define the index. For example:

KEY `index` (`parent_menu_id`,`menu_link`(50),`plugin`(50),`alias`(50))

But what's the best prefix length for a given column? Here's a method to find out:

 ROUND(SUM(LENGTH(`menu_link`)<10)*100/COUNT(`menu_link`),2) AS pct_length_10,
 ROUND(SUM(LENGTH(`menu_link`)<20)*100/COUNT(`menu_link`),2) AS pct_length_20,
 ROUND(SUM(LENGTH(`menu_link`)<50)*100/COUNT(`menu_link`),2) AS pct_length_50,
 ROUND(SUM(LENGTH(`menu_link`)<100)*100/COUNT(`menu_link`),2) AS pct_length_100
FROM `pds_core_menu_items`;

It tells you the proportion of rows that have no more than a given string length in the menu_link column. You might see output like this:

| pct_length_10 | pct_length_20 | pct_length_50 | pct_length_100 |
|         21.78 |         80.20 |        100.00 |         100.00 |

This tells you that 80% of your strings are less than 20 characters, and all of your strings are less than 50 characters. So there's no need to index more than a prefix length of 50, and certainly no need to index the full length of 255 characters.

PS: The INT(1) and INT(32) data types indicates another misunderstanding about MySQL. The numeric argument has no effect related to storage or the range of values allowed for the column. INT is always 4 bytes, and it always allows values from -2147483648 to 2147483647. The numeric argument is about padding values during display, which has no effect unless you use the ZEROFILL option.

How can I represent an 'Enum' in Python?

Here is one implementation:

class Enum(set):
    def __getattr__(self, name):
        if name in self:
            return name
        raise AttributeError

Here is its usage:

Animals = Enum(["DOG", "CAT", "HORSE"])


Deploying Java webapp to Tomcat 8 running in Docker container

You are trying to copy the war file to a directory below webapps. The war file should be copied into the webapps directory.

Remove the mkdir command, and copy the war file like this:

COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war

Tomcat will extract the war if autodeploy is turned on.

Regular Expression for any number greater than 0?

Simplified only for 2 decimal places.




Add or Remove modes to sql_mode

MySQL 5.7.9 or later

To add or remove a mode from sql_mode, you can use list_add and list_drop functions.

To remove a mode from the current SESSION.sql_mode, you can use one of the following:

SET SESSION sql_mode = sys.list_drop(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY');
SET sql_mode = sys.list_drop(@@sql_mode, 'ONLY_FULL_GROUP_BY');
SET @@sql_mode = sys.list_drop(@@sql_mode, 'ONLY_FULL_GROUP_BY');

To remove a mode from the GLOBAL.sql_mode that persists for the current runtime operation, until the service is restarted.

SET GLOBAL sql_mode = sys.list_drop(@@GLOBAL.sql_mode, 'ONLY_FULL_GROUP_BY');

MySQL 5.7.8 or prior

Since the sql_mode value is a CSV string of modes, you would need to ensure that the string does not contain residual commas, which can be accomplished by using TRIM(BOTH ',' FROM ...).

To remove a mode from the sql_mode variable, you would want to use REPLACE() along with TRIM() to ensure any residual commas are removed.


To add a mode to the sql_mode variable, you would want to use CONCAT_WS(',', ...), to ensure a comma is appended with the current modes and TRIM() to ensure any residual commas are removed.


NOTE: Changing the GLOBAL variable does not propagate to the SESSION variable, until a new connection is established.

The GLOBAL variable will persist until the running service is restarted.

The SESSION variable will persist for the current connection, until the connection is closed and a new connection is established.

Revert to GLOBAL.sql_mode

Since SET sql_mode = 'ONLY_FULL_GROUP_BY'; was executed without the GLOBAL modifier, the change only affected the current SESSION state value, which also pertains to @@sql_mode. To remove it and revert to the global default on server restart value, you would want to use the value from @@GLOBAL.sql_mode. [sic]

The current SESSION value is only valid for the current connection. Reconnecting to the server will revert the value back to the GLOBAL value.

To revert the current session state value to the current global value, you can use one of the following:

SET SESSION sql_mode = @@GLOBAL.sql_mode;
SET @@sql_mode = @@GLOBAL.sql_mode;
SET sql_mode = @@GLOBAL.sql_mode;

Change SESSION.sql_mode value to ONLY_FULL_GROUP_BY

SET sql_mode = 'ONLY_FULL_GROUP_BY';
SELECT @@sql_mode, @@GLOBAL.sql_mode;
| @@sql_mode         | @@GLOBAL.sql_mode                            |

Revert the SESSION.sql_mode value to the GLOBAL.sql_mode value

SET sql_mode = @@GLOBAL.sql_mode;
SELECT @@sql_mode, @@GLOBAL.sql_mode;
| @@sql_mode                                   | @@GLOBAL.sql_mode                            |

Server Restart Persistent sql_mode using the option file

To set the SQL mode at server startup, use the --sql-mode="modes" option on the command line, or sql-mode="modes" in an option file such as my.cnf (Unix operating systems) or my.ini (Windows). [sic]

Please see your version of MySQL to determine the supported and default modes.

MySQL >= 5.7.5, <= 5.7.6 default


Please see the Option File Syntax for more information.

The syntax for specifying options in an option file is similar to command-line syntax. However, in an option file, you omit the leading two dashes from the option name and you specify only one option per line. For example, --quick and --host=localhost on the command line should be specified as quick and host=localhost on separate lines in an option file. To specify an option of the form --loose-opt_name in an option file, write it as loose-opt_name.

The value optionally can be enclosed within single quotation marks or double quotation marks, which is useful if the value contains a # comment character.

Default sql_mode values

Since the MySQL documentation per-version values have been removed, I have added them here for your reference.

MySQL >= 8.0.11 8.0.5 - 8.0.10 Skipped


MySQL >= 5.7.8, <= 8.0.4


MySQL 5.7.7


MySQL >= 5.7.5, <= 5.7.6


MySQL >= 5.6.6, <= 5.7.4


MySQL <= 5.6.5


What's the difference between .bashrc, .bash_profile, and .environment?

The main difference with shell config files is that some are only read by "login" shells (eg. when you login from another host, or login at the text console of a local unix machine). these are the ones called, say, .login or .profile or .zlogin (depending on which shell you're using).

Then you have config files that are read by "interactive" shells (as in, ones connected to a terminal (or pseudo-terminal in the case of, say, a terminal emulator running under a windowing system). these are the ones with names like .bashrc, .tcshrc, .zshrc, etc.

bash complicates this in that .bashrc is only read by a shell that's both interactive and non-login, so you'll find most people end up telling their .bash_profile to also read .bashrc with something like

[[ -r ~/.bashrc ]] && . ~/.bashrc

Other shells behave differently - eg with zsh, .zshrc is always read for an interactive shell, whether it's a login one or not.

The manual page for bash explains the circumstances under which each file is read. Yes, behaviour is generally consistent between machines.

.profile is simply the login script filename originally used by /bin/sh. bash, being generally backwards-compatible with /bin/sh, will read .profile if one exists.

What is the use of GO in SQL Server Management Studio & Transact SQL?

Use herDatabase
GO ; 

Code says to execute the instructions above the GO marker. My default database is myDatabase, so instead of using myDatabase GO and makes current query to use herDatabase

Convert Numeric value to Varchar

i think it should be

select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212


select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212

How create Date Object with values in java

I think the best way would be using a SimpleDateFormat object.

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2014-02-11";
Date dateObject = sdf.parse(dateString); // Handle the ParseException here

Using PowerShell credentials without being prompted for a password

There is another way, but...

DO NOT DO THIS IF YOU DO NOT WANT YOUR PASSWORD IN THE SCRIPT FILE (It isn't a good idea to store passwords in scripts, but some of us just like to know how.)

Ok, that was the warning, here's the code:

$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr

$cred will have the credentials from John Doe with the password "ABCDEF".

Alternative means to get the password ready for use:

$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

Looks like the solution has been baked into Homebrew now:

$ brew info postgresql
==> Caveats
To migrate existing data from a previous major version of PostgreSQL run:
  brew postgresql-upgrade-database

iOS app 'The application could not be verified' only on one device

I also encountered the same issue. Deleting the app didn't work, but when I tried deleting another app which was the current one's 'parent'(I copied the whole project from the previous app, modified some urls and images, then I clicked 'Run' and saw the unhappy 'could not be verified' dialog). Seems the issue is related to provisioning and code signing and/or some configurations of the project. Very tricky.

LINQ Aggregate algorithm explained

Aggregate is basically used to Group or Sum up data.

According to MSDN "Aggregate Function Applies an accumulator function over a sequence."

Example 1: Add all the numbers in a array.

int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate((total, nextValue) => total + nextValue);

*important: The initial aggregate value by default is the 1 element in the sequence of collection. i.e: the total variable initial value will be 1 by default.

variable explanation

total: it will hold the sum up value(aggregated value) returned by the func.

nextValue: it is the next value in the array sequence. This value is than added to the aggregated value i.e total.

Example 2: Add all items in an array. Also set the initial accumulator value to start adding with from 10.

int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate(10, (total, nextValue) => total + nextValue);

arguments explanation:

the first argument is the initial(starting value i.e seed value) which will be used to start addition with the next value in the array.

the second argument is a func which is a func that takes 2 int. this will hold same as before the sum up value(aggregated value) returned by the func after the calculation.

2.nextValue: : it is the next value in the array sequence. This value is than added to the aggregated value i.e total.

Also debugging this code will give you a better understanding of how aggregate work.

How to find the maximum value in an array?

Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.

sql query to find the duplicate records

You can do it in a single query:

Select t.Id, t.title, z.dupCount
From yourtable T
   (select title, Count (*) dupCount
    from yourtable 
    group By title
    Having Count(*) > 1) z
   On z.title = t.Title
order By dupCount Desc

Available text color classes in Bootstrap

The bootstrap 3 documentation lists this under helper classes: Muted, Primary, Success, Info, Warning, Danger.

The bootstrap 4 documentation lists this under utilities -> color, and has more options: primary, secondary, success, danger, warning, info, light, dark, muted, white.

To access them one uses the class text-[class-name]

So, if I want the primary text color for example I would do something like this:

<p class="text-primary">This text is the primary color.</p>

This is not a huge number of choices, but it's some.

Build unsigned APK file with Android Studio

AndroidStudio 3.4

After Grade Build Running complete, you will see the notification at bottom-right corner like.

Click on locate and you will see your debuggable APK

Select single item from a list

There are two easy ways, depending on if you want to deal with exceptions or get a default value.

You can use the First<T>() or the FirstOrDefault<T>() extension method to get the first result or default(T).

var list = new List<int> { 1, 2, 4 };
var result = list.Where(i => i == 3).First(); // throws InvalidOperationException
var result = list.Where(i => i == 3).FirstOrDefault(); // = 0

How can I create a UIColor from a hex string?

This is a function that takes a hex string and returns a UIColor.
(You can enter hex strings with either format: #ffffff or ffffff)


var color1 = hexStringToUIColor("#d3d3d3")

Swift 4:

func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)

    if ((cString.count) != 6) {
        return UIColor.gray

    var rgbValue:UInt32 = 0
    Scanner(string: cString).scanHexInt32(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)

Swift 3:

func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)

    if ((cString.characters.count) != 6) {
        return UIColor.gray

    var rgbValue:UInt32 = 0
    Scanner(string: cString).scanHexInt32(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)

Swift 2:

func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString

    if (cString.hasPrefix("#")) {
      cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))

    if ((cString.characters.count) != 6) {
      return UIColor.grayColor()

    var rgbValue:UInt32 = 0
    NSScanner(string: cString).scanHexInt(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)

Source: arshad/gist:de147c42d7b3063ef7bc

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

How to get JSON Key and Value?

It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):

$.each(result[0], function(key, value){
    console.log(key, value);

If you might have more than one element and you'd like to iterate over them all, you could nest $.each():

$.each(result, function(key, value){
    $.each(value, function(key, value){
        console.log(key, value);

How to format a Java string with leading zero?

Using Guava's Strings utility class:

Strings.padStart("Apple", 8, '0');

Equivalent of Math.Min & Math.Max for Dates?

// Two different dates
var date1 = new Date(2013, 05, 13); 
var date2 = new Date(2013, 04, 10) ;
// convert both dates in milliseconds and use Math.min function
var minDate = Math.min(date1.valueOf(), date2.valueOf());
// convert minDate to Date
var date = new Date(minDate);

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.



  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

Java Date cut off time information

For timestamps:

timestamp -= timestamp % (24 * 60 * 60 * 1000)

How to sort an array in Bash

Original response:

array=(a c b "f f" 3 5)
readarray -t sorted < <(for a in "${array[@]}"; do echo "$a"; done | sort)


$ for a in "${sorted[@]}"; do echo "$a"; done
f f

Note this version copes with values that contains special characters or whitespace (except newlines)

Note readarray is supported in bash 4+.

Edit Based on the suggestion by @Dimitre I had updated it to:

readarray -t sorted < <(printf '%s\0' "${array[@]}" | sort -z | xargs -0n1)

which has the benefit of even understanding sorting elements with newline characters embedded correctly. Unfortunately, as correctly signaled by @ruakh this didn't mean the the result of readarray would be correct, because readarray has no option to use NUL instead of regular newlines as line-separators.

Should I use "camel case" or underscores in python?

for everything related to Python's style guide: i'd recommend you read PEP8.

To answer your question:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Python IndentationError unindent does not match any outer indentation level

You have mixed indentation formatting (spaces and tabs)

On Notepad++

Change Tab Settings to 4 spaces

Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

Fix the current file mixed indentations

Select everything CTRL+A

Click TAB once, to add an indentation everywhere

Run SHIFT + TAB to remove the extra indentation, it will replace all TAB characters to 4 spaces.

How can I return the sum and average of an int array?


How to solve npm install throwing fsevents warning on non-MAC OS?

Instead of using --no-optional every single time, we can just add it to npm or yarn config.

For Yarn, there is a default no-optional config, so we can just edit that:

yarn config set ignore-optional true

For npm, there is no default config set, so we can create one:

npm config set ignore-optional true

Send inline image in email

Try this

 string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:filename\"></body></html>";
 AlternateView avHtml = AlternateView.CreateAlternateViewFromString
    (htmlBody, null, MediaTypeNames.Text.Html);

 LinkedResource inline = new LinkedResource("filename.jpg", MediaTypeNames.Image.Jpeg);
 inline.ContentId = Guid.NewGuid().ToString();

 MailMessage mail = new MailMessage();

 Attachment att = new Attachment(filePath);
 att.ContentDisposition.Inline = true;

 mail.From = from_email;
 mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot";
 mail.Body = String.Format(
            "<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" +
            @"<img src=""cid:{0}"" />", att.ContentId);

 mail.IsBodyHtml = true;

Where is the WPF Numeric UpDown control?


    <Style TargetType="{x:Type local:NumericUpDown}">
        <Setter Property="Template">
                <ControlTemplate TargetType="{x:Type local:NumericUpDown}">              
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                            <RepeatButton Grid.Row="0" Name="Part_UpButton"/>
                            <ContentPresenter Grid.Row="1"></ContentPresenter>
                            <RepeatButton Grid.Row="2" Name="Part_DownButton"/>

    <Window x:Class="numericButton2.MainWindow"
            Title="MainWindow" Height="350" Width="525">
            <local:NumericUpDown Margin="181,94,253,161" x:Name="ufuk" StepValue="4" Minimum="0" Maximum="20">            
            <TextBlock Margin="211,112,279,0" Text="{Binding ElementName=ufuk, Path=Value}" Height="20" VerticalAlignment="Top"></TextBlock>
public class NumericUpDown : Control
    private RepeatButton _UpButton;
    private RepeatButton _DownButton;
    public readonly static DependencyProperty MaximumProperty;
    public readonly static DependencyProperty MinimumProperty;
    public readonly static DependencyProperty ValueProperty;
    public readonly static DependencyProperty StepProperty;   
    static NumericUpDown()
        DefaultStyleKeyProperty.OverrideMetadata(typeof(NumericUpDown), new FrameworkPropertyMetadata(typeof(NumericUpDown)));
        MaximumProperty = DependencyProperty.Register("Maximum", typeof(int), typeof(NumericUpDown), new UIPropertyMetadata(10));
        MinimumProperty = DependencyProperty.Register("Minimum", typeof(int), typeof(NumericUpDown), new UIPropertyMetadata(0));
        StepProperty = DependencyProperty.Register("StepValue", typeof(int), typeof(NumericUpDown), new FrameworkPropertyMetadata(5));
        ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(NumericUpDown), new FrameworkPropertyMetadata(0));
    #region DpAccessior
    public int Maximum
        get { return (int)GetValue(MaximumProperty); }
        set { SetValue(MaximumProperty, value); }
    public int Minimum
        get { return (int)GetValue(MinimumProperty); }
        set { SetValue(MinimumProperty, value); }
    public int Value
        get { return (int)GetValue(ValueProperty); }
        set { SetCurrentValue(ValueProperty, value); }
    public int StepValue
        get { return (int)GetValue(StepProperty); }
        set { SetValue(StepProperty, value); }
    public override void OnApplyTemplate()
        _UpButton = Template.FindName("Part_UpButton", this) as RepeatButton;
        _DownButton = Template.FindName("Part_DownButton", this) as RepeatButton;
        _UpButton.Click += _UpButton_Click;
        _DownButton.Click += _DownButton_Click;

    void _DownButton_Click(object sender, RoutedEventArgs e)
        if (Value > Minimum)
            Value -= StepValue;
            if (Value < Minimum)
                Value = Minimum;

    void _UpButton_Click(object sender, RoutedEventArgs e)
        if (Value < Maximum)
            Value += StepValue;
            if (Value > Maximum)
                Value = Maximum;


How do you use the "WITH" clause in MySQL?

Mysql Developers Team announced that version 8.0 will have Common Table Expressions in MySQL (CTEs). So it will be possible to write queries like this:

  SELECT 1+n FROM my_cte WHERE n<10
SELECT * FROM my_cte;
| n    |
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    6 |
|    7 |
|    8 |
|    9 |
|   10 |
10 rows in set (0,00 sec)

How to convert array values to lowercase in PHP?


by continue

    function array_change_value_case($array, $case = CASE_LOWER){
        if ( ! is_array($array)) return false;
        foreach ($array as $key => &$value){
            if (is_array($value))
            call_user_func_array(__function__, array (&$value, $case ) ) ;
            $array[$key] = ($case == CASE_UPPER )
            ? strtoupper($array[$key])
            : strtolower($array[$key]);
        return $array;

    $arrays = array ( 1 => 'ONE', 2=> 'TWO', 3 => 'THREE',
                     'FOUR' => array ('a' => 'Ahmed', 'b' => 'basem',
                     'c' => 'Continue'),
                      5=> 'FIVE',

    $change_case = array_change_value_case($arrays, CASE_UPPER);
    echo "<pre>";
 [1] => one
 [2] => two
 [3] => three
 [FOUR] => Array
   [a] => ahmed
   [b] => basem
   [c] => continue

 [5] => five
 [6] => Array
   [0] => abcdef


iFrame Height Auto (CSS)

According to this post

You need to add the !important css modifier to your height percentages.

Hope this helps.

Convert String[] to comma separated string in java

As tempting and "cool" as the code may appear, do not use fold or reduce on large collections of strings, as these will suffer from the string concatenation problem

String[] strings = { "foo", "bar", "baz" };
Optional<String> result =
        .reduce((a, b) -> String.format("%s,%s", a, b));

Instead, as per other answers, use String.join() if you already have a collection, or a StringBuilder if not.

Can the :not() pseudo-class have multiple arguments?

Why :not just use two :not:


Yes, it is intentional

How do I use shell variables in an awk script?

I had to insert date at the beginning of the lines of a log file and it's done like below:

DATE=$(date +"%Y-%m-%d")
awk '{ print "'"$DATE"'", $0; }' /path_to_log_file/log_file.log

It can be redirect to another file to save

string to string array conversion in java

I guess there is simply no need for it, as it won't get more simple than

String[] array = {"name"};

Of course if you insist, you could write:

static String[] convert(String... array) {
   return array;

String[] array = convert("name","age","hobby"); 

[Edit] If you want single-letter Strings, you can use:

String[] s = "name".split("");

Unfortunately s[0] will be empty, but after this the letters n,a,m,e will follow. If this is a problem, you can use e.g. System.arrayCopy in order to get rid of the first array entry.

npm install doesn't create node_modules directory

my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine

Maintain the aspect ratio of a div with CSS

Just create a wrapper <div> with a percentage value for padding-bottom, like this:

.demoWrapper {
  padding: 10px;
  background: white;
  box-sizing: border-box;
  resize: horizontal;
  border: 1px dashed;
  overflow: auto;
  max-width: 100%;
  height: calc(100vh - 16px);

div {
  width: 100%;
  padding-bottom: 75%;
  background: gold; /** <-- For the demo **/
<div class="demoWrapper">

It will result in a <div> with height equal to 75% of the width of its container (a 4:3 aspect ratio).

This relies on the fact that for padding :

The percentage is calculated with respect to the width of the generated box's containing block [...] (source:, emphasis mine)

Padding-bottom values for other aspect ratios and 100% width :

aspect ratio  | padding-bottom value
    16:9      |       56.25%
    4:3       |       75%
    3:2       |       66.66%
    8:5       |       62.5%

Placing content in the div :

In order to keep the aspect ratio of the div and prevent its content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:

div.stretchy-wrapper {
  position: relative;

div.stretchy-wrapper > div {
  position: absolute;
  top: 0; bottom: 0; left: 0; right: 0;

Here's a demo and another more in depth demo

How add spaces between Slick carousel item

An improvement based on the post by Dishan TD (which removes the vertical margin as well):

    margin-left:  15px;
    margin-right:  15px;

  .slick-list {
    margin-left: -15px;
    margin-right: -15px;
    pointer-events: none;

Note: the pointer-events was necessary in my case, to be able to click on the left arrow.

How to split a string and assign it to variables

What you are doing is, you are accepting split response in two different variables, and strings.Split() is returning only one response and that is an array of string. you need to store it to single variable and then you can extract the part of string by fetching the index value of an array.

example :

 var hostAndPort string
    hostAndPort = ""
    sArray := strings.Split(hostAndPort, ":")
    fmt.Println("host : " + sArray[0])
    fmt.Println("port : " + sArray[1])

Android ImageView Fixing Image Size

In your case you need to

  1. Fix the ImageView's size. You need to use dp unit so that it will look the same in all devices.
  2. Set android:scaleType to fitXY

Below is an example:


For more information regarding ImageView scaleType please refer to the developer website.

Programmatically close aspx page from code behind

You just need to add this property in your asp:Button element (for example):


It works perfectly.

Remove warning messages in PHP

There is already answer with Error Control Operator but it lacks of explanation. You can use @ operator with every expression and it hides errors (except of Fatal Errors).

@$test['test']; //PHP Notice:  Undefined variable: test

@(14/0); // PHP Warning:  Division by zero

//This is not working. You can't hide Fatal Errors this way.
@customFuntion(); // PHP Fatal error:  Uncaught Error: Call to undefined function customFuntion()

For debugging it's fast and perfect method. But you should never ever use it on production nor permanent include in your local version. It will give you a lot of unnecessary irritation.

You should consider instead:

1. Error reporting settings as mentioned in accepted answer.

error_reporting(E_ERROR | E_PARSE);

or from PHP INI settings


2. Catching exceptions

try {
} catch (Error $e) {
    // Handle error
    echo $e->getMessage();


got the below error

PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm install vue npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! errno UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! request to failed, reason: unable to get local issuer certificate

npm ERR! A complete log of this run can be found in: npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm ERR!

Below command solved the issue:

npm config set strict-ssl false

Insert default value when parameter is null

You can use the COALESCE function in MS SQL.

INSERT INTO t ( value ) VALUES( COALESCE(@value, 'something') )

Personally, I'm not crazy about this solution as it is a maintenance nightmare if you want to change the default value.

My preference would be Mitchel Sellers proposal, but that doesn't work in MS SQL. Can't speak to other SQL dbms.

WPF Button with Image

You want to do something like this instead:

        <Image Source="Pictures/apple.jpg" />
        <TextBlock>Disconnect from Server</TextBlock>

Trim Cells using VBA in Excel

Worked for me perfectly as this:

Trims all selected cells. Beware of selecting full columns/rows :P.

Sub TrimSelected()    
Dim rng As Range, cell As Range    
Set rng = Selection   

For Each cell In rng    
cell = Trim(cell)   

Next cell    

End Sub

Establish a VPN connection in cmd

Is Powershell an option?

Start Powershell:


Create the VPN Connection: Add-VpnConnection

Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm] 

Edit VPN connections: Set-VpnConnection

Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]

Lookup VPN Connections: Get-VpnConnection

Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]

Connect: rasdial [connectionName]

rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]

You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial.

The results of Get-VpnConnection can be a little verbose. This can be simplified with a simple Select-Object filter:

Get-VpnConnection | Select-Object -Property Name

More information can be found here:

How to check for changes on remote (origin) Git repository

My regular question is rather "anything new or changed in repo" so whatchanged comes handy. Found it here.

git whatchanged origin/master -n 1

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

NameError: global name 'xrange' is not defined in Python 3

I solved the issue by adding this import
More info

from past.builtins import xrange

Get size of all tables in database

IF you only care about the empty wasted space in the database and not the individual tables you can consider the following:

If the database experiences large amount of data insertion and then deletions, maybe like in an ETL situation, this will cause too much unused space in the database as the file groups auto-grows but never auto-shrinks back.

You can see if this is the case by using the Properties page of your database. You can shrink (right click on the database > Tasks > Shrink) and claim some space back. But, if the underlying reason is still there, the database will grow back (and consume extra time trying to grow back and things gets slowed down until it grows enough - so don't do it in that case)

(KEK: key encryption key)

MySQL - UPDATE query based on SELECT Query

You can update values from another table using inner join like this

UPDATE [table1_name] AS t1 INNER JOIN [table2_name] AS t2 ON t1.column1_name] = t2.[column1_name] SET t1.[column2_name] = t2.column2_name];

Follow here to know how to use this query

or you can use select as subquery to do this

UPDATE [table_name] SET [column_name] = (SELECT [column_name] FROM [table_name] WHERE [column_name] = [value]) WHERE [column_name] = [value];

query explained in details here

Spring Security with roles and permissions

Just for sake of completeness (maybe someone else won't have to implement it from scratch):

We've implemented our own small library, as everyone else. It's supposed to make things easier, so that our developers don't have to reimplement it each time. It would be great if spring security would provide support of rbac out of the box, as this approach is much better than the default permission based one.

Have a look at Github (OSS, MIT license) to see if it suits your needs. It's basically only addressing the role <-> privileges mapping. The missing piece, you'll have to provide on your own is basically the user <-> roles mapping, e.g. by mapping groups (racf/ad groups) to roles (1:1) or by implementing an additional mapping. That one's different in each project, so it doesn't make sense to provide some implementation.

We've basically used this internally, so that we can start with rbac from the beginning. We can still replace it with some other implementation later on, if the application is growing, but it's important for us to get the setup right at the beginning.

If you don't use rbac, there's a good chance, that the permissions are scattered throughout the codebase and you'll have a hard time to extract/group those (into roles) later on. The generated graphs do also help to reason about it/restructure it later on.

Cut Java String at a number of character

String strOut = str.substring(0, 8) + "...";

How to remove anaconda from windows completely?

Method1: To uninstall Anaconda3 go to the Anaconda3 folder, there u will be able to find an executable called Uninstall-Anaconda3.exe, double click on it. This should uninstall ur application. There are times when the shortcut of anaconda command prompt,jupyter notebook, spyder, etc exists, so delete those files too.

Method2 (Windows8): Go to control panel->Programs->Uninstall a Program and then select Anaconda3(Python3.1. 64-bit)in the menu.

npm install won't install devDependencies

Check if npm config production value is set to true. If this value is true, it will skip over the dev dependencies.

Run npm config get production

To set it: npm config set -g production false

MySQL - Trigger for updating same table after insert

This is how I update a row in the same table on insert

activationCode and email are rows in the table USER. On insert I don't specify a value for activationCode, it will be created on the fly by MySQL.

Change username with your MySQL username and db_name with your db name.

CREATE DEFINER=`username`@`localhost` 
       TRIGGER `db_name`.`user_BEFORE_INSERT` 
       BEFORE INSERT ON `user` 
            SET new.activationCode = MD5(;

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute Xpath: It uses Complete path from the Root Element to the desire element.

Relative Xpath: You can simply start by referencing the element you want and go from there.

Relative Xpaths are always preferred as they are not the complete paths from the root element. (//html//body). Because in future, if any webelement is added/removed, then the absolute Xpath changes. So Always use Relative Xpaths in your Automation.

Below are Some Links which you can Refer for more Information on them.

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Perfectly fine.
You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().
So if m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile..

Update: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)

SecurityError: The operation is insecure - window.history.pushState()

We experienced the SecurityError: The operation is insecure when a user disabled their cookies prior to visiting our site, any subsequent XHR requests trying to use the session would obviously fail and cause this error.

How to set default values in Go structs

There is a way of doing this with tags, which allows for multiple defaults.

Assume you have the following struct, with 2 default tags default0 and default1.

type A struct {
   I int    `default0:"3" default1:"42"`
   S string `default0:"Some String..." default1:"Some Other String..."`

Now it's possible to Set the defaults.

func main() {

ptr := &A{}

Set(ptr, "default0")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=3 ptr.S=Some String...

Set(ptr, "default1")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=42 ptr.S=Some Other String...

Here's the complete program in a playground.

If you're interested in a more complex example, say with slices and maps, then, take a look at creasty/defaultse

How can I beautify JSON programmatically?

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

How to search text using php if ($text contains "World")

  /* */

  function search($search, $string) {

    $pos = strpos($string, $search);  

    if ($pos === false) {

      return "not found";     

    } else {

      return "found in " . $pos;



  echo search("world", "hello world");

Embed PHP online:

body, html, iframe { _x000D_
  width: 100% ;_x000D_
  height: 100% ;_x000D_
  overflow: hidden ;_x000D_
<iframe src="" ></iframe>

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

I have experience this issue in past. Based on that I can say that generally we get this issue if your dataset has multiple fieldnames that points to same field source. Take a look into following posts for detail error description

In your case, you should check your all field names returned by Sp prc_RPT_Select_BI_Completes_Data_View and make sure that all fields has unique name.

an htop-like tool to display disk activity in linux

nmon shows a nice display of disk activity per device. It is available for linux.

? Disk I/O ?????(/proc/diskstats)????????all data is Kbytes per second???????????????????????????????????????????????????????????????
?DiskName Busy  Read WriteKB|0          |25         |50          |75       100|                                                      ?
?sda        0%    0.0  127.9|>                                                |                                                      ?
?sda1       1%    0.0  127.9|>                                                |                                                      ?
?sda2       0%    0.0    0.0|>                                                |                                                      ?
?sda5       0%    0.0    0.0|>                                                |                                                      ?
?sdb       61%  385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                 |                                                      ?
?sdb1      61%  385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                 |                                                      ?
?sdc       52%  353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR   >                  |                                                      ?
?sdc1      53%  353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR   >                  |                                                      ?
?sdd       56%  359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW>                    |                                                      ?
?sdd1      56%  359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW>                    |                                                      ?
?sde       57%  371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                   |                                                      ?
?sde1      57%  371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                   |                                                      ?
?sdf       53%  371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR    >                 |                                                      ?
?sdf1      53%  371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR    >                 |                                                      ?
?md0        0% 1726.0 2093.6|>disk busy not available                         |                                                      ?

How to decompile an APK or DEX file on Android platform?

I have created a tool that combines dex2jar, jd-core and apktool: Just checkout the project locally and run the script as documented and you'll get all the resources and sources decompiled.

multiprocessing: How do I share a dict among multiple processes?

multiprocessing is not like threading. Each child process will get a copy of the main process's memory. Generally state is shared via communication (pipes/sockets), signals, or shared memory.

Multiprocessing makes some abstractions available for your use case - shared state that's treated as local by use of proxies or shared memory:

Relevant sections:

HTML how to clear input using javascript?

For me this is the best way:

<form id="myForm">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Reset form">

function myFunction() {

How can I drop a table if there is a foreign key constraint in SQL Server?

Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;

MySQL – Temporarily disable Foreign Key Checks or Constraints

Insert auto increment primary key to existing table

Export your table, then empty your table, then add field as unique INT, then change it to AUTO_INCREMENT, then import your table again that you exported previously.

JUnit Eclipse Plugin?

You might want to try out Quick JUnit:

The plugin is stable and it allows switching between production and test code. I am currently using Eclipse Mars 4.5 and the plugin is supported for this release as well as for the following:

Luna (4.4), Kepler (4.3), Juno (4.2, 3.8), Previous to Juno (<=4.1)

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:


Google Maps JS API v3 - Simple Multiple Marker Example

  • I know this answer is very much late. But I wish this will help other developers also. :-)
  • The Following code will add multiple markers on the google map with the information window.
  • And this code can be used to plot any number of markers on the map.
  • Please put your Google Map API key to the correct position of this code. (I have marked that as "Your API Key")

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Google Map</title>
            height: 600px;
            width: 100%;

<h1>My Google Map`</h1>
<div id="map"></div>

        function initMap(){
          //Map options
            var options = {
                center:{lat:42.3601, lng:-71.0589}
            // new map
            var map = new google.maps.Map(document.getElementById('map'), options);
            // customer marker
            var iconBase = '';
            //array of Marrkeers
            var markers = [
                coords:{lat: 42.4668, lng: -70.9495},img:iconBase,con:'<h3> This Is your Content <h3>'
                coords:{lat: 42.8584, lng: -70.9300},img:iconBase,con:'<h3> This Is your Content <h3>'
                coords:{lat: 42.7762, lng: -71.0773},img:iconBase,con:'<h3> This Is your Content <h3>'

            //loopthrough markers
            for(var i = 0; i <markers.length; i++){
              //add markeers

            //function for the plotting markers on the map
            function addMarker (props){
              var marker = new google.maps.Marker({
                position: props.coords,
              var infoWindow = new google.maps.InfoWindow({
              marker.addListener("click", () => {
      , marker);



Remove a string from the beginning of a string

This will remove first match wherever it is found i.e., start or middle or end.

$str = substr($str, 0, strpos($str, $prefix)).substr($str, strpos($str, $prefix)+strlen($prefix));

SQL Server: converting UniqueIdentifier to string in a case statement

It is possible to use the convert function here, but 36 characters are enough to hold the unique identifier value:

convert(nvarchar(36), requestID) as requestID

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

The only difference between files that causing the issue is the 8th byte of file

CA FE BA BE 00 00 00 33 - Java 7


CA FE BA BE 00 00 00 32 - Java 6

Setting -XX:-UseSplitVerifier resolves the issue. However, the cause of this issue is

Posting JSON Data to ASP.NET MVC

If you've got ther JSON data coming in as a string (e.g. '[{"id":1,"name":"Charles"},{"id":8,"name":"John"},{"id":13,"name":"Sally"}]')

Then I'd use and use Linq to JSON to get the values out...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)

    if (Request["items"] != null)
        var items = Request["items"].ToString(); // Get the JSON string
        JArray o = JArray.Parse(items); // It is an array so parse into a JArray
        var a = o.SelectToken("[0].name").ToString(); // Get the name value of the 1st object in the array
        // a == "Charles"

Confused about Service vs Factory

This is how I understood the difference between them in terms of design patterns:

Service: Return a type, that will be newed to create an object of that type. If Java analogy is used, Service returns a Java Class definition.

Factory: Returns a concrete object that can be immediately used. In Java Analogy a Factory returns a Java Object.

The part that often confuses people (including myself) is that when you inject a Service or a Factory in your code they can be used the same way, what you get in your code in both cases is a concrete object that you can immediately invoke. Which means in case of the Service, angular calls "new" on the service declaration on behalf of you. I think this is a convoluted concept.

How to dump a table to console?

Feel free to browse the Lua Wiki on table serialization. It lists several ways on how to dump a table to the console.

You just have to choose which one suits you best. There are many ways to do it, but I usually end up using the one from Penlight:

> t = { a = { b = { c = "Hello world!", 1 }, 2, d = { 3 } } }
> require 'pl.pretty'.dump(t)
  a = {
    d = {
    b = {
      c = "Hello world!",

Declare global variables in Visual Studio 2010 and VB.NET

Okay. I finally found what actually works to answer the question that seems to be asked;

"When needing many modules and forms, how can I declare a variable to be public to all of them such that they each reference the same variable?"

Amazingly to me, I spent considerable time searching the web for that seemingly simple question, finding nothing but vagueness that left me still getting errors.

But thanks to Cody Gray's link to an example, I was able to discern a proper answer;

Situation; You have multiple Modules and/or Forms and want to reference a particular variable from each or all.

"A" way that works; On one module place the following code (wherein "DefineGlobals" is an arbitrarily chosen name);

Public Module DefineGlobals

Public Parts As Integer                 'Assembled-particle count
Public FirstPrtAff As Long              'Addr into Link List 
End Module

And then in each Module/Form in need of addressing that variable "Parts", place the following code (as an example of the "InitForm2" form);

Public Class InitForm2
Private Sub InitForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Parts = Parts + 3

End Sub

End Class

And perhaps another Form; Public Class FormX

Sub CreateAff()

   Parts = 1000

End Sub 

 End Class

That type of coding seems to have worked on my VB2008 Express and seems to be all needed at the moment (void of any unknown files being loaded in the background) even though I have found no end to the "Oh btw..." surprise details. And I'm certain a greater degree of standardization would be preferred, but the first task is simply to get something working at all, with or without standards.

Nothing beats exact and well worded, explicit examples.

Thanks again, Cody

How to declare an array in Python?

You don't actually declare things, but this is how you create an array in Python:

from array import array
intarray = array('i')

For more info see the array module:

Now possible you don't want an array, but a list, but others have answered that already. :)

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {

[1] "foo"

How to force Chrome browser to reload .css file while debugging in Visual Studio?

For macOS Chrome:

  1. Open developers tools cmd+alt+i
  2. Click three dots on the top right corner in developers tools
  3. Click settings
  4. Scroll down to Network
  5. Enable Disable cache (while DevTools is open) see screenshot: enter image description here

What is a NoReverseMatch error, and how do I fix it?

It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView - I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name for the new class, it worked fine.

What is the difference between the kernel space and the user space?

IN short kernel space is the portion of memory where linux kernel runs (top 1 GB virtual space in case of linux) and user space is the portion of memory where user application runs( bottom 3 GB of virtual memory in case of Linux. If you wanna know more the see the link given below :)

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

With Eclipse and Windows:

you have to copy 2 files - - here : C:\Eclipse\CONTENER\TOMCAT\apache-tomcat-7\lib

How to detect current state within directive


This answer was for a much older release of Ui-Router. For the more recent releases (0.2.5+), please use the helper directive ui-sref-active. Details here.

Original Answer:

Include the $state service in your controller. You can assign this service to a property on your scope.

An example:

$scope.$state = $state;

Then to get the current state in your templates:


To check if a state is current active:


This method returns true if the state is included, even if it's part of a nested state. If you were at a nested state, user.details, and you checked for $state.includes('user'), it'd return true.

In your class example, you'd do something like this:

ng-class="{active: $state.includes('stateName')}"

500 internal server error at GetResponse()

In my case I just remove the SoapAction instruction from the HttpWebRequest object. So, I don't define .Headers.Add("SOAPAction","someurl") in HttpWebRequest definitions and my code works fine.

ResultXML is an XDocument. ResultString is a string.

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
    //req.Headers.Add("SOAPAction", "");
    req.ProtocolVersion = HttpVersion.Version11;
    req.ContentType = "text/xml;charset=\"utf-8\"";
    req.Accept = "text/xml";
    req.KeepAlive = true;
    req.Method = "POST";        

    using (Stream stm = req.GetRequestStream())
        using (StreamWriter stmw = new StreamWriter(stm))
    using (StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream()))
        string result = responseReader.ReadToEnd();
        ResultXML = XDocument.Parse(result);
        ResultString = result;      

Error: Argument is not a function, got undefined

Turns out it's the Cache of the browser, using Chrome here. Simply check the "Disable cache" under Inspect (Element) solved my problem.

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:


Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

Generic type conversion FROM string

Check the static Nullable.GetUnderlyingType. - If the underlying type is null, then the template parameter is not Nullable, and we can use that type directly - If the underlying type is not null, then use the underlying type in the conversion.

Seems to work for me:

public object Get( string _toparse, Type _t )
    // Test for Nullable<T> and return the base type instead:
    Type undertype = Nullable.GetUnderlyingType(_t);
    Type basetype = undertype == null ? _t : undertype;
    return Convert.ChangeType(_toparse, basetype);

public T Get<T>(string _key)
    return (T)Get(_key, typeof(T));

public void test()
    int x = Get<int>("14");
    int? nx = Get<Nullable<int>>("14");

Java Regex Capturing Groups

The issue you're having is with the type of quantifier. You're using a greedy quantifier in your first group (index 1 - index 0 represents the whole Pattern), which means it'll match as much as it can (and since it's any character, it'll match as many characters as there are in order to fulfill the condition for the next groups).

In short, your 1st group .* matches anything as long as the next group \\d+ can match something (in this case, the last digit).

As per the 3rd group, it will match anything after the last digit.

If you change it to a reluctant quantifier in your 1st group, you'll get the result I suppose you are expecting, that is, the 3000 part.

Note the question mark in the 1st group.

String line = "This order was placed for QT3000! OK?";
Pattern pattern = Pattern.compile("(.*?)(\\d+)(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    System.out.println("group 1: " +;
    System.out.println("group 2: " +;
    System.out.println("group 3: " +;


group 1: This order was placed for QT
group 2: 3000
group 3: ! OK?

More info on Java Pattern here.

Finally, the capturing groups are delimited by round brackets, and provide a very useful way to use back-references (amongst other things), once your Pattern is matched to the input.

In Java 6 groups can only be referenced by their order (beware of nested groups and the subtlety of ordering).

In Java 7 it's much easier, as you can use named groups.

Understanding the Gemfile.lock file

It looks to me like PATH lists the first-generation dependencies directly from your gemspec, whereas GEM lists second-generation dependencies (i.e. what your dependencies depend on) and those from your Gemfile. PATH::remote is . because it relied on a local gemspec in the current directory to find out what belongs in PATH::spec, whereas GEM::remote is, since that's where it had to go to find out what belongs in GEM::spec.

In a Rails plugin, you'll see a PATH section, but not in a Rails app. Since the app doesn't have a gemspec file, there would be nothing to put in PATH.

As for DEPENDENCIES, states:

Runtime dependencies in your gemspec are treated like base dependencies, 
and development dependencies are added by default to the group, :development

The Gemfile generated by rails plugin new my_plugin says something similar:

# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.

What this means is that the difference between

s.add_development_dependency "july" # (1)


s.add_dependency "july" # (2)

is that (1) will only include "july" in Gemfile.lock (and therefore in the application) in a development environment. So when you run bundle install, you'll see "july" not only under PATH but also under DEPENDENCIES, but only in development. In production, it won't be there at all. However, when you use (2), you'll see "july" only in PATH, not in DEPENDENCIES, but it will show up when you bundle install from a production environment (i.e. in some other gem that includes yours as a dependency), not only development.

These are just my observations and I can't fully explain why any of this is the way it is but I welcome further comments.

Generating a random hex color code with PHP

If someone wants to generate light colors

sprintf('#%06X', mt_rand(0xFF9999, 0xFFFF00));

Where does Android app package gets installed on phone

An application when installed on a device or on an emulator will install at:


The APK itself is placed in the /data/app/ folder.

These paths, however, are in the System Partition and to access them, you will need to have root. This is for a device. On the emulator, you can see it in your logcat (DDMS) in the File Explorer tab

By the way, it only shows the package name that is defined in your Manifest.XML under the package="APP_PACKAGE_NAME" attribute. Any other packages you may have created in your project in Eclipse do not show up here.

Error message "Strict standards: Only variables should be passed by reference"

The second snippet doesn't work either and that's why.

array_shift is a modifier function, that changes its argument. Therefore it expects its parameter to be a reference, and you cannot reference something that is not a variable. See Rasmus' explanations here: Strict standards: Only variables should be passed by reference

Angular 4 checkbox change value

try this worked for me :

checkValue(event: any) {
    this.siteSelected.majeur = event;

VLook-Up Match first 3 characters of one column with another column


Clearing Magento Log Data

SET foreign_key_checks = 0;
TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;
SET foreign_key_checks = 1;

Turn off axes in subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)

To turn off axes for all subplots, do either:

[axi.set_axis_off() for axi in ax.ravel()]


map(lambda axi: axi.set_axis_off(), ax.ravel())

How to format a URL to get a file from Amazon S3?

Documentation here, and I'll use the Frankfurt region as an example.

There are 2 different URL styles:

But this url does not work:

The message is explicit: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

I may be talking about another problem because I'm not getting NoSuchKey error but I suspect the error message has been made clearer over time.

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.


Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
    else if(btn.Tag == "Goodbye")
    // etc.

Disclaimer : That's a contrived example; don't do that!


Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
    if(/* some condition*/)
       // Cancel this event
       e.Cancel = true;

Are "while(true)" loops so bad?

It's your gun, your bullet and your foot...

It's bad because you are asking for trouble. It won't be you or any of the other posters on this page who have examples of short/simple while loops.

The trouble will start at some very random time in the future. It might be caused by another programmer. It might be the person installing the software. It might be the end user.

Why? I had to find out why a 700K LOC app would gradually start burning 100% of the CPU time until every CPU was saturated. It was an amazing while (true) loop. It was big and nasty but it boiled down to:

x = read_value_from_database()
while (true) 
 if (x == 1)
 else if (x ==2)
and lots more else if conditions

There was no final else branch. If the value did not match an if condition the loop kept running until the end of time.

Of course, the programmer blamed the end users for not picking a value the programmer expected. (I then eliminated all instances of while(true) in the code.)

IMHO it is not good defensive programming to use constructs like while(true). It will come back to haunt you.

(But I do recall professors grading down if we did not comment every line, even for i++;)

ASP.NET strange compilation error

I removed Roslyn related packages by NuGet and it does work now.

Roslyn related packages:

  • Microsoft.CodeDom.Providers.DotNetCompilerPlatform
  • Microsoft.Net.Compilers

P.S: My local IIS doesn't have any problem with Roslyn but as I publish the project on the server (this is why I don't think the server supports Roslyn), it shows the following error message:

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: The compiler failed with error code -532462766.

Show Detailed Compiler Output:

C:\Windows\SysWOW64\inetsrv>D:\...\wwwroot\bin\roslyn\csc.exe /t:library /utf8output /nostdlib+ /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\08433893\97359c03_e1abd201\System.Web.WebPages.Deployment.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Extensions\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.Extensions.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\2574b56e\eed229e7_dfabd201\Autofac.Integration.WebApi.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.Web.PageInspector.Loader\v4.0_1.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Web.PageInspector.Loader.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\2da0bd13\b2333a9c_e0abd201\System.Net.Http.Formatting.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\99fd000f\fe3c7c0e_e1abd201\System.Web.WebPages.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\695a732a\7a32e84e_e2abd201\WebGrease.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.Activities.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\ca091706\f1f4ae28_78afd201\Core.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\ce3c4f34\2b7b911a_e0abd201\EntityFramework.SqlServer.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\c73494ac\8f453228_78afd201\CommonViewModels.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.Web.Infrastructure\v4.0_1.0.0.0__31bf3856ad364e35\Microsoft.Web.Infrastructure.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\03d13810\0845500f_e1abd201\System.Web.Http.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\5cc83c73\51b7f8fe_e0abd201\System.Web.Http.WebHost.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\290d81d3\fb074b29_78afd201\Data.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activation\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activation.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\7a5d0293\283dbf3a_e0abd201\GridMvc.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\eb50e8c6\1900fa91_e0abd201\System.Web.Razor.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\a7d6ceb3\4c5f9c2c_78afd201\Web.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.Linq.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Deployment\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Deployment.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.DynamicData\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.DynamicData.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\3bd130ea\7b432ba6_e0abd201\System.Web.Optimization.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel\v4.0_4.0.0.0__b77a5c561934e089\System.ServiceModel.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\8486430e\674206e7_dfabd201\Autofac.Integration.Mvc.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\c0d9cc06\83811806_e1abd201\System.Web.WebPages.Razor.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\8835020a\58c1c60e_e1abd201\System.Web.Helpers.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\30c33f64\00d8a820_d154d201\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\6ea00d7f\02323228_78afd201\Extensions.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\f8f1e397\e9660a29_78afd201\Services.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\ff57243f\bb5e8b92_e0abd201\System.Web.Mvc.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Deployment\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.WebPages.Deployment.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_4.0.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\fd2c5d18\00ae74dd_e7acd201\Autofac.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ComponentModel.DataAnnotations\v4.0_4.0.0.0__31bf3856ad364e35\System.ComponentModel.DataAnnotations.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.ApplicationServices\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.ApplicationServices.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\a44c79bb\74928fbb_e0abd201\EntityFramework.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Services\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\227cd18a\6ab66d28_78afd201\Domain.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\assembly\dl3\8cbb60ec\00788858_b3abd201\Newtonsoft.Json.dll" /out:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\App_Code._bgj8eyw.dll" /debug- /optimize+ /warnaserror- /w:4 /nowarn:1659;1699;1701;612;618 /langversion:6 /nowarn:1659;1699;1701  "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\App_Code._bgj8eyw.0.cs" "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\a47e39f5\cc42bc06\App_Code._bgj8eyw.1.cs"

How to uninstall the Roslyn packages.

In the Solution Explorer, by Right-Click on the web project, select Manage NuGet Packages....
Go to Installed tab then search the related Roslyn packages as mentioned at above.
Use Uninstall button to delete them.

Setting Oracle 11g Session Timeout

Check applications connection Pool settings, rather than altering any session timout settings on the oracle db. It's normal that they time out.

Have a look here:

Are you sure that you have set the "pooled" parameter correctly?

Greetings, Lars

Your config seems ok on first glimpse. I came across this issue today. Maybe it is related to your pain:
"Infinite loop of exceptions if the application is started when the database is down for maintenance"

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I hope this will help somebody, I solved the problem like this

There was a problem because the database was not open. Command startup opens the database.

This you can solve with command alter database open in some case with alter database open resetlogs

$ sqlplus / sysdba

SQL> startup
ORACLE instance started.

Total System Global Area 1073741824 bytes
Fixed Size          8628936 bytes
Variable Size         624952632 bytes
Database Buffers      436207616 bytes
Redo Buffers            3952640 bytes
Database mounted.
Database opened.

SQL> conn user/pass123

Programmatically navigate using React router

Using the "useHistory" hook is the best option if you're using a newer version of react

How to install an apk on the emulator in Android Studio?

Just download the apk from talkback website

Drag the downloaded apk to the started emulator, Go to settings on emulator > Search for talkback, you will now find it there

Compiling problems: cannot find crt1.o

I had the same problem today, I solved it by installing recommended packages: libc6-dev-mipsel-cross libc6-dev-mipsel-cross, libc-dev-mipsel-cross

This worked:

sudo apt-get install libc6-dev-mipsel-cross

Load jQuery with Javascript and use jQuery

From the DevTools console, you can run:

document.getElementsByTagName("head")[0].innerHTML += '<script type="text/javascript" src="//"><\/script>';

Check the available jQuery version at

To check whether it's loaded, see: Checking if jquery is loaded using Javascript.

Using CSS td width absolute, position

Try to use

table {
  table-layout: auto;

If you use Bootstrap, class table has table-layout: fixed; by default.

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

jQuery: Change button text on click

try this, this javascript code to change text all time to click button.

html code

<button class="SeeMore2">See More</button>


        var $this = $(this);
            $this.text('See More');         
        } else {
            $this.text('See Less');

How to parse/read a YAML file into a Python object?

If your YAML file looks like this:

# tree format
        name: Node 1
            name: Node 1-1
        name: Node 2
            name: Node 2-1

And you've installed PyYAML like this:

pip install PyYAML

And the Python code looks like this:

import yaml
with open('tree.yaml') as f:
    # use safe_load instead load
    dataMap = yaml.safe_load(f)

The variable dataMap now contains a dictionary with the tree data. If you print dataMap using PrettyPrint, you will get something like:

    'treeroot': {
        'branch1': {
            'branch1-1': {
                'name': 'Node 1-1'
            'name': 'Node 1'
        'branch2': {
            'branch2-1': {
                'name': 'Node 2-1'
            'name': 'Node 2'

So, now we have seen how to get data into our Python program. Saving data is just as easy:

with open('newtree.yaml', "w") as f:
    yaml.dump(dataMap, f)

You have a dictionary, and now you have to convert it to a Python object:

class Struct:
    def __init__(self, **entries): 

Then you can use:

>>> args = your YAML dictionary
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s...

and follow "Convert Python dict to object".

For more information you can look at and this.

How to limit the maximum files chosen when using multiple file input

You should also consider using libraries to do that: they allow limiting and much more:

They are also available at

Header set Access-Control-Allow-Origin in .htaccess doesn't work

Just for the record, I was running into the exact same problem and none of the answers worked.

I used a headers checker tool:

I was testing with my IP ( and what came back was the following:

HTTP/1.1 301 Moved Permanently => 
Date => Sat, 10 Jan 2015 04:03:35 GMT
Server => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1
Location =>
Content-Length => 380
Connection => close
Content-Type => text/html; charset=iso-8859-1

There was a redirection happening and the AJAX request does not honor/follow redirects.

It turned out to be the missing slash at the end of the domain (

I tested again with slash at the end and I got this below. Added a slash in the script too, and it was now working.

HTTP/1.1 200 OK => 
Date => Sat, 10 Jan 2015 04:03:53 GMT
Server => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By => PHP/5.3.8
Access-Control-Allow-Origin => *
Access-Control-Allow-Methods => PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Headers => *
Content-Length => 1435
Connection => close
Content-Type => text/html

Use this tool to test if your headers are good and to troubleshoot what is happening.

How do I compute the intersection point of two lines?

If your lines are multiple points instead, you can use this version.

enter image description here

import numpy as np
import matplotlib.pyplot as plt
5 April 2017
Based on:    

def _rect_inter_inner(x1,x2):
    return S1,S2,S3,S4

def _rectangle_intersection_(x1,y1,x2,y2):


    ii,jj=np.nonzero(C1 & C2 & C3 & C4)
    return ii,jj

def intersection(x1,y1,x2,y2):
INTERSECTIONS Intersections of curves.
   Computes the (x,y) locations where two curves intersect.  The curves
   can be broken with NaNs or have vertical segments.
    a, b = 1, 2
    phi = np.linspace(3, 10, 100)
    x1 = a*phi - b*np.sin(phi)
    y1 = a - b*np.cos(phi)




    for i in range(n):

    in_range= (T[0,:] >=0) & (T[1,:] >=0) & (T[0,:] <=1) & (T[1,:] <=1)

    return xy0[:,0],xy0[:,1]

if __name__ == '__main__':

    # a piece of a prolate cycloid, and am going to find
    a, b = 1, 2
    phi = np.linspace(3, 10, 100)
    x1 = a*phi - b*np.sin(phi)
    y1 = a - b*np.cos(phi)


How do I store an array in localStorage?

Another solution would be to write a wrapper that store the array like this:

localStorage.setItem('names_length', names.length);
localStorage.setItem('names_0', names[0]);
localStorage.setItem('names_1', names[1]);
localStorage.setItem('names_' + n, names[n]);

Removes the overhead of converting to JSON, but would be annoying if you need to remove elements, as you would have to re-index the array :)

How to recover Git objects damaged by hard disk failure?

Here are the steps I followed to recover from a corrupt blob object.

1) Identify corrupt blob

git fsck --full
  error: inflate: data stream error (incorrect data check)
  error: sha1 mismatch 241091723c324aed77b2d35f97a05e856b319efd
  error: 241091723c324aed77b2d35f97a05e856b319efd: object corrupt or missing

Corrupt blob is 241091723c324aed77b2d35f97a05e856b319efd

2) Move corrupt blob to a safe place (just in case)

mv .git/objects/24/1091723c324aed77b2d35f97a05e856b319efd ../24/

3) Get parent of corrupt blob

git fsck --full
  Checking object directories: 100% (256/256), done.
  Checking objects: 100% (70321/70321), done.
  broken link from    tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
              to    blob 241091723c324aed77b2d35f97a05e856b319efd

Parent hash is 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180.

4) Get file name corresponding to corrupt blob

git ls-tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
  100644 blob 241091723c324aed77b2d35f97a05e856b319efd    dump.tar.gz

Find this particular file in a backup or in the upstream git repository (in my case it is dump.tar.gz). Then copy it somewhere inside your local repository.

5) Add previously corrupted file in the git object database

git hash-object -w dump.tar.gz

6) Celebrate!

git gc
  Counting objects: 75197, done.
  Compressing objects: 100% (21805/21805), done.
  Writing objects: 100% (75197/75197), done.
  Total 75197 (delta 52999), reused 69857 (delta 49296)

Selenium Webdriver move mouse to Point

IMHO you should pay your attention to Robot.class

Still if you want to move the mouse pointer physically, you need to take different approach using Robot class

  Point coordinates = driver.findElement("ctl00_portalmaster_txtUserName")).getLocation();
  Robot robot = new Robot();

Webdriver provide document coordinates, where as Robot class is based on Screen coordinates, so I have added +120 to compensate the browser header.
Screen Coordinates: These are coordinates measured from the top left corner of the user's computer screen. You'd rarely get coordinates (0,0) because that is usually outside the browser window. About the only time you'd want these coordinates is if you want to position a newly created browser window at the point where the user clicked. In all browsers these are in event.screenX and event.screenY.
Window Coordinates: These are coordinates measured from the top left corner of the browser's content area. If the window is scrolled, vertically or horizontally, this will be different from the top left corner of the document. This is rarely what you want. In all browsers these are in event.clientX and event.clientY.
Document Coordinates: These are coordinates measured from the top left corner of the HTML Document. These are the coordinates that you most frequently want, since that is the coordinate system in which the document is defined.

More details you can get here

Hope this be helpful to you.

Is this very likely to create a memory leak in Tomcat?

Sometimes this has to do with configuration changes. When we upgraded from Tomncat 6.0.14 to 6.0.26, we had seen something similar. here is the solution

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

Where you have written the code

public class Main {
    public static void main(String args[])
        Calculate obj = new Calculate(1,2,'+');

Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.

Sticky Header after scrolling down

window bottom scroll to top scroll using jquery.


 var lastScroll = 0;

 $(document).ready(function($) {


 setTimeout(function() { 
    var scroll = $(window).scrollTop();
    if (scroll > lastScroll) {


    if (scroll == 0) {

    else if (scroll < lastScroll - 5) {


    lastScroll = scroll;

How to loop over a Class attributes in Java?

Simple way to iterate over class fields and obtain values from object:

 Class<?> c = obj.getClass();
 Field[] fields = c.getDeclaredFields();
 Map<String, Object> temp = new HashMap<String, Object>();

 for( Field field : fields ){
      try {
           temp.put(field.getName().toString(), field.get(obj));
      } catch (IllegalArgumentException e1) {
      } catch (IllegalAccessException e1) {

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

I've always thought that DLLs and shared objects are just different terms for the same thing - Windows calls them DLLs, while on UNIX systems they're shared objects, with the general term - dynamically linked library - covering both (even the function to open a .so on UNIX is called dlopen() after 'dynamic library').

They are indeed only linked at application startup, however your notion of verification against the header file is incorrect. The header file defines prototypes which are required in order to compile the code which uses the library, but at link time the linker looks inside the library itself to make sure the functions it needs are actually there. The linker has to find the function bodies somewhere at link time or it'll raise an error. It ALSO does that at runtime, because as you rightly point out the library itself might have changed since the program was compiled. This is why ABI stability is so important in platform libraries, as the ABI changing is what breaks existing programs compiled against older versions.

Static libraries are just bundles of object files straight out of the compiler, just like the ones that you are building yourself as part of your project's compilation, so they get pulled in and fed to the linker in exactly the same way, and unused bits are dropped in exactly the same way.

How to create SPF record for multiple IPs?

Try this:

v=spf1 ~all

How to cut an entire line in vim and paste it?

dd in command mode (after pressing escape) will cut the line, p in command mode will paste.


For a bonus, d and then a movement will cut the equivalent of that movement, so dw will cut a word, d<down-arrow> will cut this line and the line below, d50w will cut 50 words.

yy is copy line, and works like dd.

D cuts from cursor to end of line.

If you've used v (visual mode), you should try V (visual line mode) and <ctrl>v (visual block mode).

How to add buttons like refresh and search in ToolBar in Android?

Try to do this:


and if you made your custom toolbar (which i presume you did) then you can use the simplest way possible to do this:

toolbarTitle = (TextView)findViewById(;
toolbarSubTitle = (TextView)findViewById(;

Same goes for any other views you put in your toolbar. Hope it helps.

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:



Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:


Creating a select box with a search option

This will work for most of us. The answer given by Hemanth Palle is the easiest way to do it, It worked for me and the JS code wasn't necessary. The only problem that I've found is that according to W3Schools, The datalist tag is not supported in Internet Explorer 9 and earlier versions, or in Safari.

<!DOCTYPE html>
<script src=""></script>
<input list="browsers">
<datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

's up guys i read every single forum about this topic i still had problem (occurred trying to project from git)

after 4 hours and a lot of swearing i solved this issue by myself just by changing target framework setting in project properties (right click on project -> properties) -> application and changed target framework from .net core 3.0 to .net 5.0 i hope it will help anybody

happy coding gl hf nerds

Check if a string contains a substring in SQL Server 2005, using a stored procedure

CHARINDEX() searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found

if CHARINDEX('ME',@mainString) > 0
    --do something

Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX call would look like:

CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')

(Add more recursive REPLACE() calls for any other punctuation that may occur)

Installing mcrypt extension for PHP on OSX Mountain Lion

I just went through this on Mountain Lion. Homebrew blocked on libiconv which it thought was missing but was actually up to date. After an hour of trying to get it to recognize libiconv, I gave up and installed it the old fashion way, which took all of five minutes...

(download your php version)
$ wget
$ tar -xvzf php-5.3.21.tar.gz
$ cd php-5.3.21/ext/mcrypt
$ phpize
$ ./configure
$ make
$ make test
$ sudo make install is now in your PHP ext dir (/usr/lib/php/extensions/no-debug-non-zts-20090626/ in my case), now you need to add to php.ini as a module

$ vi /etc/php.ini
$ (insert)
$ sudo apachectl restart

Done - no brew necessary. HTH someone.

Rename package in Android Studio

This I believe what you are looking for is Refactor > Move. You can also press F6.

You will get two popups. Make sure you select rename package on both. After that you will get a pop up to place the new package name.

Please note that if your package name is, for example, then this will let you change to something else.

One more thing, this will update the applicationId in your build.gradle as well. Just make sure that the checkboxes for "search in comments and strings" and "search for text occurrences" are both checked for it to work.

How can I align YouTube embedded video in the center in bootstrap

    <iframe id="myFrame" src="" width="640" height="360" frameborder="0" allowfullscreen> . 

    function myFunction() {
        var wscreen = window.innerWidth;
        var hscreen = window.innerHeight;

        document.getElementById("myFrame").width = wscreen ;
        document.getElementById("myFrame").height = hscreen ;


    window.addEventListener('resize', function(){ myFunction(); });

this works on Vimeo adding an id myFrame to the iframe

How to remove "href" with Jquery?

If you want your anchor to still appear to be clickable:


And if you wanted to remove the href from only anchors with certain attributes (eg ones that just have a hash mark as the href - this can be useful in


MVC pattern on Android

There is no universally unique MVC pattern. MVC is a concept rather than a solid programming framework. You can implement your own MVC on any platform. As long as you stick to the following basic idea, you are implementing MVC:

  • Model: What to render
  • View: How to render
  • Controller: Events, user input

Also think about it this way: When you program your model, the model should not need to worry about the rendering (or platform specific code). The model would say to the view, I don't care if your rendering is Android or iOS or Windows Phone, this is what I need you to render. The view would only handle the platform-specific rendering code.

This is particularly useful when you use Mono to share the model in order to develop cross-platform applications.

"Unorderable types: int() < str()"

The issue here is that input() returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.

To fix this, simply call int() to convert your string to an integer:


As a note, if you want to deal with decimal numbers, you will want to use one of float() or decimal.Decimal() (depending on your accuracy and speed needs).

Note that the more pythonic way of looping over a series of numbers (as opposed to a while loop and counting) is to use range(). For example:

def main():
    print("Let me Retire Financial Calculator")
    deposit = float(input("Please input annual deposit in dollars: $"))
    rate = int(input ("Please input annual rate in percentage: %")) / 100
    time = int(input("How many years until retirement?"))
    value = 0
    for x in range(1, time+1):
        value = (value * rate) + deposit
        print("The value of your account after" + str(x) + "years will be $" + str(value))

CodeIgniter Disallowed Key Characters

Open libraries/Input.php (system/core/Input.php in CI version 2.0+) and locate function _clean_input_keys($str){, The whole block should look like so:

function _clean_input_keys($str)
    if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
        exit('Disallowed Key Characters.');

    return $str;

Modify the PCRE sot that it allows the new chars.

Please not that the char thats missing is the .(dot) and you should always escape the .(dot) in Regular Expressions as they will otherwise allow any single char.


jQuery click event not working after adding class

I Know this is an old topic...but none of the above helped me. And after searching a lot and trying everything...I came up with this.

First remove the click code out of the $(document).ready part and put it in a separate section. then put your click code in an $(function(){......}); code.

Like this:

    //your click code
    $("a.tabclick").on('click',function() {
      //do something

how to add background image to activity?

Place the Image in the folder drawable. drawable folder is in res. drawable have 5 variants drawable-hdpi drawable-ldpi drawable-mdpi drawable-xhdpi drawable-xxhdpi

How to implement an android:background that doesn't stretch?

You should use ImageView if you don't want it to stretch. Background images will always stretch to fit the view. You need to set it as a Drawable to force the image aspect to the object.

Otherwise, if you are sticking with the Button idea, then you will need to force the scaling in the button to prevent the image from stretching.


onCreate(Bundle bundle) {
  // Set content layout, etc up here

  // Now adjust button sizes
  Button b = (Button) findViewById(;
  int someDimension = 50; //50pixels

Best solution to protect PHP code without encryption

Obfuscating things can only inconvenience your legitimate, law-abiding customers, while the people who would would rip you off are not your target paying customers anyway. (edited out other thoughts about obfuscation)

Another suggestion for protecting your software: create a business model in which the code is an incomplete part of the value of your offering. For example, sell product licenses along with access to some data you manage on your site, or license the product on a subscription model or with customer support.

Designing a EULA is a legal matter, not a coding matter. You can start by reading some EULA text for products and websites you use. You might find some interesting details!

Creating a proprietary license is is highly flexible, and probably a subject beyond the intended scope of StackOverflow, since it's not strictly about coding.

Some parts of a EULA that come to mind:

  • Limiting your liability if the product has bugs or causes damage.
  • Spelling out how the customer can use their licensed software, for how long, on how many machines, with or without redistribution rights, etc.
  • Giving you rights to audit their site, so you can enforce the licenses.
  • What happens if they violate the EULA, e.g. they lose their privilege to use your software.

You should consult a legal professional to prepare a commercial EULA.

edit: If this project can't justify the expense of a lawyer, check out these resources:

How to make execution pause, sleep, wait for X seconds in R?

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

You can track all calls to [ASIdentifierManager advertisingIdentifier] with symbolic breakpoint in Xcode: enter image description here

Replace contents of factor column in R dataframe

A more general solution that works with all the data frame at once and where you don't have to add new factors levels is:

data.mtx <- as.matrix(data.df)
data.mtx[which(data.mtx == "")] <- "new.value"
data.df <-

A nice feature of this code is that you can assign as many values as you have in your original data frame at once, not only one "new.value", and the new values can be random values. Thus you can create a complete new random data frame with the same size as the original.

Methods vs Constructors in Java

The important difference between constructors and methods is that constructors initialize objects that are being created with the new operator, while methods perform operations on objects that already exist.

Constructors can't be called directly; they are called implicitly when the new keyword creates an object. Methods can be called directly on an object that has already been created with new.

The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public), and they have method bodies in braces.

Constructors must be named with the same name as the class name. They can't return anything, even void (the object itself is the implicit return).

Methods must be declared to return something, although it can be void.

Checkout another branch when there are uncommitted changes on the current branch

You have two choices: stash your changes:

git stash

then later to get them back:

git stash apply

or put your changes on a branch so you can get the remote branch and then merge your changes onto it. That's one of the greatest things about git: you can make a branch, commit to it, then fetch other changes on to the branch you were on.

You say it doesn't make any sense, but you are only doing it so you can merge them at will after doing the pull. Obviously your other choice is to commit on your copy of the branch and then do the pull. The presumption is you either don't want to do that (in which case I am puzzled that you don't want a branch) or you are afraid of conflicts.