Programs & Examples On #Nsmanagedobjectcontext

An instance of NSManagedObjectContext represents a single “object space”. Its primary responsibility is to manage a collection of managed objects. These objects form a group of related model objects that represent an internally consistent view of one or more persistent stores. A single managed object instance exists in one and only one context, but multiple copies of an object can exist in different contexts. Available in iOS 3.0 and later in CoreData.

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Swift 3

I had this keep coming up as a newbie and found that present loads modal views that can be dismissed but switching to root controller is best if you don't need to show a modal.

I was using this

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc  = storyboard?.instantiateViewController(withIdentifier: "MainAppStoryboard") as! TabbarController
present(vc, animated: false, completion: nil)

Using this instead with my tabController:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let view = storyboard.instantiateViewController(withIdentifier: "MainAppStoryboard") as UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//show window
appDelegate.window?.rootViewController = view

Just adjust to a view controller if you need to switch between multiple storyboard screens.

Detect changed input text box

Each answer is missing some points, so here is my solution:

_x000D_
_x000D_
$("#input").on("input", function(e) {_x000D_
  var input = $(this);_x000D_
  var val = input.val();_x000D_
_x000D_
  if (input.data("lastval") != val) {_x000D_
    input.data("lastval", val);_x000D_
_x000D_
    //your change action goes here _x000D_
    console.log(val);_x000D_
  }_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="input">_x000D_
<p>Try to drag the letters and copy paste</p>
_x000D_
_x000D_
_x000D_

The Input Event fires on Keyboard input, Mouse Drag, Autofill and Copy-Paste tested on Chrome and Firefox. Checking for previous value makes it detect real changes, which means not firing when pasting the same thing or typing the same character or etc.

Working example: http://jsfiddle.net/g6pcp/473/


update:

And if you like to run your change function only when user finishes typing and prevent firing the change action several times, you could try this:

_x000D_
_x000D_
var timerid;_x000D_
$("#input").on("input", function(e) {_x000D_
  var value = $(this).val();_x000D_
  if ($(this).data("lastval") != value) {_x000D_
_x000D_
    $(this).data("lastval", value);_x000D_
    clearTimeout(timerid);_x000D_
_x000D_
    timerid = setTimeout(function() {_x000D_
      //your change action goes here _x000D_
      console.log(value);_x000D_
    }, 500);_x000D_
  };_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="input">
_x000D_
_x000D_
_x000D_

If user starts typing (e.g. "foobar") this code prevents your change action to run for every letter user types and and only runs when user stops typing, This is good specially for when you send the input to the server (e.g. search inputs), that way server does only one search for foobar and not six searches for f and then fo and then foo and foob and so on.

Convert seconds to HH-MM-SS with JavaScript?

You can also use below code:

int ss = nDur%60;
nDur   = nDur/60;
int mm = nDur%60;
int hh = nDur/60;

jquery loop on Json data using $.each

Have you converted your data from string to JavaScript object?

You can do it with data = eval('(' + string_data + ')'); or, which is safer, data = JSON.parse(string_data); but later will only works in FF 3.5 or if you include json2.js

jQuery since 1.4.1 also have function for that, $.parseJSON().

But actually, $.getJSON() should give you already parsed json object, so you should just check everything thoroughly, there is little mistake buried somewhere, like you might have forgotten to quote something in json, or one of the brackets is missing.

Android 5.0 - Add header/footer to a RecyclerView

You can use viewtype to solve this problem, here is my demo: https://github.com/yefengfreedom/RecyclerViewWithHeaderFooterLoadingEmptyViewErrorView

  1. you can define some recycler view display mode:

    public static final int MODE_DATA = 0, MODE_LOADING = 1, MODE_ERROR = 2, MODE_EMPTY = 3, MODE_HEADER_VIEW = 4, MODE_FOOTER_VIEW = 5;

2.override the getItemViewType mothod

 @Override
public int getItemViewType(int position) {
    if (mMode == RecyclerViewMode.MODE_LOADING) {
        return RecyclerViewMode.MODE_LOADING;
    }
    if (mMode == RecyclerViewMode.MODE_ERROR) {
        return RecyclerViewMode.MODE_ERROR;
    }
    if (mMode == RecyclerViewMode.MODE_EMPTY) {
        return RecyclerViewMode.MODE_EMPTY;
    }
    //check what type our position is, based on the assumption that the order is headers > items > footers
    if (position < mHeaders.size()) {
        return RecyclerViewMode.MODE_HEADER_VIEW;
    } else if (position >= mHeaders.size() + mData.size()) {
        return RecyclerViewMode.MODE_FOOTER_VIEW;
    }
    return RecyclerViewMode.MODE_DATA;
}

3.override the getItemCount method

@Override
public int getItemCount() {
    if (mMode == RecyclerViewMode.MODE_DATA) {
        return mData.size() + mHeaders.size() + mFooters.size();
    } else {
        return 1;
    }
}

4.override the onCreateViewHolder method. create view holder by viewType

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType == RecyclerViewMode.MODE_LOADING) {
        RecyclerView.ViewHolder loadingViewHolder = onCreateLoadingViewHolder(parent);
        loadingViewHolder.itemView.setLayoutParams(
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, parent.getHeight() - mToolBarHeight)
        );
        return loadingViewHolder;
    }
    if (viewType == RecyclerViewMode.MODE_ERROR) {
        RecyclerView.ViewHolder errorViewHolder = onCreateErrorViewHolder(parent);
        errorViewHolder.itemView.setLayoutParams(
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, parent.getHeight() - mToolBarHeight)
        );
        errorViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (null != mOnErrorViewClickListener) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mOnErrorViewClickListener.onErrorViewClick(v);
                        }
                    }, 200);
                }
            }
        });
        return errorViewHolder;
    }
    if (viewType == RecyclerViewMode.MODE_EMPTY) {
        RecyclerView.ViewHolder emptyViewHolder = onCreateEmptyViewHolder(parent);
        emptyViewHolder.itemView.setLayoutParams(
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, parent.getHeight() - mToolBarHeight)
        );
        emptyViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (null != mOnEmptyViewClickListener) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mOnEmptyViewClickListener.onEmptyViewClick(v);
                        }
                    }, 200);
                }
            }
        });
        return emptyViewHolder;
    }
    if (viewType == RecyclerViewMode.MODE_HEADER_VIEW) {
        RecyclerView.ViewHolder headerViewHolder = onCreateHeaderViewHolder(parent);
        headerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (null != mOnHeaderViewClickListener) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mOnHeaderViewClickListener.onHeaderViewClick(v, v.getTag());
                        }
                    }, 200);
                }
            }
        });
        return headerViewHolder;
    }
    if (viewType == RecyclerViewMode.MODE_FOOTER_VIEW) {
        RecyclerView.ViewHolder footerViewHolder = onCreateFooterViewHolder(parent);
        footerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (null != mOnFooterViewClickListener) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mOnFooterViewClickListener.onFooterViewClick(v, v.getTag());
                        }
                    }, 200);
                }
            }
        });
        return footerViewHolder;
    }
    RecyclerView.ViewHolder dataViewHolder = onCreateDataViewHolder(parent);
    dataViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (null != mOnItemClickListener) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mOnItemClickListener.onItemClick(v, v.getTag());
                    }
                }, 200);
            }
        }
    });
    dataViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(final View v) {
            if (null != mOnItemLongClickListener) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mOnItemLongClickListener.onItemLongClick(v, v.getTag());
                    }
                }, 200);
                return true;
            }
            return false;
        }
    });
    return dataViewHolder;
}

5.Override the onBindViewHolder method. bind data by viewType

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (mMode == RecyclerViewMode.MODE_LOADING) {
        onBindLoadingViewHolder(holder, position);
    } else if (mMode == RecyclerViewMode.MODE_ERROR) {
        onBindErrorViewHolder(holder, position);
    } else if (mMode == RecyclerViewMode.MODE_EMPTY) {
        onBindEmptyViewHolder(holder, position);
    } else {
        if (position < mHeaders.size()) {
            if (mHeaders.size() > 0) {
                onBindHeaderViewHolder(holder, position);
            }
        } else if (position >= mHeaders.size() + mData.size()) {
            if (mFooters.size() > 0) {
                onBindFooterViewHolder(holder, position - mHeaders.size() - mData.size());
            }
        } else {
            onBindDataViewHolder(holder, position - mHeaders.size());
        }
    }
}

How to print the contents of RDD?

There are probably many architectural differences between myRDD.foreach(println) and myRDD.collect().foreach(println) (not only 'collect', but also other actions). One the differences I saw is when doing myRDD.foreach(println), the output will be in a random order. For ex: if my rdd is coming from a text file where each line has a number, the output will have a different order. But when I did myRDD.collect().foreach(println), order remains just like the text file.

How do I connect C# with Postgres?

If you want an recent copy of npgsql, then go here

http://www.npgsql.org/

This can be installed via package manager console as

PM> Install-Package Npgsql

How to keep the spaces at the end and/or at the beginning of a String?

This question may be old, but as of now the easiest way to do it is to add quotation marks. For example:

<string name="Toast_Memory_GameWon_part1">"you found ALL PAIRS ! on "</string>
<string name="Toast_Memory_GameWon_part2">" flips !"</string>

Automatically open default email client and pre-populate content

As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:

mailto:[email protected]?subject=Subject&body=message%20goes%20here

User doesn't need to click a link if you force it to be opened with JavaScript

window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";

Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.

Stop executing further code in Java

To stop executing java code just use this command:

    System.exit(1);

After this command java stops immediately!

for example:

    int i = 5;
    if (i == 5) {
       System.out.println("All is fine...java programm executes without problem");
    } else {
       System.out.println("ERROR occured :::: java programm has stopped!!!");
       System.exit(1);
    }

Change the "From:" address in Unix "mail"

None of the above solutions are working for me...

#!/bin/bash

# Message
echo "My message" > message.txt

# Mail
subject="Test"
mail_header="From: John Smith <[email protected]>"
recipients="[email protected]"

#######################################################################
cat message.txt | mail -s "$subject" -a "$mail_header" -t "$recipients"

Cosine Similarity between 2 Number Lists

another version based on numpy only

from numpy import dot
from numpy.linalg import norm

cos_sim = dot(a, b)/(norm(a)*norm(b))

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

Parsing HTML using Python

I recommend using justext library:

https://github.com/miso-belica/jusText

Usage: Python2:

import requests
import justext

response = requests.get("http://planet.python.org/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
    print paragraph.text

Python3:

import requests
import justext

response = requests.get("http://bbc.com/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
    print (paragraph.text)

How do I view 'git diff' output with my preferred diff tool/ viewer?

On Mac OS X,

git difftool -t diffuse 

does the job for me in the git folder. For installing diffuse, one can use port -

sudo port install diffuse

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

In my view, "Explicit is always better than implicit." Because at some point, you may got confused with this increments statement y+ = x++ + ++y. A good programmer always makes his or her code more readable.

Python syntax for "if a or b or c but not all of them"

And why not just count them ?

import sys
a = sys.argv
if len(a) = 1 :  
    # No arguments were given, the program name count as one
elif len(a) = 4 :
    # Three arguments were given
else :
    # another amount of arguments was given

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

Python assigning multiple variables to same value? list behavior

You can use id(name) to check if two names represent the same object:

>>> a = b = c = [0, 3, 5]
>>> print(id(a), id(b), id(c))
46268488 46268488 46268488

Lists are mutable; it means you can change the value in place without creating a new object. However, it depends on how you change the value:

>>> a[0] = 1
>>> print(id(a), id(b), id(c))
46268488 46268488 46268488
>>> print(a, b, c)
[1, 3, 5] [1, 3, 5] [1, 3, 5]

If you assign a new list to a, then its id will change, so it won't affect b and c's values:

>>> a = [1, 8, 5]
>>> print(id(a), id(b), id(c))
139423880 46268488 46268488
>>> print(a, b, c)
[1, 8, 5] [1, 3, 5] [1, 3, 5]

Integers are immutable, so you cannot change the value without creating a new object:

>>> x = y = z = 1
>>> print(id(x), id(y), id(z))
507081216 507081216 507081216
>>> x = 2
>>> print(id(x), id(y), id(z))
507081248 507081216 507081216
>>> print(x, y, z)
2 1 1

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

As mentioned in other answers, you'll always get the QuotaExceededError in Safari Private Browser Mode on both iOS and OS X when localStorage.setItem (or sessionStorage.setItem) is called.

One solution is to do a try/catch or Modernizr check in each instance of using setItem.

However if you want a shim that simply globally stops this error being thrown, to prevent the rest of your JavaScript from breaking, you can use this:

https://gist.github.com/philfreo/68ea3cd980d72383c951

// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
// to avoid the entire page breaking, without having to do a check at each usage of Storage.
if (typeof localStorage === 'object') {
    try {
        localStorage.setItem('localStorage', 1);
        localStorage.removeItem('localStorage');
    } catch (e) {
        Storage.prototype._setItem = Storage.prototype.setItem;
        Storage.prototype.setItem = function() {};
        alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
    }
}

MongoDB: How to find out if an array field contains an element?

I am trying to explain by putting problem statement and solution to it. I hope it will help

Problem Statement:

Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-

Solution:

Below are the conditions that need to be taken care of

  1. Product price should be less than 15
  2. Product name should be either ABC Product or PQR Product
  3. Product should be in published state.

Below is the statement that applies above criterion to create query and fetch data.

$elements = $collection->find(
             Array(
                [price] => Array( [$lt] => 15 ),
                [$or] => Array(
                            [0]=>Array(
                                    [product_name]=>Array(
                                       [$in]=>Array(
                                            [0] => ABC Product,
                                            [1]=> PQR Product
                                            )
                                        )
                                    )
                                ),
                [state]=>Published
                )
            );

multiple conditions for JavaScript .includes() method

You can use the .some method referenced here.

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

_x000D_
_x000D_
// test cases
var str1 = 'hi, how do you do?';
var str2 = 'regular string';

// do the test strings contain these terms?
var conditions = ["hello", "hi", "howdy"];

// run the tests against every element in the array
var test1 = conditions.some(el => str1.includes(el));
var test2 = conditions.some(el => str2.includes(el));

// display results
console.log(str1, ' ===> ', test1);
console.log(str2, ' ===> ', test2);
_x000D_
_x000D_
_x000D_

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

Delimiters, delimiters...

You really need them when there are multiple statements in your procedure. (in other words, do you have a ; in your code and then more statements/commands? Then, you need to use delimiters).

For such a simpler rpocedure as yours though, you could just do:

CREATE PROCEDURE ProG()
  SELECT * FROM `hs_hr_employee_leave_quota`;

Upload files from Java client to a HTTP server

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    String uploadFolder = getServletContext().getRealPath("")
            + File.separator + DATA_DIRECTORY;//DATA_DIRECTORY is directory where you upload this file on the server

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(MAX_REQUEST_SIZE);//MAX_REQUEST_SIZE is the size which size you prefer

And use <form enctype="multipart/form-data"> and use <input type="file"> in the html

Get the selected value in a dropdown using jQuery.

Hello guys i am using this technique to get the values from the selected dropdown list and it is working like charm.

var methodvalue = $("#method option:selected").val(); 

What is default session timeout in ASP.NET?

It depends on either the configuration or programmatic change.
Therefore the most reliable way to check the current value is at runtime via code.

See the HttpSessionState.Timeout property; default value is 20 minutes.

You can access this propery in ASP.NET via HttpContext:

this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere

W3WP.EXE using 100% CPU - where to start?

We had this on a recursive query that was dumping tons of data to the output - have you double checked everything does exit and no infinite loops exist?

Might try to narrow it down with a single page - we found ANTS to not be much help in that same case either - what we ended up doing was running the site hit a page watch the CPU - hit the next page watch CPU - very methodical and time consuming but if you cant find it with some code tracing you might be out of luck -

We were able to use IIS log files to track it to a set of pages that were suspect -

Hope that helps !

Upgrading PHP in XAMPP for Windows?

For Upgradation php in Xampp you can follow this steps, Else you can skip these 4 steps and direct install MAMP (for windows as well) from site and here is the direct download link

Step 1: Make backups Before starting, make sure to backup any settings, custom modules and most importantly the htdocs directory, which contains your scripts and page resources. This directory is normally located atC:\xampp\htdocs\

Step 2: Preparation

Download PHP 5.3.0rc2. I use the VC6 build in order to minimise any potential compatibility issues. It is also recommended that you download the latest Windows version of XAMPP. While this is an upgrade guide that shouldwork with previous versions of XAMPP, it is recommended that a fresh copy of the core files is used. Stop any instances of the Apache service that might be running.

Step 3: The upgrade This guide will assume your XAMPP directory is C:\xampp\

Extract the XAMPP archive to a directory of your choosing, I would recommend using the default C:\xampp\ Extract the contents of the PHP archive to C:\xampp\php\, overwriting the contents of this directory with the new files. Open the file C:\xampp\apache\conf\extra\httpd-xampp.conf and ensure the following lines are present in this order:

LoadFile "/xampp/php/php5ts.dll"
LoadModule php5_module "/xampp/apache/bin/php5apache2_2.dll"

Replace C:\xampp\php\php.ini with C:\xampp\php\php.ini-dist
Uncomment the lines:

;extension=php_mbstring.dll
;extension=php_pdo_sqlite.dll

Replace the line

magic_quotes_gpc = On

with

magic_quotes_gpc = Off

Copy all files in the C:\xampp\php\ to C:\xampp\apache\bin\ (do not copy the subdirectories or their contents).

After following the above steps, restart your Apache service (this can be done using C:\xampp\xampp-control.exe or manually through the control panel/command prompt). Your PHPinfo should indicate that the upgrade has been successful. I will update this post if I discover any problems from using this method, or a cleaner (automated) means of performing the upgrade.

Javascript select onchange='this.form.submit()'

There are a few ways this can be completed.

Elements know which form they belong to, so you don't need to wrap this in jquery, you can just call this.form which returns the form element. Then you can call submit() on a form element to submit it.

  $('select').on('change', function(e){
    this.form.submit()
  });

documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

PHP Convert String into Float/Double

If the function floatval does not work you can try to make this :

    $string = "2968789218";
    $float = $string * 1.0;
    echo $float;

But for me all the previous answer worked ( try it in http://writecodeonline.com/php/ ) Maybe the problem is on your server ?

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

Processing Symbol Files in Xcode

I know that this is not a technical solution but I had my iphone connected with the computer by cable and disconnecting the device from the computer and connecting it again (by cable again) worked for me as I could not solved it with the solutions that are provided before.

SQL Server Linked Server Example Query

Following Query is work best.

Try this Query:

SELECT * FROM OPENQUERY([LINKED_SERVER_NAME], 'SELECT * FROM [DATABASE_NAME].[SCHEMA].[TABLE_NAME]')

It Very helps to link MySQL to MS SQL

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

There are tons of questions like this out there, with many answers, but I could not find a satisfactory solution that did not involve events, scripts, plugins, etc. I wanted to keep it straight in HTML and CSS. I finally found a solution that worked, although it involved restructuring the markup to break the event chain.


1. Basic problem

Scrolling input (i.e.: mousewheel) applied to the modal element will spill over into an ancestor element and scroll it in the same direction, if some such element is scrollable:

(All examples are meant to be viewed on desktop resolutions)

https://jsfiddle.net/ybkbg26c/5/

HTML:

<div id="parent">
  <div id="modal">
    This text is pretty long here.  Hope fully, we will get some scroll bars.
  </div>
</div>

CSS:

#modal {
  position: absolute;
  height: 100px;
  width: 100px;
  top: 20%;
  left: 20%;
  overflow-y: scroll;
}
#parent {
  height: 4000px;
}

2. No parent scroll on modal scroll

The reason why the ancestor ends up scrolling is because the scroll event bubbles and some element on the chain is able to handle it. A way to stop that is to make sure none of the elements on the chain know how to handle the scroll. In terms of our example, we can refactor the tree to move the modal out of the parent element. For obscure reasons, it is not enough to keep the parent and the modal DOM siblings; the parent must be wrapped by another element that establishes a new stacking context. An absolutely positioned wrapper around the parent can do the trick.

The result we get is that as long as the modal receives the scroll event, the event will not bubble to the "parent" element.

It should typically be possible to redesign the DOM tree to support this behavior without affecting what the end user sees.

https://jsfiddle.net/0bqq31Lv/3/

HTML:

<div id="context">
  <div id="parent">
  </div>
</div>
<div id="modal">
  This text is pretty long here.  Hope fully, we will get some scroll bars.
</div>

CSS (new only):

#context {
  position: absolute;
  overflow-y: scroll;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

3. No scroll anywhere except in modal while it is up

The solution above still allows the parent to receive scroll events, as long as they are not intercepted by the modal window (i.e. if triggered by mousewheel while the cursor is not over the modal). This is sometimes undesirable and we may want to forbid all background scrolling while the modal is up. To do that, we need to insert an extra stacking context that spans the whole viewport behind the modal. We can do that by displaying an absolutely positioned overlay, which can be fully transparent if necessary (but not visibility:hidden).

https://jsfiddle.net/0bqq31Lv/2/

HTML:

<div id="context">
  <div id="parent">
  </div>
</div>
<div id="overlay">  
</div>
<div id="modal">
  This text is pretty long here.  Hope fully, we will get some scroll bars.
</div>

CSS (new on top of #2):

#overlay {
  background-color: transparent;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

How to check if the given string is palindrome?

How about this PHP example:

function noitcnuf( $returnstrrevverrtsnruter, $functionnoitcnuf) {
    $returnstrrev  = "returnstrrevverrtsnruter";
    $verrtsnruter = $functionnoitcnuf;
    return (strrev ($verrtsnruter) == $functionnoitcnuf) ; 
}

Java code To convert byte to Hexadecimal

Use

Integer.toHexString((int)b);

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

public static void DetachEntity<T>(this DbContext dbContext, T entity, string propertyName) where T: class, new()
{
   try
   {
      var dbEntity = dbContext.Find<T>(entity.GetProperty(propertyName));
      if (dbEntity != null)
          dbContext.Entry(dbEntity).State = EntityState.Detached;
      dbContext.Entry(entity).State = EntityState.Modified;
   }
   catch (Exception)
   {
        throw;
   }
}


 public static object GetProperty<T>(this T entity, string propertyName) where T : class, new()
 {
    try
    {
        Type type = entity.GetType();
        PropertyInfo propertyInfo = type.GetProperty(propertyName);
        object value = propertyInfo.GetValue(entity);
        return value;
    }
    catch (Exception)
    {
         throw;
    }
 }

I made this 2 extension methods, this is working really well.

Return sql rows where field contains ONLY non-alphanumeric characters

This will not work correctly, e.g. abcÑxyz will pass thru this as it has a,b,c... you need to work with Collate or check each byte.

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

How to create a service running a .exe file on Windows 2012 Server?

You can just do that too, it seems to work well too. sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"

You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.

How can I set the default timezone in node.js?

Here's an answer for those deploying a Node.js application to Amazon AWS Elastic Beanstalk. I haven't seen this documented anywhere else:

Under Configuration -> Software -> Environment Properties, simply set the key value pair TZ and your time zone e.g. America/Los Angeles, and Apply the change.

You can verify the effect by outputting new Date().toString() in your Node app and paying attention to the time zone suffix.

Connection Strings for Entity Framework

To enable the same edmx to access multiple databases and database providers and vise versa I use the following technique:

1) Define a ConnectionManager:

public static class ConnectionManager
{
    public static string GetConnectionString(string modelName)
    {
        var resourceAssembly = Assembly.GetCallingAssembly();

        var resources = resourceAssembly.GetManifestResourceNames();

        if (!resources.Contains(modelName + ".csdl")
            || !resources.Contains(modelName + ".ssdl")
            || !resources.Contains(modelName + ".msl"))
        {
            throw new ApplicationException(
                    "Could not find connection resources required by assembly: "
                    + System.Reflection.Assembly.GetCallingAssembly().FullName);
        }

        var provider = System.Configuration.ConfigurationManager.AppSettings.Get(
                        "MyModelUnitOfWorkProvider");

        var providerConnectionString = System.Configuration.ConfigurationManager.AppSettings.Get(
                        "MyModelUnitOfWorkConnectionString");

        string ssdlText;

        using (var ssdlInput = resourceAssembly.GetManifestResourceStream(modelName + ".ssdl"))
        {
            using (var textReader = new StreamReader(ssdlInput))
            {
                ssdlText = textReader.ReadToEnd();
            }
        }

        var token = "Provider=\"";
        var start = ssdlText.IndexOf(token);
        var end = ssdlText.IndexOf('"', start + token.Length);
        var oldProvider = ssdlText.Substring(start, end + 1 - start);

        ssdlText = ssdlText.Replace(oldProvider, "Provider=\"" + provider + "\"");

        var tempDir = Environment.GetEnvironmentVariable("TEMP") + '\\' + resourceAssembly.GetName().Name;
        Directory.CreateDirectory(tempDir);

        var ssdlOutputPath = tempDir + '\\' + Guid.NewGuid() + ".ssdl";

        using (var outputFile = new FileStream(ssdlOutputPath, FileMode.Create))
        {
            using (var outputStream = new StreamWriter(outputFile))
            {
                outputStream.Write(ssdlText);
            }
        }

        var eBuilder = new EntityConnectionStringBuilder
        {
            Provider = provider,

            Metadata = "res://*/" + modelName + ".csdl"
                        + "|" + ssdlOutputPath
                        + "|res://*/" + modelName + ".msl",

            ProviderConnectionString = providerConnectionString
        };

        return eBuilder.ToString();
    }
}

2) Modify the T4 that creates your ObjectContext so that it will use the ConnectionManager:

public partial class MyModelUnitOfWork : ObjectContext
{
    public const string ContainerName = "MyModelUnitOfWork";
    public static readonly string ConnectionString
        = ConnectionManager.GetConnectionString("MyModel");

3) Add the following lines to App.Config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="MyModelUnitOfWork" connectionString=... />
  </connectionStrings>
  <appSettings>
    <add key="MyModelUnitOfWorkConnectionString" value="data source=MyPc\SqlExpress;initial catalog=MyDB;integrated security=True;multipleactiveresultsets=True" />
    <add key="MyModelUnitOfWorkProvider" value="System.Data.SqlClient" />
  </appSettings>
</configuration>

The ConnectionManager will replace the ConnectionString and Provider to what ever is in the App.Config.

You can use the same ConnectionManager for all ObjectContexts (so they all read the same settings from App.Config), or edit the T4 so it creates one ConnectionManager for each (in its own namespace), so that each reads separate settings.

android: how to use getApplication and getApplicationContext from non activity / service class

try this, calling the activity in the constructor

public class WebService {
private Activity activity;

        public WebService(Activity _activity){
            activity=_activity;
            helper=new Helper(activity);

        }
}

How to implement authenticated routes in React Router 4?

Heres how I solved it with React and Typescript. Hope it helps !

_x000D_
_x000D_
import * as React from 'react';
import { FC } from 'react';
import { Route, RouteComponentProps, RouteProps, Redirect } from 'react-router';

const PrivateRoute: FC<RouteProps> = ({ component: Component, ...rest }) => {
    if (!Component) {
      return null;
    }
    const isLoggedIn = true; // Add your provider here
    return (
      <Route
        {...rest}
            render={(props: RouteComponentProps<{}>) => isLoggedIn ? (<Component {...props} />) : (<Redirect to={{ pathname: '/', state: { from: props.location } }} />)}
      />
    );
  };

export default PrivateRoute;








<PrivateRoute component={SignIn} path="/signin" />
_x000D_
_x000D_
_x000D_

How can I add a space in between two outputs?

You can use System.out.printf() like this if you want to get nicely formatted

System.out.printf("%-20s %s\n", Name, Income);

Prints like:

Jaden             100000.0
Angela            70000.0
Bob               10000.0

This format means:

%-20s  -> this is the first argument, Name, left justified and padded to 20 spaces.
%s     -> this is the second argument, Income, if income is a decimal swap with %f
\n     -> new line character

You could also add formatting to the Income argument so that the number is printed as desired

Check out this for a quick reference

Combining COUNT IF AND VLOOK UP EXCEL

Try this:

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

Can I get a patch-compatible output from git-diff?

Just use -p1: you will need to use -p0 in the --no-prefix case anyway, so you can just leave out the --no-prefix and use -p1:

$ git diff > save.patch
$ patch -p1 < save.patch

$ git diff --no-prefix > save.patch
$ patch -p0 < save.patch

How can I make a clickable link in an NSAttributedString?

Swift Version :

    // Attributed String for Label
    let plainText = "Apkia"
    let styledText = NSMutableAttributedString(string: plainText)
    // Set Attribuets for Color, HyperLink and Font Size
    let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14.0), NSLinkAttributeName:NSURL(string: "http://apkia.com/")!, NSForegroundColorAttributeName: UIColor.blueColor()]
    styledText.setAttributes(attributes, range: NSMakeRange(0, plainText.characters.count))
    registerLabel.attributedText = styledText

Force GUI update from UI Thread

It's very tempting to want to "fix" this and force a UI update, but the best fix is to do this on a background thread and not tie up the UI thread, so that it can still respond to events.

Deleting records before a certain date

DELETE FROM table WHERE date < '2011-09-21 08:21:22';

Clear image on picturebox

I assume you want to clear the Images drawn via PictureBox.

This you would be achieved via a Bitmap object and using Graphics object. you might be doing something like

Graphics graphic = Graphics.FromImage(pictbox.Image);
graphic.Clear(Color.Red) //Color to fill the background and reset the box

Is this what you were looking out?

EDIT

Since you are using the paint method this would cause it to be redrawn every time, I would suggest you to set a flag at the formlevel indicating whether it should or not paint the Picturebox

private bool _shouldDraw = true;
public bool ShouldDraw
{
    get { return _shouldDraw; }
    set { _shouldDraw = value; }
}

In your paint just use

if(ShouldDraw)
  //do your stuff

When you click the button set this property to false and you should be fine.

JNI converting jstring to char *

Thanks Jason Rogers's answer first.

In Android && cpp should be this:

const char *nativeString = env->GetStringUTFChars(javaString, nullptr);

// use your string

env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

4.add "env->DeleteLocalRef(nativeString);" at end.

Why should I use var instead of a type?

When you say "by warnings" what exactly do you mean? I've usually seen it giving a hint that you may want to use var, but nothing as harsh as a warning.

There's no performance difference with var - the code is compiled to the same IL. The potential benefit is in readability - if you've already made the type of the variable crystal clear on the RHS of the assignment (e.g. via a cast or a constructor call), where's the benefit of also having it on the LHS? It's a personal preference though.

If you don't want R# suggesting the use of var, just change the options. One thing about ReSharper: it's very configurable :)

C program to check little vs. big endian

This is big endian test from a configure script:

#include <inttypes.h>
int main(int argc, char ** argv){
    volatile uint32_t i=0x01234567;
    // return 0 for big endian, 1 for little endian.
    return (*((uint8_t*)(&i))) == 0x67;
}

PadLeft function in T-SQL

This works for strings, integers and numeric:

SELECT CONCAT(REPLICATE('0', 4 - LEN(id)), id)

Where 4 is desired length. Works for numbers with more than 4 digits, returns empty string on NULL value.

Python 2,3 Convert Integer to "bytes" Cleanly

I have found the only reliable, portable method to be

bytes(bytearray([n]))

Just bytes([n]) does not work in python 2. Taking the scenic route through bytearray seems like the only reasonable solution.

ActionLink htmlAttributes

Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:

@Html.ActionLink("Edit", "edit", "markets",
    new { id = 1 },
    new {@class="ui-btn-right", data_icon="gear"})

becomes:

<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>

Best way to create a temp table with same columns and type as a permanent table

Sortest one...

select top 0 * into #temptable from mytable

Note : This creates an empty copy of temp, But it doesn't create a primary key

Remove/ truncate leading zeros by javascript/jquery

I got this solution for truncating leading zeros(number or any string) in javascript:

<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
  while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
  return s;
}

var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';

alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>

Remove certain characters from a string

UPDATE yourtable 
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern') 
WHERE 1

Eloquent - where not equal to

Or like this:

Code::whereNotIn('to_be_used_by_user_id', [2])->get();

"query function not defined for Select2 undefined error"

This issue boiled down to how I was building my select2 select box. In one javascript file I had...

$(function(){
  $(".select2").select2();
});

And in another js file an override...

$(function(){
    var employerStateSelector = 
                $("#registration_employer_state").select2("destroy");
    employerStateSelector.select2({
    placeholder: 'Select a State...'
    });
});

Moving the second override into a window load event resolved the issue.

$( window ).load(function() {
  var employerStateSelector = 
              $("#registration_employer_state").select2("destroy");
  employerStateSelector.select2({
    placeholder: 'Select a State...'
  });
});

This issue blossomed inside a Rails application

How to set a value for a span using jQuery

You are using jQuery(document).ready(function($) {} means here you are using jQuery instead of $. So to resolve your issue use following code.

jQuery("#submittername").text(submitter_name);

This will resolve your problem.

The server principal is not able to access the database under the current security context in SQL Server MS 2012

We had the same error deploying a report to SSRS in our PROD environment. It was found the problem could even be reproduced with a “use ” statement. The solution was to re-sync the user's GUID account reference with the database in question (i.e., using "sp_change_users_login" like you would after restoring a db). A stock (cursor driven) script to re-sync all accounts is attached:

USE <your database>
GO

-------- Reset SQL user account guids ---------------------
DECLARE @UserName nvarchar(255) 
DECLARE orphanuser_cur cursor for 
      SELECT UserName = su.name 
      FROM sysusers su
      JOIN sys.server_principals sp ON sp.name = su.name
      WHERE issqluser = 1 AND
            (su.sid IS NOT NULL AND su.sid <> 0x0) AND
            suser_sname(su.sid) is null 
      ORDER BY su.name 

OPEN orphanuser_cur 
FETCH NEXT FROM orphanuser_cur INTO @UserName 

WHILE (@@fetch_status = 0)
BEGIN 
--PRINT @UserName + ' user name being resynced' 
exec sp_change_users_login 'Update_one', @UserName, @UserName 
FETCH NEXT FROM orphanuser_cur INTO @UserName 
END 

CLOSE orphanuser_cur 
DEALLOCATE orphanuser_cur

Fastest way to ping a network range and return responsive hosts?

This is python code for the ping in range of the 192.168.0.0-192.168.0.100. You can change for loop as you comfort.

# -*- coding: utf-8 -*-
import socket
import os
import sys

up_ip =[] #list to store the ip-addresses of server online
for x in range(100):  #here range is 0-100. You can change the range according to your comfort

    server_ip = '192.168.0.'+ str(x)
    print "Trying ,server_ip,... \n"

    rep = os.system('ping -c 1 ' + server_ip)

    if rep == 0:
        up_ip.append(server_ip)
        print '******************* Server Is Up **************** \n'
    else:
        print 'server is down \n'

print up_ip

How can I tell when HttpClient has timed out?

I found that the best way to determine if the service call has timed out is to use a cancellation token and not the HttpClient's timeout property:

var cts = new CancellationTokenSource();
cts.CancelAfter(timeout);

And then handle the CancellationException during the service call...

catch(TaskCanceledException)
{
    if(!cts.Token.IsCancellationRequested)
    {
        // Timed Out
    }
    else
    {
        // Cancelled for some other reason
    }
}

Of course if the timeout occurs on the service side of things, that should be able to handled by a WebException.

How do I time a method's execution in Java?

It would be nice if java had a better functional support, so that the action, that needs to be measured, could be wrapped into a block:

measure {
   // your operation here
}

In java this could be done by anonymous functions, that look too verbose

public interface Timer {
    void wrap();
}


public class Logger {

    public static void logTime(Timer timer) {
        long start = System.currentTimeMillis();
        timer.wrap();
        System.out.println("" + (System.currentTimeMillis() - start) + "ms");
    }

    public static void main(String a[]) {
        Logger.logTime(new Timer() {
            public void wrap() {
                // Your method here
                timeConsumingOperation();
            }
        });

    }

    public static void timeConsumingOperation() {
        for (int i = 0; i<=10000; i++) {
           System.out.println("i=" +i);
        }
    }
}

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

First some code, then the explanaition. The official docs describing this are here.

import { trigger, transition, animate, style } from '@angular/animations'

@Component({
  ...
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({transform: 'translateY(-100%)'}),
        animate('200ms ease-in', style({transform: 'translateY(0%)'}))
      ]),
      transition(':leave', [
        animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
      ])
    ])
  ]
})

In your template:

<div *ngIf="visible" [@slideInOut]>This element will slide up and down when the value of 'visible' changes from true to false and vice versa.</div>

I found the angular way a bit tricky to grasp, but once you understand it, it quite easy and powerful.

The animations part in human language:

  • We're naming this animation 'slideInOut'.
  • When the element is added (:enter), we do the following:
  • ->Immediately move the element 100% up (from itself), to appear off screen.
  • ->then animate the translateY value until we are at 0%, where the element would naturally be.

  • When the element is removed, animate the translateY value (currently 0), to -100% (off screen).

The easing function we're using is ease-in, in 200 milliseconds, you can change that to your liking.

Hope this helps!

remove borders around html input

It's simple

input {border:0;outline:0;}
input:focus {outline:none!important;}

java.net.SocketTimeoutException: Read timed out under Tomcat

I have the same issue. The java.net.SocketTimeoutException: Read timed out error happens on Tomcat under Mac 11.1, but it works perfectly in Mac 10.13. Same Tomcat folder, same WAR file. Have tried setting timeout values higher, but nothing I do works. If I run the same SpringBoot code in a regular Java application (outside Tomcat 9.0.41 (tried other versions too), then it works also.

Mac 11.1 appears to be interfering with Tomcat.

As another test, if I copy the WAR file to an AWS EC2 instance, it works fine there too.

Spent several days trying to figure this out, but cannot resolve.

Suggestions very welcome! :)

jQuery Ajax calls and the Html.AntiForgeryToken()

I think all you have to do is ensure that the "__RequestVerificationToken" input is included in the POST request. The other half of the information (i.e. the token in the user's cookie) is already sent automatically with an AJAX POST request.

E.g.,

$("a.markAsDone").click(function (event) {
    event.preventDefault();
    $.ajax({
        type: "post",
        dataType: "html",
        url: $(this).attr("rel"),
        data: { 
            "__RequestVerificationToken":
            $("input[name=__RequestVerificationToken]").val() 
        },
        success: function (response) {
            // ....
        }
    });
});

How can I use a local image as the base image with a dockerfile?

Remember to put not only the tag but also the repository in which that tag is, this way:

docker images
REPOSITORY                                TAG                       IMAGE ID            CREATED             SIZE
elixir                                    1.7-centos7_3             e15e6bf57262        20 hours ago        925MB

You should reference it this way:

elixir:1.7-centos7_3

How to enable C++17 compiling in Visual Studio?

Visual Studio 2020 version

In tasks.json file, (after you build and debug with the g++-9)

Add -std=c++2a for 2020 features (c++1z for 2017 features). Add -fconcepts to use concept keyword

"args": [
   "-std=c++2a",
   "-fconcepts",
   "-g",
   "${file}",
   "-o",
   "${fileDirname}/${fileBasenameNoExtension}"
],

now compile and you can use the 2020 features.

ORA-00932: inconsistent datatypes: expected - got CLOB

Take a substr of the CLOB and then convert it to a char:

UPDATE IMS_TEST 
  SET TEST_Category           = 'just testing' 
WHERE to_char(substr(TEST_SCRIPT, 1, 9))    = 'something'
  AND ID                      = '10000239';

How to convert this var string to URL in Swift

To Convert file path in String to NSURL, observe the following code

var filePathUrl = NSURL.fileURLWithPath(path)

selenium get current url after loading a page

Page 2 is in a new tab/window ? If it's this, use the code bellow :

try {

    String winHandleBefore = driver.getWindowHandle();

    for(String winHandle : driver.getWindowHandles()){
        driver.switchTo().window(winHandle);
        String act = driver.getCurrentUrl();
    }
    }catch(Exception e){
   System.out.println("fail");
    }

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

For your interest, to do the same with double

double doubleVal = 1.745;
double doubleVal2 = 0.745;
doubleVal = Math.round(doubleVal * 100 + 0.005) / 100.0;
doubleVal2 = Math.round(doubleVal2 * 100 + 0.005) / 100.0;
System.out.println("bdTest: " + doubleVal); //1.75
System.out.println("bdTest1: " + doubleVal2);//0.75

or just

double doubleVal = 1.745;
double doubleVal2 = 0.745;
System.out.printf("bdTest: %.2f%n",  doubleVal);
System.out.printf("bdTest1: %.2f%n",  doubleVal2);

both print

bdTest: 1.75
bdTest1: 0.75

I prefer to keep code as simple as possible. ;)

As @mshutov notes, you need to add a little more to ensure that a half value always rounds up. This is because numbers like 265.335 are a little less than they appear.

Is it possible to send a variable number of arguments to a JavaScript function?

There are two methods as of ES2015.

The arguments Object

This object is built into functions, and it refers to, appropriately, the arguments of a function. It is not technically an array, though, so typical array operations won't work on it. The suggested method is to use Array.from or the spread operator to create an array from it.

I've seen other answers mention using slice. Don't do that. It prevents optimizations (source: MDN).

Array.from(arguments)
[...arguments]

However, I would argue that arguments is problematic because it hides what a function accepts as input. An arguments function typically is written like this:

function mean(){
    let args = [...arguments];
    return args.reduce((a,b)=>a+b) / args.length;
}

Sometimes, the function header is written like the following to document the arguments in a C-like fashion:

function mean(/* ... */){ ... }

But that is rare.

As for why it is problematic, take C, for example. C is backwards compatible with an ancient pre-ANSI dialect of the language known as K&R C. K&R C allows function prototypes to have an empty arguments list.

int myFunction();
/* This function accepts unspecified parameters */

ANSI C provides a facility for varargs (...), and void to specify an empty arguments-list.

int myFunction(void);
/* This function accepts no parameters */

Many people inadvertently declare functions with an unspecified arguments list (int myfunction();), when they expect the function to take zero arguments. This is technically a bug because the function will accept arguments. Any number of them.

A proper varargs function in C takes the form:

int myFunction(int nargs, ...);

And JavaScript actually does have something similar to this.

Spread Operator / Rest Parameters

I've already shown you the spread operator, actually.

...name

It's pretty versatile, and can also be used in a function's argument-list ("rest parameters") to specify varargs in a nicely documented fashion:

function mean(...args){
    return args.reduce((a,b)=>a+b) / args.length;
}

Or as a lambda expression:

((...args)=>args.reduce((a,b)=>a+b) / args.length)(1,2,3,4,5); // 3

I much prefer the spread operator. It is clean and self-documenting.

Non-invocable member cannot be used like a method?

As the error clearly states, OffenceBox.Text() is not a function and therefore doesn't make sense.

Changing a specific column name in pandas DataFrame

Since inplace argument is available, you don't need to copy and assign the original data frame back to itself, but do as follows:

df.rename(columns={'two':'new_name'}, inplace=True)

Detect rotation of Android phone in the browser with JavaScript

Worth noting that on my Epic 4G Touch I had to set up the webview to use WebChromeClient before any of the javascript android calls worked.

webView.setWebChromeClient(new WebChromeClient());

Visual C++: How to disable specific linker warnings?

The PDB file is typically used to store debug information. This warning is caused probably because the file vc80.pdb is not found when linking the target object file. Read the MSDN entry on LNK4099 here.

Alternatively, you can turn off debug information generation from the Project Properties > Linker > Debugging > Generate Debug Info field.

z-index not working with position absolute

Old question but this answer might help someone.

If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden, otherwise anything outside of it will be cut off.

json Uncaught SyntaxError: Unexpected token :

You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399 part to the URL (you can see this in your dump of the request).

What you're returning is JSON, not JSONP. Your response looks like

{"red" : "#f00"}

and jQuery is expecting something like this:

jQuery16406345664265099913_1319854793396({"red" : "#f00"})

If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json needs to be able to actually return a JSONP response.

If the same origin policy isn't an issue for your application, then you just need to fix the dataType in your jQuery.ajax call to be json instead of jsonp.

How to create a laravel hashed password

ok, this is a extract from the make function in hash.php

    $work = str_pad(8, 2, '0', STR_PAD_LEFT);

    // Bcrypt expects the salt to be 22 base64 encoded characters including
    // dots and slashes. We will get rid of the plus signs included in the
    // base64 data and replace them with dots.
    if (function_exists('openssl_random_pseudo_bytes'))
    {
        $salt = openssl_random_pseudo_bytes(16);
    }
    else
    {
        $salt = Str::random(40);
    }

    $salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);

    echo crypt('yourpassword', '$2a$'.$work.'$'.$salt);

Just copy/paste it into a php file and run it.

Launching a website via windows commandline

You can start web pages using command line in any browser typing this command

cd %your chrome directory%
start /max http://google.com

save it as bat and run it :)

Including one C source file in another?

No.

Depending on your build environment (you don't specify), you may find that it works in exactly the way that you want.

However, there are many environments (both IDEs and a lot of hand crafted Makefiles) that expect to compile *.c - if that happens you will probably end up with linker errors due to duplicate symbols.

As a rule this practice should be avoided.

If you absolutely must #include source (and generally it should be avoided), use a different file suffix for the file.

Is there a difference between "throw" and "throw ex"?

int a = 0;
try {
    int x = 4;
    int y ;
    try {
        y = x / a;
    } catch (Exception e) {
        Console.WriteLine("inner ex");
        //throw;   // Line 1
        //throw e;   // Line 2
        //throw new Exception("devide by 0");  // Line 3
    }
} catch (Exception ex) {
    Console.WriteLine(ex);
    throw ex;
}
  1. if all Line 1 ,2 and 3 are commented - Output - inner ex

  2. if all Line 2 and 3 are commented - Output - inner ex System.DevideByZeroException: {"Attempted to divide by zero."}---------

  3. if all Line 1 and 2 are commented - Output - inner ex System.Exception: devide by 0 ----

  4. if all Line 1 and 3 are commented - Output - inner ex System.DevideByZeroException: {"Attempted to divide by zero."}---------

and StackTrace will be reset in case of throw ex;

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

transferring file from local to remote host

scp -i (path of your key) (path for your file to be transferred) (username@ip):(path where file to be copied)

e.g scp -i aws.pem /home/user1/Desktop/testFile   ec2-user@someipAddress:/home/ec2-user/

P.S. - ec2-user@someipAddress of this ip address should have access to the destination folder in my case /home/ec2-user/

Replace first occurrence of pattern in a string

I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

Move all files except one

I would go with the traditional find & xargs way:

find ~/Linux/Old -maxdepth 1 -mindepth 1 -not -name Tux.png -print0 | 
    xargs -0 mv -t ~/Linux/New

-maxdepth 1 makes it not search recursively. If you only care about files, you can say -type f. -mindepth 1 makes it not include the ~/Linux/Old path itself into the result. Works with any filenames, including with those that contain embedded newlines.

One comment notes that the mv -t option is a probably GNU extension. For systems that don't have it

find ~/Linux/Old -maxdepth 1 -mindepth 1 -not -name Tux.png \
    -exec mv '{}' ~/Linux/New \;

Override intranet compatibility mode IE8

If you want your Web site to force IE 8 standards mode, then use this metatag along with a valid DOCTYPE:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

Note the "EmulateIE8" value rather than the plain "IE8".

According to IE devs, this should, "Display Standards DOCTYPEs in IE8 Standards mode; Display Quirks DOCTYPEs in Quirks mode. Use this tag to override compatibility view on client machines and force Standards to IE8 Standards."

more info on this IE blog post: http://blogs.msdn.com/b/ie/archive/2008/08/27/introducing-compatibility-view.aspx

Get selected value from combo box in C# WPF

private void usuarioBox_TextChanged(object sender, EventArgs e)
{
    string textComboBox = usuarioBox.Text;
}

How to set Android camera orientation properly?

This problem was solved a long time ago but I encountered some difficulties to put all pieces together so here is my final solution, I hope this will help others :

public void startPreview() {
        try {
            Log.i(TAG, "starting preview: " + started);

            // ....
            Camera.CameraInfo camInfo = new Camera.CameraInfo();
            Camera.getCameraInfo(cameraIndex, camInfo);
            int cameraRotationOffset = camInfo.orientation;
            // ...

            Camera.Parameters parameters = camera.getParameters();
            List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
            Camera.Size previewSize = null;
            float closestRatio = Float.MAX_VALUE;

            int targetPreviewWidth = isLandscape() ? getWidth() : getHeight();
            int targetPreviewHeight = isLandscape() ? getHeight() : getWidth();
            float targetRatio = targetPreviewWidth / (float) targetPreviewHeight;

            Log.v(TAG, "target size: " + targetPreviewWidth + " / " + targetPreviewHeight + " ratio:" + targetRatio);
            for (Camera.Size candidateSize : previewSizes) {
                float whRatio = candidateSize.width / (float) candidateSize.height;
                if (previewSize == null || Math.abs(targetRatio - whRatio) < Math.abs(targetRatio - closestRatio)) {
                    closestRatio = whRatio;
                    previewSize = candidateSize;
                }
            }

            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            int degrees = 0;
            switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break; // Natural orientation
            case Surface.ROTATION_90:
                degrees = 90;
                break; // Landscape left
            case Surface.ROTATION_180:
                degrees = 180;
                break;// Upside down
            case Surface.ROTATION_270:
                degrees = 270;
                break;// Landscape right
            }
            int displayRotation;
            if (isFrontFacingCam) {
                displayRotation = (cameraRotationOffset + degrees) % 360;
                displayRotation = (360 - displayRotation) % 360; // compensate
                                                                    // the
                                                                    // mirror
            } else { // back-facing
                displayRotation = (cameraRotationOffset - degrees + 360) % 360;
            }

            Log.v(TAG, "rotation cam / phone = displayRotation: " + cameraRotationOffset + " / " + degrees + " = "
                    + displayRotation);

            this.camera.setDisplayOrientation(displayRotation);

            int rotate;
            if (isFrontFacingCam) {
                rotate = (360 + cameraRotationOffset + degrees) % 360;
            } else {
                rotate = (360 + cameraRotationOffset - degrees) % 360;
            }

            Log.v(TAG, "screenshot rotation: " + cameraRotationOffset + " / " + degrees + " = " + rotate);

            Log.v(TAG, "preview size: " + previewSize.width + " / " + previewSize.height);
            parameters.setPreviewSize(previewSize.width, previewSize.height);
            parameters.setRotation(rotate);
            camera.setParameters(parameters);
            camera.setPreviewDisplay(mHolder);
            camera.startPreview();

            Log.d(TAG, "preview started");

            started = true;
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

VB.net: Date without time

Format datetime to short date string and convert back to date

CDate(YourDate.ToString("d"))

Or use short date string

CDate(YourDate.ToShortDateString)

Conversion failed when converting date and/or time from character string while inserting datetime

The conversion in SQL server fails sometimes not because of the Date or Time formats used, It is Merely because you are trying to store wrong data that is not acceptable to the system.

Example:

Create Table MyTable (MyDate);

Insert Into MyTable(MyDate) Values ('2015-02-29');

The SQL server will throw the following error:

Conversion failed when converting date and/or time from character string.

The reason for this error is simply there is no such date (Feb-29) in Year (2015).

What is ":-!!" in C code?

The : is a bitfield. As for !!, that is logical double negation and so returns 0 for false or 1 for true. And the - is a minus sign, i.e. arithmetic negation.

It's all just a trick to get the compiler to barf on invalid inputs.

Consider BUILD_BUG_ON_ZERO. When -!!(e) evaluates to a negative value, that produces a compile error. Otherwise -!!(e) evaluates to 0, and a 0 width bitfield has size of 0. And hence the macro evaluates to a size_t with value 0.

The name is weak in my view because the build in fact fails when the input is not zero.

BUILD_BUG_ON_NULL is very similar, but yields a pointer rather than an int.

How do I launch the Android emulator from the command line?

Just to add here, whenever you get "error: device offline" means that connection with emulator & adb bridge has been broken due to time taken in emulator startup.

Rather than re-starting emulator at this point try below two commands which stops & start adb bridge again.

adb kill-server

adb start-server

Proxies with Python 'Requests' module

I have found that urllib has some really good code to pick up the system's proxy settings and they happen to be in the correct form to use directly. You can use this like:

import urllib

...
r = requests.get('http://example.org', proxies=urllib.request.getproxies())

It works really well and urllib knows about getting Mac OS X and Windows settings as well.

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

As far as I can tell, both syntaxes are equivalent. The first is SQL standard, the second is MySQL's extension.

So they should be exactly equivalent performance wise.

http://dev.mysql.com/doc/refman/5.6/en/insert.html says:

INSERT inserts new rows into an existing table. The INSERT ... VALUES and INSERT ... SET forms of the statement insert rows based on explicitly specified values. The INSERT ... SELECT form inserts rows selected from another table or tables.

passing object by reference in C++

A reference is really a pointer with enough sugar to make it taste nice... ;)

But it also uses a different syntax to pointers, which makes it a bit easier to use references than pointers. Because of this, we don't need & when calling the function that takes the pointer - the compiler deals with that for you. And you don't need * to get the content of a reference.

To call a reference an alias is a pretty accurate description - it is "another name for the same thing". So when a is passed as a reference, we're really passing a, not a copy of a - it is done (internally) by passing the address of a, but you don't need to worry about how that works [unless you are writing your own compiler, but then there are lots of other fun things you need to know when writing your own compiler, that you don't need to worry about when you are just programming].

Note that references work the same way for int or a class type.

How to auto-format code in Eclipse?

We can make it by :
Ctrl+i or Ctrl+Shift+F

Django ChoiceField

If your choices are not pre-decided or they are coming from some other source, you can generate them in your view and pass it to the form .

Example:

views.py:

def my_view(request, interview_pk):
    interview = Interview.objects.get(pk=interview_pk)
    all_rounds = interview.round_set.order_by('created_at')
    all_round_names = [rnd.name for rnd in all_rounds]
    form = forms.AddRatingForRound(all_round_names)
    return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})

forms.py

class AddRatingForRound(forms.ModelForm):

    def __init__(self, round_list, *args, **kwargs):
        super(AddRatingForRound, self).__init__(*args, **kwargs)
        self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))

    class Meta:
        model = models.RatingSheet
        fields = ('name', )

template:

<form method="post">
    {% csrf_token %}
    {% if interview %}
         {{ interview }}
    {% endif %}
    {% if rounds %}
    <hr>
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    {% else %}
        <h3>No rounds found</h3>
    {% endif %}

</form>

TypeScript getting error TS2304: cannot find name ' require'

You can

declare var require: any

Or, for more comprehensive support, use DefinitelyTyped's require.d.ts

Also, instead of var mongoose = require('mongoose'), you could try the following

import mongoose from 'mongoose' // or
import mongoose = require('mongoose')

Key existence check in HashMap

if(map.get(key) != null || (map.get(key) == null && map.containsKey(key)))

Does functional programming replace GoF design patterns?

The GoF Design Patterns is coding workaround recipes for OO languages that are descendants of Simula 67, like Java and C++.

Most of the "ills" treated by the design patterns are caused by:

  • statically typed classes, which specify objects, but are not themselves objects;
  • restriction to single dispatch (only the leftmost argument is used to select a method, the remaining arguments are considered as static types only: if they have dynamic types, it's up to the method to sort that out with ad-hoc approaches);
  • distinction between regular function calls and object-oriented function calls, meaning that object-oriented functions cannot be passed as functional arguments where regular functions are expected and vice versa; and
  • distinction between "base types" and "class types".

There isn't a single one of these design patterns that doesn't disappear in the Common Lisp Object System, even though the solution is structured in essentially the same way as in the corresponding design pattern. (Moreover, that object system precedes the GoF book by well over a decade. Common Lisp became an ANSI standard the same year that that book was first published.)

As far as functional programming is concerned, whether or not the patterns apply to it depends on whether the given functional programming language has some kind of object system, and whether it is modeled after the object systems which benefit from the patterns. That type of object-orientation does not mix well with functional programming, because the mutation of state is at the front and centre.

Construction and non-mutating access are compatible with functional programming, and so patterns which have to do with abstracting access or construction could be applicable: patterns like Factory, Facade, Proxy, Decorator, and Visitor.

On the other hand, the behavioral patterns like State and Strategy probably do not directly apply in functional OOP because mutation of state is at their core. This doesn't mean they don't apply; perhaps they somehow apply in combination with whatever tricks are available for simulating mutable state.

Push existing project into Github

Git has been the version-control system of choice since its inception in 2005. About 87% of the developers use Git as their version-control system.

But if you have a project that is already existing and you want to push to Git in the remote server, follow along the below steps:

  1. Go to the terminal of your project directory

  2. You need to initialize your project git using git init

  3. Create a .gitignore file and it is actually a text file that tells Git which files or folders to ignore in a project.

  4. Stage your files using git add .

  5. Commit your changes to your local repository with an appropriate commit message: git commit -m "my first commit"

  6. In this step, you just need to create a repository in any one of the distributed version control systems like GitHub or Bitbucket

  7. Use this Git command to link your local repository with that of the remote: git remote add <your-remote-name> <your-remote-url>

So, if your GitHub repo-url is https://github.com/your-github-username/new-repository.git, then the Git command becomes:

git remote add origin https://github.com/<your-github-username>/new-repository.git
  1. Push your code to remote GitHub repository

    git push origin master

Note: The git push command requires two parameters: the name of the remote repository (origin) and the branch to push to (here master is the default branch for every repository).

Refer this blog for detailed information.

Is there a JavaScript strcmp()?

localeCompare() is slow, so if you don't care about the "correct" ordering of non-English-character strings, try your original method or the cleaner-looking:

str1 < str2 ? -1 : +(str1 > str2)

This is an order of magnitude faster than localeCompare() on my machine.

The + ensures that the answer is always numeric rather than boolean.

Eclipse : Failed to connect to remote VM. Connection refused.

I faced the same issue. But i resolved it by changing my port numbers to different one.

Remove empty lines in a text file via grep

Try the following:

grep -v -e '^$'

How to read user input into a variable in Bash?

Use read -p:

# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user

If you like to confirm:

read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1

You should also quote your variables to prevent pathname expansion and word splitting with spaces:

# passwd "$user"
# mkdir "$home"
# chown "$user:$group" "$home"

How to merge multiple lists into one list in python?

Just add them:

['it'] + ['was'] + ['annoying']

You should read the Python tutorial to learn basic info like this.

How to view kafka message

You can try Kafka Magic - it's free and you can write complex queries in JavaScript referencing message properties and metadata. Works with Avro serialization too

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

I'm doing something like the following code. It works for USB-devices and also the stupid serial8250-devuices that we all have 30 of - but only a couple of them realy works.

Basically I use concept from previous answers. First enumerate all tty-devices in /sys/class/tty/. Devices that does not contain a /device subdir is filtered away. /sys/class/tty/console is such a device. Then the devices actually containing a devices in then accepted as valid serial-port depending on the target of the driver-symlink fx.

$ ls -al /sys/class/tty/ttyUSB0//device/driver
lrwxrwxrwx 1 root root 0 sep  6 21:28 /sys/class/tty/ttyUSB0//device/driver -> ../../../bus/platform/drivers/usbserial

and for ttyS0

$ ls -al /sys/class/tty/ttyS0//device/driver
lrwxrwxrwx 1 root root 0 sep  6 21:28 /sys/class/tty/ttyS0//device/driver -> ../../../bus/platform/drivers/serial8250

All drivers driven by serial8250 must be probes using the previously mentioned ioctl.

        if (ioctl(fd, TIOCGSERIAL, &serinfo)==0) {
            // If device type is no PORT_UNKNOWN we accept the port
            if (serinfo.type != PORT_UNKNOWN)
                the_port_is_valid

Only port reporting a valid device-type is valid.

The complete source for enumerating the serialports looks like this. Additions are welcome.

#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <linux/serial.h>

#include <iostream>
#include <list>

using namespace std;

static string get_driver(const string& tty) {
    struct stat st;
    string devicedir = tty;

    // Append '/device' to the tty-path
    devicedir += "/device";

    // Stat the devicedir and handle it if it is a symlink
    if (lstat(devicedir.c_str(), &st)==0 && S_ISLNK(st.st_mode)) {
        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));

        // Append '/driver' and return basename of the target
        devicedir += "/driver";

        if (readlink(devicedir.c_str(), buffer, sizeof(buffer)) > 0)
            return basename(buffer);
    }
    return "";
}

static void register_comport( list<string>& comList, list<string>& comList8250, const string& dir) {
    // Get the driver the device is using
    string driver = get_driver(dir);

    // Skip devices without a driver
    if (driver.size() > 0) {
        string devfile = string("/dev/") + basename(dir.c_str());

        // Put serial8250-devices in a seperate list
        if (driver == "serial8250") {
            comList8250.push_back(devfile);
        } else
            comList.push_back(devfile); 
    }
}

static void probe_serial8250_comports(list<string>& comList, list<string> comList8250) {
    struct serial_struct serinfo;
    list<string>::iterator it = comList8250.begin();

    // Iterate over all serial8250-devices
    while (it != comList8250.end()) {

        // Try to open the device
        int fd = open((*it).c_str(), O_RDWR | O_NONBLOCK | O_NOCTTY);

        if (fd >= 0) {
            // Get serial_info
            if (ioctl(fd, TIOCGSERIAL, &serinfo)==0) {
                // If device type is no PORT_UNKNOWN we accept the port
                if (serinfo.type != PORT_UNKNOWN)
                    comList.push_back(*it);
            }
            close(fd);
        }
        it ++;
    }
}

list<string> getComList() {
    int n;
    struct dirent **namelist;
    list<string> comList;
    list<string> comList8250;
    const char* sysdir = "/sys/class/tty/";

    // Scan through /sys/class/tty - it contains all tty-devices in the system
    n = scandir(sysdir, &namelist, NULL, NULL);
    if (n < 0)
        perror("scandir");
    else {
        while (n--) {
            if (strcmp(namelist[n]->d_name,"..") && strcmp(namelist[n]->d_name,".")) {

                // Construct full absolute file path
                string devicedir = sysdir;
                devicedir += namelist[n]->d_name;

                // Register the device
                register_comport(comList, comList8250, devicedir);
            }
            free(namelist[n]);
        }
        free(namelist);
    }

    // Only non-serial8250 has been added to comList without any further testing
    // serial8250-devices must be probe to check for validity
    probe_serial8250_comports(comList, comList8250);

    // Return the lsit of detected comports
    return comList;
}


int main() {
    list<string> l = getComList();

    list<string>::iterator it = l.begin();
    while (it != l.end()) {
        cout << *it << endl;
        it++;
    }

    return 0;   
}

Initialize 2D array

You can use for loop if you really want to.

char table[][] table = new char[row][col];
for(int i = 0; i < row * col ; ++i){
     table[i/row][i % col] = char('a' + (i+1));
}

or do what bhesh said.

Best Free Text Editor Supporting *More Than* 4GB Files?

I have had problems with TextPad on 4G files too. Notepad++ works nicely.

How can I connect to MySQL in Python 3 on Windows?

Summary

Mysqlclient is the best alternative(IMHO) because it works flawlessly with Python 3+, follows expected conventions (unlike mysql connector), uses the object name mysqldb which enables convenient porting of existing software and is used by Django for Python 3 builds

Is there a repository available where the binaries exist for mysqldb?

Yes. mysqlclient allows you to use mysqldb functions. Though, remember this is not a direct port by mysqldb, but a build by mysqlclient

How can I connect to MySQL in Python 3 on Windows?

pip install mysqlclient

Example

#!/Python36/python
#Please change above path to suit your platform.  Am running it on Windows
import MySQLdb
db = MySQLdb.connect(user="my-username",passwd="my-password",host="localhost",db="my-databasename")
cursor = db.cursor()
cursor.execute("SELECT * from my-table-name")
data=cursor.fetchall()
for row in data :
    print (row)
db.close()

I can't find mysqldb for Python 3.

mysqldb has not been ported yet

Using psql how do I list extensions installed in a database?

This SQL query gives output similar to \dx:

SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description" 
FROM pg_catalog.pg_extension e 
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace 
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass 
ORDER BY 1;

Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/

Adding gif image in an ImageView in android

First, copy your GIF image into Asset Folder of your app create following classes and paste the code AnimationActivity: -

public class AnimationActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    InputStream stream = null;
    try {
        stream = getAssets().open("piggy.gif");
    } catch (IOException e) {
        e.printStackTrace();
    }
          GifWebView view = new GifWebView(this, "file:///android_asset    /piggy.gif");                 

    setContentView(view);
}
}

GifDecoder:-

public class GifDecoder {

    public static final int STATUS_OK = 0;

    public static final int STATUS_FORMAT_ERROR = 1;

    public static final int STATUS_OPEN_ERROR = 2;

    protected static final int MAX_STACK_SIZE = 4096;
    protected InputStream in;
    protected int status;
    protected int width; // full image width
    protected int height; // full image height
    protected boolean gctFlag; // global color table used
    protected int gctSize; // size of global color table
    protected int loopCount = 1; // iterations; 0 = repeat forever
    protected int[] gct; // global color table
    protected int[] lct; // local color table
    protected int[] act; // active color table
    protected int bgIndex; // background color index
    protected int bgColor; // background color
    protected int lastBgColor; // previous bg color
    protected int pixelAspect; // pixel aspect ratio
    protected boolean lctFlag; // local color table flag
    protected boolean interlace; // interlace flag
    protected int lctSize; // local color table size
    protected int ix, iy, iw, ih; // current image rectangle
    protected int lrx, lry, lrw, lrh;
    protected Bitmap image; // current frame
    protected Bitmap lastBitmap; // previous frame
    protected byte[] block = new byte[256]; // current data block
    protected int blockSize = 0; // block size last graphic control extension info
    protected int dispose = 0; // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
    protected int lastDispose = 0;
    protected boolean transparency = false; // use transparent color
    protected int delay = 0; // delay in milliseconds
    protected int transIndex; // transparent color index
    // LZW decoder working arrays
    protected short[] prefix;
    protected byte[] suffix;
    protected byte[] pixelStack;
    protected byte[] pixels;
    protected Vector<GifFrame> frames; // frames read from current file
    protected int frameCount;

    private static class GifFrame {
            public GifFrame(Bitmap im, int del) {
                    image = im;
                    delay = del;
            }

            public Bitmap image;
            public int delay;
    }


    public int getDelay(int n) {
            delay = -1;
            if ((n >= 0) && (n < frameCount)) {
                    delay = frames.elementAt(n).delay;
            }
            return delay;
    }


    public int getFrameCount() {
            return frameCount;
    }


    public Bitmap getBitmap() {
            return getFrame(0);
    }


    public int getLoopCount() {
            return loopCount;
    }
    protected void setPixels() {

            int[] dest = new int[width * height];

            if (lastDispose > 0) {
                    if (lastDispose == 3) {
                            // use image before last
                            int n = frameCount - 2;
                            if (n > 0) {
                                    lastBitmap = getFrame(n - 1);
                            } else {
                                    lastBitmap = null;
                            }
                    }
                    if (lastBitmap != null) {
                            lastBitmap.getPixels(dest, 0, width, 0, 0, width, height);
                            if (lastDispose == 2) {
                                    // fill last image rect area with background color
                                    int c = 0;
                                    if (!transparency) {
                                            c = lastBgColor;
                                    }
                                    for (int i = 0; i < lrh; i++) {
                                            int n1 = (lry + i) * width + lrx;
                                            int n2 = n1 + lrw;
                                            for (int k = n1; k < n2; k++) {
                                                    dest[k] = c;
                                            }
                                    }
                            }
                    }
            }
            int pass = 1;
            int inc = 8;
            int iline = 0;
            for (int i = 0; i < ih; i++) {
                    int line = i;
                    if (interlace) {
                            if (iline >= ih) {
                                    pass++;
                                    switch (pass) {
                                    case 2:
                                            iline = 4;
                                            break;
                                    case 3:
                                            iline = 2;
                                            inc = 4;
                                            break;
                                    case 4:
                                            iline = 1;
                                            inc = 2;
                                            break;
                                    default:
                                            break;
                                    }
                            }
                            line = iline;
                            iline += inc;
                    }
                    line += iy;
                    if (line < height) {
                            int k = line * width;
                            int dx = k + ix; // start of line in dest
                            int dlim = dx + iw; // end of dest line
                            if ((k + width) < dlim) {
                                    dlim = k + width; // past dest edge
                            }
                            int sx = i * iw; // start of line in source
                            while (dx < dlim) {
                                    // map color and insert in destination
                                    int index = ((int) pixels[sx++]) & 0xff;
                                    int c = act[index];
                                    if (c != 0) {
                                            dest[dx] = c;
                                    }
                                    dx++;
                            }
                    }
            }
            image = Bitmap.createBitmap(dest, width, height, Config.ARGB_4444);
    }
    public Bitmap getFrame(int n) {
            if (frameCount <= 0)
                    return null;
            n = n % frameCount;
            return ((GifFrame) frames.elementAt(n)).image;
    }
    public int read(InputStream is) {
            init();
            if (is != null) {
                    in = is;
                    readHeader();
                    if (!err()) {
                            readContents();
                            if (frameCount < 0) {
                                    status = STATUS_FORMAT_ERROR;
                            }
                    }
            } else {
                    status = STATUS_OPEN_ERROR;
            }
            try {
                    is.close();
            } catch (Exception e) {
            }
            return status;
    }      
    protected void decodeBitmapData() {
            int nullCode = -1;
            int npix = iw * ih;
            int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi;
            if ((pixels == null) || (pixels.length < npix)) {
                    pixels = new byte[npix]; // allocate new pixel array
            }
            if (prefix == null) {
                    prefix = new short[MAX_STACK_SIZE];
            }
            if (suffix == null) {
                    suffix = new byte[MAX_STACK_SIZE];
            }
            if (pixelStack == null) {
                    pixelStack = new byte[MAX_STACK_SIZE + 1];
            }                
            data_size = read();
            clear = 1 << data_size;
            end_of_information = clear + 1;
            available = clear + 2;
            old_code = nullCode;
            code_size = data_size + 1;
            code_mask = (1 << code_size) - 1;
            for (code = 0; code < clear; code++) {
                    prefix[code] = 0; // XXX ArrayIndexOutOfBoundsException
                    suffix[code] = (byte) code;
            }               
            datum = bits = count = first = top = pi = bi = 0;
            for (i = 0; i < npix;) {
                    if (top == 0) {
                            if (bits < code_size) {
                                    // Load bytes until there are enough bits for a code.
                                    if (count == 0) {
                                            // Read a new data block.
                                            count = readBlock();
                                            if (count <= 0) {
                                                    break;
                                            }
                                            bi = 0;
                                    }
                                    datum += (((int) block[bi]) & 0xff) << bits;
                                    bits += 8;
                                    bi++;
                                    count--;
                                    continue;
                            }                               
                            code = datum & code_mask;
                            datum >>= code_size;
                            bits -= code_size;                               
                            if ((code > available) || (code == end_of_information)) {
                                    break;
                            }
                            if (code == clear) {
                                    // Reset decoder.
                                    code_size = data_size + 1;
                                    code_mask = (1 << code_size) - 1;
                                    available = clear + 2;
                                    old_code = nullCode;
                                    continue;
                            }
                            if (old_code == nullCode) {
                                    pixelStack[top++] = suffix[code];
                                    old_code = code;
                                    first = code;
                                    continue;
                            }
                            in_code = code;
                            if (code == available) {
                                    pixelStack[top++] = (byte) first;
                                    code = old_code;
                            }
                            while (code > clear) {
                                    pixelStack[top++] = suffix[code];
                                    code = prefix[code];
                            }
                            first = ((int) suffix[code]) & 0xff;
                            if (available >= MAX_STACK_SIZE) {
                                    break;
                            }
                            pixelStack[top++] = (byte) first;
                            prefix[available] = (short) old_code;
                            suffix[available] = (byte) first;
                            available++;
                            if (((available & code_mask) == 0) && (available < MAX_STACK_SIZE)) {
                                    code_size++;
                                    code_mask += available;
                            }
                            old_code = in_code;
                    }
                    // Pop a pixel off the pixel stack.
                    top--;
                    pixels[pi++] = pixelStack[top];
                    i++;
            }
            for (i = pi; i < npix; i++) {
                    pixels[i] = 0; // clear missing pixels
            }
    }        
    protected boolean err() {
            return status != STATUS_OK;
    }       
    protected void init() {
            status = STATUS_OK;
            frameCount = 0;
            frames = new Vector<GifFrame>();
            gct = null;
            lct = null;
    }        
    protected int read() {
            int curByte = 0;
            try {
                    curByte = in.read();
            } catch (Exception e) {
                    status = STATUS_FORMAT_ERROR;
            }
            return curByte;
    }       
    protected int readBlock() {
            blockSize = read();
            int n = 0;
            if (blockSize > 0) {
                    try {
                            int count = 0;
                            while (n < blockSize) {
                                    count = in.read(block, n, blockSize - n);
                                    if (count == -1) {
                                            break;
                                    }
                                    n += count;
                            }
                    } catch (Exception e) {
                            e.printStackTrace();
                    }
                    if (n < blockSize) {
                            status = STATUS_FORMAT_ERROR;
                    }
            }
            return n;
    }        
    protected int[] readColorTable(int ncolors) {
            int nbytes = 3 * ncolors;
            int[] tab = null;
            byte[] c = new byte[nbytes];
            int n = 0;
            try {
                    n = in.read(c);
            } catch (Exception e) {
                    e.printStackTrace();
            }
            if (n < nbytes) {
                    status = STATUS_FORMAT_ERROR;
            } else {
                    tab = new int[256]; // max size to avoid bounds checks
                    int i = 0;
                    int j = 0;
                    while (i < ncolors) {
                            int r = ((int) c[j++]) & 0xff;
                            int g = ((int) c[j++]) & 0xff;
                            int b = ((int) c[j++]) & 0xff;
                            tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
                    }
            }
            return tab;
    }       
    protected void readContents() {
            // read GIF file content blocks
            boolean done = false;
            while (!(done || err())) {
                    int code = read();
                    switch (code) {
                    case 0x2C: // image separator
                            readBitmap();
                            break;
                    case 0x21: // extension
                            code = read();
                            switch (code) {
                            case 0xf9: // graphics control extension
                                    readGraphicControlExt();
                                    break;
                            case 0xff: // application extension
                                    readBlock();
                                    String app = "";
                                    for (int i = 0; i < 11; i++) {
                                            app += (char) block[i];
                                    }
                                    if (app.equals("NETSCAPE2.0")) {
                                            readNetscapeExt();
                                    } else {
                                            skip(); // don't care
                                    }
                                    break;
                            case 0xfe:// comment extension
                                    skip();
                                    break;
                            case 0x01:// plain text extension
                                    skip();
                                    break;
                            default: // uninteresting extension
                                    skip();
                            }
                            break;
                    case 0x3b: // terminator
                            done = true;
                            break;
                    case 0x00: // bad byte, but keep going and see what happens break;
                    default:
                            status = STATUS_FORMAT_ERROR;
                    }
            }
    }      
    protected void readGraphicControlExt() {
            read(); // block size
            int packed = read(); // packed fields
            dispose = (packed & 0x1c) >> 2; // disposal method
            if (dispose == 0) {
                    dispose = 1; // elect to keep old image if discretionary
            }
            transparency = (packed & 1) != 0;
            delay = readShort() * 10; // delay in milliseconds
            transIndex = read(); // transparent color index
            read(); // block terminator
    }       
    protected void readHeader() {
            String id = "";
            for (int i = 0; i < 6; i++) {
                    id += (char) read();
            }
            if (!id.startsWith("GIF")) {
                    status = STATUS_FORMAT_ERROR;
                    return;
            }
            readLSD();
            if (gctFlag && !err()) {
                    gct = readColorTable(gctSize);
                    bgColor = gct[bgIndex];
            }
    }        
    protected void readBitmap() {
            ix = readShort(); // (sub)image position & size
            iy = readShort();
            iw = readShort();
            ih = readShort();
            int packed = read();
            lctFlag = (packed & 0x80) != 0; // 1 - local color table flag interlace
            lctSize = (int) Math.pow(2, (packed & 0x07) + 1);
            interlace = (packed & 0x40) != 0;
            if (lctFlag) {
                    lct = readColorTable(lctSize); // read table
                    act = lct; // make local table active
            } else {
                    act = gct; // make global table active
                    if (bgIndex == transIndex) {
                            bgColor = 0;
                    }
            }
            int save = 0;
            if (transparency) {
                    save = act[transIndex];
                    act[transIndex] = 0; // set transparent color if specified
            }
            if (act == null) {
                    status = STATUS_FORMAT_ERROR; // no color table defined
            }
            if (err()) {
                    return;
            }
            decodeBitmapData(); // decode pixel data
            skip();
            if (err()) {
                    return;
            }
            frameCount++;
            // create new image to receive frame data
            image = Bitmap.createBitmap(width, height, Config.ARGB_4444);
            setPixels(); // transfer pixel data to image
            frames.addElement(new GifFrame(image, delay)); // add image to frame
            // list
            if (transparency) {
                    act[transIndex] = save;
            }
            resetFrame();
    }
    protected void readLSD() {
            // logical screen size
            width = readShort();
            height = readShort();
            // packed fields
            int packed = read();
            gctFlag = (packed & 0x80) != 0; // 1 : global color table flag
            // 2-4 : color resolution
            // 5 : gct sort flag
            gctSize = 2 << (packed & 7); // 6-8 : gct size
            bgIndex = read(); // background color index
            pixelAspect = read(); // pixel aspect ratio
    }       
    protected void readNetscapeExt() {
            do {
                    readBlock();
                    if (block[0] == 1) {
                            // loop count sub-block
                            int b1 = ((int) block[1]) & 0xff;
                            int b2 = ((int) block[2]) & 0xff;
                            loopCount = (b2 << 8) | b1;
                    }
            } while ((blockSize > 0) && !err());
    }       
    protected int readShort() {
            // read 16-bit value, LSB first
            return read() | (read() << 8);
    }
    protected void resetFrame() {
            lastDispose = dispose;
            lrx = ix;
            lry = iy;
            lrw = iw;
            lrh = ih;
            lastBitmap = image;
            lastBgColor = bgColor;
            dispose = 0;
            transparency = false;
            delay = 0;
            lct = null;
    }
    protected void skip() {
            do {
                    readBlock();
            } while ((blockSize > 0) && !err());
    }
}

GifDecoderView:-

public class GifDecoderView extends ImageView {

private boolean mIsPlayingGif = false;

private GifDecoder mGifDecoder;

private Bitmap mTmpBitmap;

final Handler mHandler = new Handler();

final Runnable mUpdateResults = new Runnable() {
    public void run() {
        if (mTmpBitmap != null && !mTmpBitmap.isRecycled()) {
            GifDecoderView.this.setImageBitmap(mTmpBitmap);
        }
    }
};

public GifDecoderView(Context context, InputStream stream) {
    super(context);
    playGif(stream);
}

private void playGif(InputStream stream) {
    mGifDecoder = new GifDecoder();
    mGifDecoder.read(stream);

    mIsPlayingGif = true;

    new Thread(new Runnable() {
        public void run() {
            final int n = mGifDecoder.getFrameCount();
            final int ntimes = mGifDecoder.getLoopCount();
            int repetitionCounter = 0;
            do {
                for (int i = 0; i < n; i++) {
                    mTmpBitmap = mGifDecoder.getFrame(i);
                    int t = mGifDecoder.getDelay(i);
                    mHandler.post(mUpdateResults);
                    try {
                        Thread.sleep(t);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(ntimes != 0) {
                    repetitionCounter ++;
                }
            } while (mIsPlayingGif && (repetitionCounter <= ntimes));
        }
    }).start();
}

public void stopRendering() {
    mIsPlayingGif = true;
}
}

GifMovieView:-

public class GifMovieView extends View {

private Movie mMovie;

private long mMoviestart;

public GifMovieView(Context context, InputStream stream) {
    super(context);

    mMovie = Movie.decodeStream(stream);        
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.TRANSPARENT);
    super.onDraw(canvas);
    final long now = SystemClock.uptimeMillis();

    if (mMoviestart == 0) { 
        mMoviestart = now;
    }

    final int relTime = (int)((now - mMoviestart) % mMovie.duration());
    mMovie.setTime(relTime);
    mMovie.draw(canvas, 10, 10);
    this.invalidate();
}
}

GifWebView:-

public class GifWebView extends WebView {

public GifWebView(Context context, String path) {
    super(context);        

    loadUrl(path);
}
}

I Think It Might Help You... :)

Simple PHP Pagination script

This is a mix of HTML and code but it's pretty basic, easy to understand and should be fairly simple to decouple to suit your needs I think.

try {

    // Find out how many items are in the table
    $total = $dbh->query('
        SELECT
            COUNT(*)
        FROM
            table
    ')->fetchColumn();

    // How many items to list per page
    $limit = 20;

    // How many pages will there be
    $pages = ceil($total / $limit);

    // What page are we currently on?
    $page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
        'options' => array(
            'default'   => 1,
            'min_range' => 1,
        ),
    )));

    // Calculate the offset for the query
    $offset = ($page - 1)  * $limit;

    // Some information to display to the user
    $start = $offset + 1;
    $end = min(($offset + $limit), $total);

    // The "back" link
    $prevlink = ($page > 1) ? '<a href="?page=1" title="First page">&laquo;</a> <a href="?page=' . ($page - 1) . '" title="Previous page">&lsaquo;</a>' : '<span class="disabled">&laquo;</span> <span class="disabled">&lsaquo;</span>';

    // The "forward" link
    $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">&rsaquo;</a> <a href="?page=' . $pages . '" title="Last page">&raquo;</a>' : '<span class="disabled">&rsaquo;</span> <span class="disabled">&raquo;</span>';

    // Display the paging information
    echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';

    // Prepare the paged query
    $stmt = $dbh->prepare('
        SELECT
            *
        FROM
            table
        ORDER BY
            name
        LIMIT
            :limit
        OFFSET
            :offset
    ');

    // Bind the query params
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    // Do we have any results?
    if ($stmt->rowCount() > 0) {
        // Define how we want to fetch the results
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $iterator = new IteratorIterator($stmt);

        // Display the results
        foreach ($iterator as $row) {
            echo '<p>', $row['name'], '</p>';
        }

    } else {
        echo '<p>No results could be displayed.</p>';
    }

} catch (Exception $e) {
    echo '<p>', $e->getMessage(), '</p>';
}

TensorFlow not found using pip

as of today, if anyone else is wondering, python >= 3.9 will cause the same issue uninstall python 3.9, and install 3.8 , it should resolve it

How can I escape double quotes in XML attributes values?

The String conversion page on the Coder's Toolbox site is handy for encoding more than a small amount of HTML or XML code for inclusion as a value in an XML element.

Check if string begins with something?

A little more reusable function:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}

Assign output to variable in Bash

Same with something more complex...getting the ec2 instance region from within the instance.

INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")

echo $INSTANCE_REGION

Correctly ignore all files recursively under a specific folder except for a specific file type

The best answer is to add a Resources/.gitignore file under Resources containing:

# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo

If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:

# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo

You will need to edit that pattern if you add directories deeper than specified.

response.sendRedirect() from Servlet to JSP does not seem to work

I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:

response.sendRedirect("simpleList.do")

In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.

Visual Studio: How to break on handled exceptions?

There is an 'exceptions' window in VS2005 ... try Ctrl+Alt+E when debugging and click on the 'Thrown' checkbox for the exception you want to stop on.

How to install Openpyxl with pip

  1. go to command prompt, and run as Administrator
  2. in c:/> prompt -> pip install openpyxl
  3. once you run in CMD you will get message like, Successfully installed et-xmlfile-1.0.1 jdcal-1.4.1 openpyxl-3.0.5
  4. go to python interactive shell and run openpyxl module
  5. openpyxl will work

must appear in the GROUP BY clause or be used in an aggregate function

I recently run into this problem, when trying to count using case when, and found that changing the order of the which and count statements fixes the problem:

SELECT date(dateday) as pick_day,
COUNT(CASE WHEN (apples = 'TRUE' OR oranges 'TRUE') THEN fruit END)  AS fruit_counter

FROM pickings

GROUP BY 1

Instead of using - in the latter, where I got errors that apples and oranges should appear in aggregate functions

CASE WHEN ((apples = 'TRUE' OR oranges 'TRUE') THEN COUNT(*) END) END AS fruit_counter

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

Remove all elements contained in another array

Proper way to remove all elements contained in another array is to make source array same object by remove only elements:

Array.prototype.removeContained = function(array) {
  var i, results;
  i = this.length;
  results = [];
  while (i--) {
    if (array.indexOf(this[i]) !== -1) {
      results.push(this.splice(i, 1));
    }
  }
  return results;
};

Or CoffeeScript equivalent:

Array.prototype.removeContained = (array) ->
  i = @length
  @splice i, 1 while i-- when array.indexOf(@[i]) isnt -1

Testing inside chrome dev tools:

19:33:04.447 a=1
19:33:06.354 b=2
19:33:07.615 c=3
19:33:09.981 arr = [a,b,c]
19:33:16.460 arr1 = arr

19:33:20.317 arr1 === arr
19:33:20.331 true

19:33:43.592 arr.removeContained([a,c])
19:33:52.433 arr === arr1
19:33:52.438 true

Using Angular framework is the best way to keep pointer to source object when you update collections without large amount of watchers and reloads.

Read and write a String from text file

write in ViewDidLoad

var error: NSError?
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var documentsDirectory = paths.first as String
var dataPath = documentsDirectory.stringByAppendingPathComponent("MyFolder")

if !NSFileManager.defaultManager().fileExistsAtPath(dataPath) {
    NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil, error: &error)
} else {
    println("not creted or exist")
}

func listDocumentDirectoryfiles() -> [String] {
    if let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
        let myFilePath = documentDirectory.stringByAppendingPathComponent("MyFolder")
        return NSFileManager.defaultManager().contentsOfDirectoryAtPath(myFilePath, error: nil) as [String]
    }
    return []
}

glm rotate usage in Opengl

GLM has good example of rotation : http://glm.g-truc.net/code.html

glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 ViewTranslate = glm::translate(
    glm::mat4(1.0f),
    glm::vec3(0.0f, 0.0f, -Translate)
);
glm::mat4 ViewRotateX = glm::rotate(
    ViewTranslate,
    Rotate.y,
    glm::vec3(-1.0f, 0.0f, 0.0f)
);
glm::mat4 View = glm::rotate(
    ViewRotateX,
    Rotate.x,
    glm::vec3(0.0f, 1.0f, 0.0f)
);
glm::mat4 Model = glm::scale(
    glm::mat4(1.0f),
    glm::vec3(0.5f)
);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));

"elseif" syntax in JavaScript

Conditional statements are used to perform different actions based on different conditions.

Use if to specify a block of code to be executed, if a specified condition is true

Use else to specify a block of code to be executed, if the same condition is false

Use else if to specify a new condition to test, if the first condition is false

Deleting multiple columns based on column names in Pandas

Not sure if this solution has been mentioned anywhere yet but one way to do is is pandas.Index.difference.

>>> df = pd.DataFrame(columns=['A','B','C','D'])
>>> df
Empty DataFrame
Columns: [A, B, C, D]
Index: []
>>> to_remove = ['A','C']
>>> df = df[df.columns.difference(to_remove)]
>>> df
Empty DataFrame
Columns: [B, D]
Index: []

Cropping images in the browser BEFORE the upload

The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:

  1. supply a server-side fallback, or
  2. tell the user that you're very sorry, but he'll need to get a more modern browser.

Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.

EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage function with Jcrop.

How to implement if-else statement in XSLT?

If I may offer some suggestions (two years later but hopefully helpful to future readers):

  • Factor out the common h2 element.
  • Factor out the common ooooooooooooo text.
  • Be aware of new XPath 2.0 if/then/else construct if using XSLT 2.0.

XSLT 1.0 Solution (also works with XSLT 2.0)

<h2>
  <xsl:choose>
    <xsl:when test="$CreatedDate > $IDAppendedDate">m</xsl:when>
    <xsl:otherwise>d</xsl:otherwise>
  </xsl:choose>
  ooooooooooooo
</h2>

XSLT 2.0 Solution

<h2>
   <xsl:value-of select="if ($CreatedDate > $IDAppendedDate) then 'm' else 'd'"/>
   ooooooooooooo
</h2>

Simple way to convert datarow array to datatable

.Net 3.5+ added DataTableExtensions, use DataTableExtensions.CopyToDataTable Method

For datarow array just use .CopyToDataTable() and it will return datatable.

For single datarow use

new DataRow[] { myDataRow }.CopyToDataTable()

Search for all files in project containing the text 'querystring' in Eclipse

press Ctrl + H . Then choose "File Search" tab.

additional search options

search for resources: Ctrl + Shift + R

search for Java types: Ctrl + Shift + T

Creating .pem file for APNS?

Development Phase:

Step 1: Create Certificate .pem from Certificate .p12
openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12

Step 2: Create Key .pem from Key .p12
openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12

Step 3 (Optional): If you want to remove pass phrase asked in second step
openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem

Step 4: Now we have to merge the Key .pem and Certificate .pem to get Development .pem needed for Push Notifications in Development Phase of App.

If 3rd step was performed, run:
cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem

If 3rd step was not performed, run:
cat apns-dev-cert.pem apns-dev-key.pem > apns-dev.pem

Step 5: Check certificate validity and connectivity to APNS

If 3rd step was performed, run:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert apns-dev-cert.pem -key apns-dev-key-noenc.pem

If 3rd step was not performed, run:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert apns-dev-cert.pem -key apns-dev-key.pem

Production Phase:

Step 1: Create Certificate .pem from Certificate .p12
openssl pkcs12 -clcerts -nokeys -out apns-pro-cert.pem -in apns-pro-cert.p12

Step 2: Create Key .pem from Key .p12
openssl pkcs12 -nocerts -out apns-pro-key.pem -in apns-pro-key.p12

Step 3 (Optional): If you want to remove pass phrase asked in second step
openssl rsa -in apns-pro-key.pem -out apns-pro-key-noenc.pem

Step 4: Now we have to merge the Key .pem and Certificate .pem to get Production .pem needed for Push Notifications in Production Phase of App.

If 3rd step was performed, run:
cat apns-pro-cert.pem apns-pro-key-noenc.pem > apns-pro.pem

If 3rd step was not performed, run:
cat apns-pro-cert.pem apns-pro-key.pem > apns-pro.pem

Step 5: Check certificate validity and connectivity to APNS.

If 3rd step was performed, run:
openssl s_client -connect gateway.push.apple.com:2195 -cert apns-pro-cert.pem -key apns-pro-key-noenc.pem

If 3rd step was not performed, run:
openssl s_client -connect gateway.push.apple.com:2195 -cert apns-pro-cert.pem -key apns-pro-key.pem

Stash only one file out of multiple files that have changed with Git?

I would use git stash save --patch. I don't find the interactivity to be annoying because there are options during it to apply the desired operation to entire files.

Get root view from current activity

Kotlin Extension Solution

Use this to simplify access in an Activity. Then you can directly refer to rootView from the Activity, or activity.rootView outside of it:

val Activity.rootView get() = window.decorView.rootView

If you'd like to add the same for Fragments for consistency, add:

val Fragment.rootView get() = view?.rootView

How to avoid reverse engineering of an APK file?

Your client should hire someone that knows what they are doing, who can make the right decisions and can mentor you.

Talk above about you having some ability to change the transaction processing system on the backend is absurd - you shouldn't be allowed to make such architectural changes, so don't expect to be able to.

My rationale on this:

Since your domain is payment processing, its safe to assume that PCI DSS and/or PA DSS (and potential state/federal law) will be significant to your business - to be compliant you must show you are secure. To be insecure then find out (via testing) that you aren't secure, then fixing, retesting, etcetera until security can be verified at a suitable level = expensive, slow, high-risk way to success. To do the right thing, think hard up front, commit experienced talent to the job, develop in a secure manner, then test, fix (less), etcetera (less) until security can be verified at a suitable level = inexpensive, fast, low-risk way to success.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Convert string to Time

This gives you the needed results:

string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM"  string

You could also use CultureInfo.CreateSpecificCulture("en-US") as not all cultures will display AM/PM.

How to set ANDROID_HOME path in ubuntu?

I would like to share an answer that also demonstrates approach using the Android SDK provided by the Ubuntu repository:

Install Android SDK

sudo apt-get install android-sdk

Export environmental variables

export ANDROID_HOME="/usr/lib/android-sdk/"
export PATH="${PATH}:${ANDROID_HOME}tools/:${ANDROID_HOME}platform-tools/"

How to split CSV files as per number of rows specified?

I have a one-liner answer (this example gives you 999 lines of data and one header row per file)

cat bigFile.csv | parallel --header : --pipe -N999 'cat >file_{#}.csv'

https://stackoverflow.com/a/53062251/401226

How can I save a base64-encoded image to disk?

Easy way to convert base64 image into file and save as some random id or name.

// to create some random id or name for your image name
const imgname = new Date().getTime().toString();

// to declare some path to store your converted image
const path = yourpath.png    

// image takes from body which you uploaded
const imgdata = req.body.image;    

// to convert base64 format into random filename
const base64Data = imgdata.replace(/^data:([A-Za-z-+/]+);base64,/, '');
fs.writeFile(path, base64Data, 'base64', (err) => {
    console.log(err);
});

// assigning converted image into your database
req.body.coverImage = imgname

How to bind multiple values to a single WPF TextBlock?

If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding ID}"/>
    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.

AngularJS : Why ng-bind is better than {{}} in angular?

Visibility:

While your angularjs is bootstrapping, the user might see your placed brackets in the html. This can be handled with ng-cloak. But for me this is a workaround, that I don't need to use, if I use ng-bind.


Performance:

The {{}} is much slower.

This ng-bind is a directive and will place a watcher on the passed variable. So the ng-bind will only apply, when the passed value does actually change.

The brackets on the other hand will be dirty checked and refreshed in every $digest, even if it's not necessary.


I am currently building a big single page app (~500 bindings per view). Changing from {{}} to strict ng-bind did save us about 20% in every scope.$digest.


Suggestion:

If you use a translation module such as angular-translate, always prefer directives before brackets annotation.

{{'WELCOME'|translate}} => <span ng-translate="WELCOME"></span>

If you need a filter function, better go for a directive, that actually just uses your custom filter. Documentation for $filter service


UPDATE 28.11.2014 (but maybe off the topic):

In Angular 1.3x the bindonce functionality was introduced. Therefore you can bind the value of an expression/attribute once (will be bound when != 'undefined').

This is useful when you don't expect your binding to change.

Usage: Place :: before your binding:

<ul>  
  <li ng-repeat="item in ::items">{{item}}</li>
</ul>  
<a-directive name="::item">
<span data-ng-bind="::value"></span>

Example:

ng-repeat to output some data in the table, with multiple bindings per row. Translation-bindings, filter outputs, which get executed in every scope digest.

Pandas convert dataframe to array of tuples

Changing the data frames list into a list of tuples.

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
print(df)
OUTPUT
   col1  col2
0     1     4
1     2     5
2     3     6

records = df.to_records(index=False)
result = list(records)
print(result)
OUTPUT
[(1, 4), (2, 5), (3, 6)]

Java Timer vs ExecutorService?

ExecutorService is newer and more general. A timer is just a thread that periodically runs stuff you have scheduled for it.

An ExecutorService may be a thread pool, or even spread out across other systems in a cluster and do things like one-off batch execution, etc...

Just look at what each offers to decide.

CSS: center element within a <div> element

text-align:center; on the parent div Should do the trick

How to use putExtra() and getExtra() for string data

first Screen.java

text=(TextView)findViewById(R.id.tv1);
edit=(EditText)findViewById(R.id.edit);
button=(Button)findViewById(R.id.bt1);

button.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
        String s=edit.getText().toString();

        Intent ii=new Intent(MainActivity.this, newclass.class);
        ii.putExtra("name", s);
        startActivity(ii);
    }
});

Second Screen.java

public class newclass extends Activity
{
    private TextView Textv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent);
        Textv = (TextView)findViewById(R.id.tv2);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null)
        {
            String j =(String) b.get("name");
            Textv.setText(j);
        }
    }
}

Synchronizing a local Git repository with a remote one

These steps will do it:

git reset --hard HEAD
git clean -f -x -d -n

then without -n

This will take care of all local changes. Now the commits...

git status

and note the line such as:

Your branch is ahead of 'xxxx' by N commits.

Take a note of number 'N' now:

git reset --hard HEAD~N
git pull

and finally:

git status

should show nothing to add/commit. All clean.

However, a fresh clone can do the same (but is much slow).

===Updated===

As my git knowledge slightly improved over the the time, I have come up with yet another simpler way to do the same. Here is how (#with explanation). While in your working branch:

git fetch # This updates 'remote' portion of local repo. 
git reset --hard origin/<your-working-branch>
# this will sync your local copy with remote content, discarding any committed
# or uncommitted changes.

Although your local commits and changes will disappear from sight after this, it is possible to recover committed changes, if necessary.

How to launch html using Chrome at "--allow-file-access-from-files" mode?

Search for the path of your Chrome executable and then, on your cmd, try :

> "C:\PathTo\Chrome.exe" --allow-file-access-from-files

Source

EDIT : As I see on your question, don't forget that Windows is a little bit similar to Unix, so when you type "chrome ...", cmd will search for Chrome in the PATH, but in general the Chrome folder isn't on the PATH. Also, you don't specify an extension for your executable... So if you move to Chrome's folder, this command will probably work too :

> .\chrome.exe --allow-file-access-from-files

Best way to format multiple 'or' conditions in an if statement (Java)

I use this kind of pattern often. It's very compact:

// Define a constant in your class. Use a HashSet for performance
private static final Set<Integer> values = new HashSet<Integer>(Arrays.asList(12, 16, 19));

// In your method:
if (values.contains(x)) {
    ...
}

A HashSet is used here to give good look-up performance - even very large hash sets are able to execute contains() extremely quickly.

If performance is not important, you can code the gist of it into one line:

if (Arrays.asList(12, 16, 19).contains(x))

but know that it will create a new ArrayList every time it executes.

Should ol/ul be inside <p> or outside?

actually you should only put in-line elements inside the p, so in your case ol is better outside

Jquery Setting Value of Input Field

This should work.

$(".formData").val("valuesgoeshere")

For empty

$(".formData").val("")

If this does not work, you should post a jsFiddle.

Demo:

_x000D_
_x000D_
$(function() {_x000D_
  $(".resetInput").on("click", function() {_x000D_
    $(".formData").val("");_x000D_
  });_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" class="formData" value="yoyoyo">_x000D_
_x000D_
_x000D_
<button class="resetInput">Click Here to reset</button>
_x000D_
_x000D_
_x000D_

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Simply adding it to the root folder works after a fashion, but I've found that if I need to change the favicon, it can take days to update... even a cache refresh doesn't do the trick.

fetch from origin with deleted remote branches?

This worked for me.

git remote update --prune

PHP foreach with Nested Array?

foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

git - Server host key not cached

For those of you who are setting up MSYS Git on Windows using PuTTY via the standard command prompt, the way to add a host to PuTTY's cache is to run

> plink.exe <host>

For example:

> plink.exe codebasehq.com

The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 2e:db:b6:22:f7:bd:48:f6:da:72:bf:59:d7:75:d7:4e
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)

Just answer y, and then Ctrl+C the rest.

Do check the fingerprint though. This warning is there for a good reason. Fingerprints for some git services (please edit to add more):

Copy or rsync command

It's not really a question of what's more efficient.

The commands 'rsync', and 'cp' are not equivalent and achieve different goals.

1- rsync can preserve the time of creation of existing files. (using -a option)
2- rsync will run multiprocess and transfer using either local sockets or network sockets. (i.e. fork itself into multiple processes)
3- The multiprocessing, and threading will increase your throughput when copying large number of small files, and even with multiple larger files.

So bottom line is rsync is for large data, and cp is for smaller local copying. (MB to small GB range). When you start getting into multiple GB or in the TB range, go with rsync. And of course network copies, rsync all the way.

How to sort a collection by date in MongoDB?

Additional Square [ ] Bracket is required for sorting parameter to work.

collection.find({}, {"sort" : [['datefield', 'asc']]} ).toArray(function(err,docs) {});

ASP.NET Core Web API exception handling

There is a built-in middleware that makes it easier than writing a custom one.

Asp.Net Core 5 version:

app.UseExceptionHandler(a => a.Run(async context =>
{
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;
    
    await context.Response.WriteAsJsonAsync(new { error = exception.Message });
}));

Older versions (they did not have WriteAsJsonAsync extension):

app.UseExceptionHandler(a => a.Run(async context =>
{
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;
    
    var result = JsonConvert.SerializeObject(new { error = exception.Message });
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsync(result);
}));

It should do pretty much the same, just a bit less code to write.

Important: Remember to add it before UseMvc (or UseRouting in .Net Core 3) as order is important.

Is it ok to use `any?` to check if an array is not empty?

I don't think it's bad to use any? at all. I use it a lot. It's clear and concise.

However if you are concerned about all nil values throwing it off, then you are really asking if the array has size > 0. In that case, this dead simple extension (NOT optimized, monkey-style) would get you close.

Object.class_eval do

  def size?
    respond_to?(:size) && size > 0
  end

end

> "foo".size?
 => true
> "".size?
 => false
> " ".size?
 => true
> [].size?
 => false
> [11,22].size?
 => true
> [nil].size?
 => true

This is fairly descriptive, logically asking "does this object have a size?". And it's concise, and it doesn't require ActiveSupport. And it's easy to build on.

Some extras to think about:

  1. This is not the same as present? from ActiveSupport.
  2. You might want a custom version for String, that ignores whitespace (like present? does).
  3. You might want the name length? for String or other types where it might be more descriptive.
  4. You might want it custom for Integer and other Numeric types, so that a logical zero returns false.

Check if something is (not) in a list in Python

How do I check if something is (not) in a list in Python?

The cheapest and most readable solution is using the in operator (or in your specific case, not in). As mentioned in the documentation,

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

Additionally,

The operator not in is defined to have the inverse true value of in.

y not in x is logically the same as not y in x.

Here are a few examples:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

(1, 2) in [(3, 4), (1, 2)]
#  True

If the object on the RHS defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in short-circuits, so if your element is at the start of the list, in evaluates faster:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you're storing on your list hashable? IOW, can you call hash on them?

If you answered "yes" to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.

Refreshing data in RecyclerView and keeping its scroll position

If you have one or more EditTexts inside of a recyclerview items, disable the autofocus of these, putting this configuration in the parent view of recyclerview:

android:focusable="true"
android:focusableInTouchMode="true"

I had this issue when I started another activity launched from a recyclerview item, when I came back and set an update of one field in one item with notifyItemChanged(position) the scroll of RV moves, and my conclusion was that, the autofocus of EditText Items, the code above solved my issue.

best.

php search array key and get value

The key is already the ... ehm ... key

echo $array[20120504];

If you are unsure, if the key exists, test for it

$key = 20120504;
$result = isset($array[$key]) ? $array[$key] : null;

Minor addition:

$result = @$array[$key] ?: null;

One may argue, that @ is bad, but keep it serious: This is more readable and straight forward, isn't?

Update: With PHP7 my previous example is possible without the error-silencer

$result = $array[$key] ?? null;

Fastest way to convert string to integer in PHP

Run a test.

   string coerce:          7.42296099663
   string cast:            8.05654597282
   string fail coerce:     7.14159703255
   string fail cast:       7.87444186211

This was a test that ran each scenario 10,000,000 times. :-)

Co-ercion is 0 + "123"

Casting is (integer)"123"

I think Co-ercion is a tiny bit faster. Oh, and trying 0 + array('123') is a fatal error in PHP. You might want your code to check the type of the supplied value.

My test code is below.


function test_string_coerce($s) {
    return 0 + $s;
}

function test_string_cast($s) {
    return (integer)$s;
}

$iter = 10000000;

print "-- running each text $iter times.\n";

// string co-erce
$string_coerce = new Timer;
$string_coerce->Start();

print "String Coerce test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_coerce('123');
}

$string_coerce->Stop();

// string cast
$string_cast = new Timer;
$string_cast->Start();

print "String Cast test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_cast('123');
}

$string_cast->Stop();

// string co-erce fail.
$string_coerce_fail = new Timer;
$string_coerce_fail->Start();

print "String Coerce fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_coerce('hello');
}

$string_coerce_fail->Stop();

// string cast fail
$string_cast_fail = new Timer;
$string_cast_fail->Start();

print "String Cast fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_cast('hello');
}

$string_cast_fail->Stop();

// -----------------
print "\n";
print "string coerce:          ".$string_coerce->Elapsed()."\n";
print "string cast:            ".$string_cast->Elapsed()."\n";
print "string fail coerce:     ".$string_coerce_fail->Elapsed()."\n";
print "string fail cast:       ".$string_cast_fail->Elapsed()."\n";


class Timer {
    var $ticking = null;
    var $started_at = false;
    var $elapsed = 0;

    function Timer() {
        $this->ticking = null;
    }

    function Start() {
        $this->ticking = true;
        $this->started_at = microtime(TRUE);
    }

    function Stop() {
        if( $this->ticking )
            $this->elapsed = microtime(TRUE) - $this->started_at;
        $this->ticking = false;
    }

    function Elapsed() {
        switch( $this->ticking ) {
            case true: return "Still Running";
            case false: return $this->elapsed;
            case null: return "Not Started";
        }
    }
}

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

IF...ELSE... is pretty much what we've got in T-SQL. There is nothing like structured programming's CASE statement. If you have an extended set of ...ELSE IF...s to deal with, be sure to include BEGIN...END for each block to keep things clear, and always remember, consistent indentation is your friend!

Retaining file permissions with Git

One addition to @Omid Ariyan's answer is permissions on directories. Add this after the for loop's done in his pre-commit script.

for DIR in $(find ./ -mindepth 1 -type d -not -path "./.git" -not -path "./.git/*" | sed 's@^\./@@')
do
    # Save the permissions of all the files in the index
    echo $DIR";"`stat -c "%a;%U;%G" $DIR` >> $DATABASE
done

This will save directory permissions as well.

Java 8, Streams to find the duplicate elements

Basic example. First-half builds the frequency-map, second-half reduces it to a filtered list. Probably not as efficient as Dave's answer, but more versatile (like if you want to detect exactly two etc.)

List<Integer> duplicates = IntStream.of( 1, 2, 3, 2, 1, 2, 3, 4, 2, 2, 2 )
   .boxed()
   .collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) )
   .entrySet()
   .stream()
   .filter( p -> p.getValue() > 1 )
   .map( Map.Entry::getKey )
   .collect( Collectors.toList() );

Table 'performance_schema.session_variables' doesn't exist

I was able to log on to the mysql server after running the command @robregonm suggested:

mysql_upgrade -u root -p --force

A MySQL server restart is required.

Getting all types in a namespace via reflection

Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:

// Setup event handler to resolve assemblies
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);

Assembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);
a.GetTypes();
// process types here

// method later in the class:
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
    return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);
}

That should help with loading types defined in other assemblies.

Hope that helps!

Simple way to sort strings in the (case sensitive) alphabetical order

Simply use

java.util.Collections.sort(list)

without String.CASE_INSENSITIVE_ORDER comparator parameter.

Removing a model in rails (reverse of "rails g model Title...")

For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:

class DropTables < ActiveRecord::Migration
  def up
    drop_table :table_you_dont_want
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Install IPA with iTunes 11

for iTunes 12 and above (Yosemite) double click on IPA then browse your iOS device, on applist you will see the app, click the install on item.

How do you get a directory listing sorted by creation date in python?

Turns out os.listdir sorts by last modified but in reverse so you can do:

import os
last_modified=os.listdir()[::-1]

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

How do I remove the passphrase for the SSH key without having to create a new key?

You might want to add the following to your .bash_profile (or equivalent), which starts ssh-agent on login.

if [ -f ~/.agent.env ] ; then
    . ~/.agent.env > /dev/null
    if ! kill -0 $SSH_AGENT_PID > /dev/null 2>&1; then
        echo "Stale agent file found. Spawning new agent… "
        eval `ssh-agent | tee ~/.agent.env`
        ssh-add
    fi 
else
    echo "Starting ssh-agent"
    eval `ssh-agent | tee ~/.agent.env`
    ssh-add
fi

On some Linux distros (Ubuntu, Debian) you can use:

ssh-copy-id -i ~/.ssh/id_dsa.pub username@host

This will copy the generated id to a remote machine and add it to the remote keychain.

You can read more here and here.

Count number of vector values in range with R

There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like:

sum( 2 %<% x %<% 5 )
sum( 2 %<=% x %<=% 5 )

which gives the same results as:

sum( 2 < x & x < 5 )
sum( 2 <= x & x <= 5 )

Which is better is probably more a matter of personal preference.

Double quotes within php script echo

use a HEREDOC, which eliminates any need to swap quote types and/or escape them:

echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;

How to compare two date values with jQuery

var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;

if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
    ----------------------------------
}

Angular Directive refresh on parameter change

If You're under AngularJS 1.5.3 or newer, You should consider to move to components instead of directives. Those works very similar to directives but with some very useful additional feautures, such as $onChanges(changesObj), one of the lifecycle hook, that will be called whenever one-way bindings are updated.

app.component('conversation ', {
    bindings: {
    type: '@',
    typeId: '='
    },
    controller: function() {
        this.$onChanges = function(changes) {
            // check if your specific property has changed
            // that because $onChanges is fired whenever each property is changed from you parent ctrl
            if(!!changes.typeId){
                refreshYourComponent();
            }
        };
    },
    templateUrl: 'conversation .html'
});

Here's the docs for deepen into components.

How to inject JPA EntityManager using spring

The latest Spring + JPA versions solve this problem fundamentally. You can learn more how to use Spring and JPA togather in a separate thread

Debug assertion failed. C++ vector subscript out of range

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

For adding a RelativeLayout attribute whose value is true or false use 0 for false and RelativeLayout.TRUE for true:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) button.getLayoutParams()
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE)

It doesn't matter whether or not the attribute was already added, you still use addRule(verb, subject) to enable/disable it. However, post-API 17 you can use removeRule(verb) which is just a shortcut for addRule(verb, 0).

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Using some text manipulation we can separate each unit of time and then sum them together with their millisecond coefficients.

To show the formulas in the cells use CTRL + `


Raw data view


Formula view

GoogleTest: How to skip a test?

You can now use the GTEST_SKIP() macro to conditionally skip a test at runtime. For example:

TEST(Foo, Bar)
{
    if (blah)
        GTEST_SKIP();

    ...
}

Note that this is a very recent feature so you may need to update your GoogleTest library to use it.

How can I check Drupal log files?

To view entries in Drupal's own internal log system (the watchdog database table), go to http://example.com/admin/reports/dblog. These can include Drupal-specific errors as well as general PHP or MySQL errors that have been thrown.

Use the watchdog() function to add an entry to this log from your own custom module.

When Drupal bootstraps it uses the PHP function set_error_handler() to set its own error handler for PHP errors. Therefore, whenever a PHP error occurs within Drupal it will be logged through the watchdog() call at admin/reports/dblog. If you look for PHP fatal errors, for example, in /var/log/apache/error.log and don't see them, this is why. Other errors, e.g. Apache errors, should still be logged in /var/log, or wherever you have it configured to log to.

Focusable EditText inside ListView

I just found another solution. I believe it's more a hack than a solution but it works on android 2.3.7 and android 4.3 (I've even tested that good old D-pad)

init your webview as usual and add this: (thanks Michael Bierman)

listView.setItemsCanFocus(true);

During the getView call:

editText.setOnFocusChangeListener(
    new OnFocusChangeListener(View view,boolean hasFocus){
        view.post(new Runnable() {
            @Override
            public void run() {
                view.requestFocus();
                view.requestFocusFromTouch();
            }
     });

Receiver not registered exception error?

I used a try - catch block to solve the issue temporarily.

// Unregister Observer - Stop monitoring the underlying data source.
        if (mDataSetChangeObserver != null) {
            // Sometimes the Fragment onDestroy() unregisters the observer before calling below code
            // See <a>http://stackoverflow.com/questions/6165070/receiver-not-registered-exception-error</a>
            try  {
                getContext().unregisterReceiver(mDataSetChangeObserver);
                mDataSetChangeObserver = null;
            }
            catch (IllegalArgumentException e) {
                // Check wether we are in debug mode
                if (BuildConfig.IS_DEBUG_MODE) {
                    e.printStackTrace();
                }
            }
        }

jquery $('.class').each() how many items?

If you are using a version of jQuery that is less than version 1.8 you can use the $('.class').size() which takes zero parameters. See documentation for more information on .size() method.

However if you are using (or plan to upgrade) to 1.8 or greater you can use $('.class').length property. See documentation for more information on .length property.