Programs & Examples On #Launcher

A launcher is a program that stores locations of applications to aid users in starting them.

Launch Minecraft from command line - username and password as prefix

You can do this, you just need to circumvent the launcher.

In %appdata%\.minecraft\bin (or ~/.minecraft/bin on unixy systems), there is a minecraft.jar file. This is the actual game - the launcher runs this.

Invoke it like so:

java -Xms512m -Xmx1g -Djava.library.path=natives/ -cp "minecraft.jar;lwjgl.jar;lwjgl_util.jar" net.minecraft.client.Minecraft <username> <sessionID>

Set the working directory to .minecraft/bin.

To get the session ID, POST (request this page):<username>&password=<password>&version=13

You'll get a response like this:


The fourth field is the session ID. More details here. Read those details, this answer is outdated

Here's an example of logging in to in C#.

How do you change the launcher logo of an app in Android Studio?

Here is another solution which I feel is more sensible for those working on Android Studio:

  1. Expand the project root folder in the Project View
  2. Right Click on the app folder
  3. In the Context Menu go to New->Image Asset
  4. In the pop up that appears select the the new logo you would like to have(image/clip art/text).
  5. If you were selecting the image radio button (as is the default choice), if you clicked on the 3-buttons to show the path tree to locate your .png image file, most probably you might not be seeing it, so drag it from the Windows Explorer (if Windows) and drop it in the tree, and it will appear and ready for being selected.

That is it! You have a new logo for you app now.

How to make a launcher

Just develop a normal app and then add a couple of lines to the app's manifest file.

First you need to add the following attribute to your activity:


Then add two categories to the intent filter :

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.HOME" />

The result could look something like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android=""
        android:versionName="1.0" >

            android:targetSdkVersion="19" />

            android:theme="@style/AppTheme" >
                android:label="@string/app_name" >
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.HOME" />


It's that simple!

How to schedule a stored procedure in MySQL

If you're open to out-of-the-DB solution: You could set up a cron job that runs a script that will itself call the procedure.

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

My silly mistake was this: change != to ==

if(convertView != null) { // <---- HERE 
                LayoutInflater layoutInflater = LayoutInflater.from(z_selBoardElectricity.this);
                convertView = layoutInflater.inflate(R.layout.listview_board_alert, null);

                TextView textView = convertView.findViewById(;
                ImageView imageView = convertView.findViewById(;


                convertView.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.putExtra("MESSAGE", text_list.get(pos));
                        setResult(98, intent);
return convertView;

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

Try loading the website in another web browser such as Safari. Recently had this problem and for some reason, it worked after loading in a different browser.

Installing Bootstrap 3 on Rails App

This answer is for those of you looking to Install Bootstrap 3 in your Rails app without using a gem. There are two simple ways to do this that take less than 10 minutes. Pick the one that suites your needs best. Glyphicons and Javascript work and I've tested them with the latest beta of Rails 4.1.0 as well.

  1. Using Bootstrap 3 with Rails 4 - The Bootstrap 3 files are copied into the vendor directory of your application.

  2. Adding Bootstrap from a CDN to your Rails application - The Bootstrap 3 files are served from the Bootstrap CDN.

Number 2 above is the most flexible. All you need to do is change the version number that is stored in a layout helper. So you can run the Bootstrap version of your choice, whether that is 3.0.0, 3.0.3 or even older Bootstrap 2 releases.

How should I edit an Entity Framework connection string?

Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.

Firebase FCM notifications click_action payload

This falls into workaround category, containing some extra information too:

Since the notifications are handled differently depending on the state of the app (foreground/background/not launched) I've seen the best way to implement a helper class where the selected activity is launched based on the custom data sent in the notification message.

  • when the app is on foreground use the helper class in onMessageReceived
  • when the app is on background use the helper class for handling the intent in main activity's onNewIntent (check for specific custom data)
  • when the app is not running use the helper class for handling the intent in main activity's onCreate (call getIntent for the intent).

This way you do not need the click_action or intent filter specific to it. Also you write the code just once and can reasonably easily start any activity.

So the minimum custom data would look something like this:

Key: run_activity
Value: com.mypackage.myactivity

And the code for handling it:

if (intent.hasExtra("run_activity")) {

private void handleFirebaseNotificationIntent(Intent intent){
    String className = intent.getStringExtra("run_activity");
    startSelectedActivity(className, intent.getExtras());

private void startSelectedActivity(String className, Bundle extras){
    Class cls;
    try {
        cls = Class.forName(className);
    }catch(ClassNotFoundException e){
    Intent i = new Intent(context, cls);

    if (i != null) {

That is the code for the last two cases, startSelectedActivity would be called also from onMessageReceived (first case).

The limitation is that all the data in the intent extras are strings, so you may need to handle that somehow in the activity itself. Also, this is simplified, you probably don't what to change the Activity/View on an app that is on the foreground without warning your user.

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

swap may not be the red herring previously suggested. How big is the python process in question just before the ENOMEM?

Under kernel 2.6, /proc/sys/vm/swappiness controls how aggressively the kernel will turn to swap, and overcommit* files how much and how precisely the kernel may apportion memory with a wink and a nod. Like your facebook relationship status, it's complicated.

...but swap is actually available on demand (according to the web host)...

but not according to the output of your free(1) command, which shows no swap space recognized by your server instance. Now, your web host may certainly know much more than I about this topic, but virtual RHEL/CentOS systems I've used have reported swap available to the guest OS.

Adapting Red Hat KB Article 15252:

A Red Hat Enterprise Linux 5 system will run just fine with no swap space at all as long as the sum of anonymous memory and system V shared memory is less than about 3/4 the amount of RAM. .... Systems with 4GB of ram or less [are recommended to have] a minimum of 2GB of swap space.

Compare your /proc/sys/vm settings to a plain CentOS 5.3 installation. Add a swap file. Ratchet down swappiness and see if you live any longer.

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

In numpy, index and dimension numbering starts with 0. So axis 0 means the 1st dimension. Also in numpy a dimension can have length (size) 0. The simplest case is:

In [435]: x = np.zeros((0,), int)
In [436]: x
Out[436]: array([], dtype=int32)
In [437]: x[0]
IndexError: index 0 is out of bounds for axis 0 with size 0

I also get it if x = np.zeros((0,5), int), a 2d array with 0 rows, and 5 columns.

So someplace in your code you are creating an array with a size 0 first axis.

When asking about errors, it is expected that you tell us where the error occurs.

Also when debugging problems like this, the first thing you should do is print the shape (and maybe the dtype) of the suspected variables.

Applied to pandas

Resolving the error:

  1. Use a try-except block
  2. Verify the size of the array is not 0
    • if x.size != 0:

Open a new tab on button click in AngularJS

I solved this question this way.

<a class="btn btn-primary" target="_blank" ng-href="{{url}}" ng-mousedown="openTab()">newTab</a>

$scope.openTab = function() {
    $scope.url = '';

"No cached version... available for offline mode."

Just happened to me after upgrading to Android Studio 3.1. The Offline Work checkbox was unchecked, so no luck there.

I went to Settings > Build, Execution, Deployment > Compiler and the Command-line Options textfield contained --offline, so I just deleted that and everything worked.

setting screenshot

how to hide the content of the div in css

Without changing the markup or using JavaScript, you'd pretty much have to alter the text color as knut mentions, or set text-indent: -1000em;

IE6 will not read the :hover selector on anything other than an anchor element, so you will have to use something like Dean Edwards' IE7.

Really though, you're better off putting the text in some kind of element (like p or span or a) and setting that to display: none; on hover.

How to get the device's IMEI/ESN programmatically in android?


The following code helps in obtaining IMEI number of android devices :

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();

Permissions required in Android Manifest:


NOTE: In case of tablets or devices which can’t act as Mobile Phone IMEI will be null.

Get protocol + host name from URL

>>> import urlparse
>>> url = ''
>>> urlparse.urljoin(url, '/')

jQuery get the rendered height of an element?

Have you set the height in the css specifically? If you haven't you need to use offsetHeight; rather than height

var h = document.getElementById('someDiv').style.offsetHeight;

How to create a new component in Angular 4 using CLI

For creating component under certain folder

ng g c employee/create-employee --skipTests=false --flat=true

This line will create a folder name 'employee', underneath that it creates a 'create-employee' component.

without creating any folder

ng g c create-employee --skipTests=false --flat=true

Safely remove migration In Laravel

I accidentally created a migration with a bad name (command: php artisan migrate:make). I did not run (php artisan migrate) the migration, so I decided to remove it. My steps:

  1. Manually delete the migration file under app/database/migrations/my_migration_file_name.php
  2. Reset the composer autoload files: composer dump-autoload
  3. Relax

If you did run the migration (php artisan migrate), you may do this:

a) Run migrate:rollback - it is the right way to undo the last migration (Thnx @Jakobud)

b) If migrate:rollback does not work, do it manually (I remember bugs with migrate:rollback in previous versions):

  1. Manually delete the migration file under app/database/migrations/my_migration_file_name.php
  2. Reset the composer autoload files: composer dump-autoload
  3. Modify your database: Remove the last entry from the migrations table

How to collapse blocks of code in Eclipse?

For windows eclipse using java: Windows -> Preferences -> Java -> Editor -> Folding

Unfortunately this will not allow for collapsing code, however if it turns off you can re-enable it to get rid of long comments and imports.

Detecting locked tables (locked by LOCK TABLE)

The simplest way is :


You get the locked tables only of the current database.

Index all *except* one item in python

Note that if variable is list of lists, some approaches would fail. For example:

v1 = [[range(3)] for x in range(4)]
v2 = v1[:3]+v1[4:] # this fails

For the general case, use

removed_index = 1
v1 = [[range(3)] for x in range(4)]
v2 = [x for i,x in enumerate(v1) if x!=removed_index]

React Hooks useState() with Object

You can pass new value like this

  setExampleState({...exampleState,  masterField2: {
        fieldOne: "c",
        fieldTwo: {
           fieldTwoOne: "d",
           fieldTwoTwo: "e"

Make button width fit to the text

Pretty late and not sure if this was available when the question was asked, set width: auto;

Seems to do the trick

Possible to iterate backwards through a foreach?

When working with a list (direct indexing), you cannot do it as efficiently as using a for loop.

Edit: Which generally means, when you are able to use a for loop, it's likely the correct method for this task. Plus, for as much as foreach is implemented in-order, the construct itself is built for expressing loops that are independent of element indexes and iteration order, which is particularly important in parallel programming. It is my opinion that iteration relying on order should not use foreach for looping.

How to get the response of XMLHttpRequest?

In XMLHttpRequest, using XMLHttpRequest.responseText may raise the exception like below

 Failed to read the \'responseText\' property from \'XMLHttpRequest\': 
 The value is only accessible if the object\'s \'responseType\' is \'\' 
 or \'text\' (was \'arraybuffer\')

Best way to access the response from XHR as follows

function readBody(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    return data;

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
}'GET', '', true);

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    $('#contactsForm').attr('action', "/test1").submit();

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

How to commit changes to a new branch

If you haven't committed changes

If your changes are compatible with the other branch

This is the case from the question because the OP wants to commit to a new branch and also applies if your changes are compatible with the target branch without triggering an overwrite.

As in the accepted answer by John Brodie, you can simply checkout the new branch and commit the work:

git checkout -b branch_name
git add <files>
git commit -m "message"

If your changes are incompatible with the other branch

If you get the error:

error: Your local changes to the following files would be overwritten by checkout:
Please commit your changes or stash them before you switch branches

Then you can stash your work, create a new branch, then pop your stash changes, and resolve the conflicts:

git stash
git checkout -b branch_name
git stash pop

It will be as if you had made those changes after creating the new branch. Then you can commit as usual:

git add <files>
git commit -m "message"

If you have committed changes

If you want to keep the commits in the original branch

See the answer by Carl Norum with cherry-picking, which is the right tool in this case:

git checkout <target name>
git cherry-pick <original branch>

If you don't want to keep the commits in the original branch

See the answer by joeytwiddle on this potential duplicate. Follow any of the above steps as appropriate, then roll back the original branch:

git branch -f <original branch> <earlier commit id>

If you have pushed your changes to a shared remote like GitHub, you should not attempt this roll-back unless you know what you are doing.

SQL Server using wildcard within IN

I think I have a solution to what the originator of this inquiry wanted in simple form. It works for me and actually it is the reason I came on here to begin with. I believe just using parentheses around the column like '%text%' in combination with ORs will do it.

select * from tableName
where (sameColumnName like '%findThis%' or sameColumnName like '%andThis%' or 
sameColumnName like '%thisToo%' or sameColumnName like '%andOneMore%') 

Best C# API to create PDF


I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.

I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at

How to call webmethod in C#

This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:

data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",

It should be:

data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",

As well as the WebMethod to:

public static string AddTo_Cart(string quantity, string itemId)

And this resolved my problem.

Hope it may be of help to someone else as well.

Is it correct to use alt tag for an anchor link?

You should use the title attribute for anchor tags if you wish to apply descriptive information similarly as you would for an alt attribute. The title attribute is valid on anchor tags and is serves no other purpose than providing information about the linked page.

W3C recommends that the value of the title attribute should match the value of the title of the linked document but it's not mandatory.

Alternatively, and likely to be more beneficial, you can use the ARIA accessibility attribute aria-label (not to be confused with aria-labeledby). aria-label serves the same function as the alt attribute does for images but for non-image elements and includes some measure of optimization since your optimizing for screen readers.

If you want to describe an anchor tag though, it's usually appropriate to use the rel or rev tag but your limited to specific values, they should not be used for human readable descriptions.

Rel serves to describe the relationship of the linked page to the current page. (e.g. if the linked page is next in a logical series it would be rel=next)

The rev attribute is essentially the reverse relationship of the rel attribute. Rev describes the relationship of the current page to the linked page.

You can find a list of valid values here:

XML parsing of a variable string in JavaScript

Updated answer for 2017

The following will parse an XML string into an XML document in all major browsers. Unless you need support for IE <= 8 or some obscure browser, you could use the following function:

function parseXml(xmlStr) {
   return new window.DOMParser().parseFromString(xmlStr, "text/xml");

If you need to support IE <= 8, the following will do the job:

var parseXml;

if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return new window.DOMParser().parseFromString(xmlStr, "text/xml");
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        return xmlDoc;
} else {
    throw new Error("No XML parser found");

Once you have a Document obtained via parseXml, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

Example usage:

var xml = parseXml("<foo>Stuff</foo>");

If you're using jQuery, from version 1.5 you can use its built-in parseXML() method, which is functionally identical to the function above.

var xml = $.parseXML("<foo>Stuff</foo>");

Keras, how do I predict after I trained a model?

I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.

fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)

MySQL - length() vs char_length()

varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.

How to read text file in JavaScript

This can be done quite easily using javascript XMLHttpRequest() class (AJAX):

function FileHelper()

    FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
        var request = new XMLHttpRequest();"GET", pathOfFileToReadFrom, false);
        var returnValue = request.responseText;

        return returnValue;


var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Possible. You can get commercial sport also.

JavaFXPorts is the name of the open source project maintained by Gluon that develops the code necessary for Java and JavaFX to run well on mobile and embedded hardware. The goal of this project is to contribute as much back to the OpenJFX project wherever possible, and when not possible, to maintain the minimal number of changes necessary to enable the goals of JavaFXPorts. Gluon takes the JavaFXPorts source code and compiles it into binaries ready for deployment onto iOS, Android, and embedded hardware. The JavaFXPorts builds are freely available on this website for all developers.

How to get unique values in an array

You can enter array with duplicates and below method will return array with unique elements.

function getUniqueArray(array){
    var uniqueArray = [];
    if (array.length > 0) {
       uniqueArray[0] = array[0];
    for(var i = 0; i < array.length; i++){
        var isExist = false;
        for(var j = 0; j < uniqueArray.length; j++){
            if(array[i] == uniqueArray[j]){
                isExist = true;
                isExist = false;
        if(isExist == false){
            uniqueArray[uniqueArray.length] = array[i];
    return uniqueArray;

What is the difference between Html.Hidden and Html.HiddenFor

Html.Hidden('name', 'value') creates a hidden tag with name = 'name' and value = 'value'.

Html.HiddenFor(x => x.nameProp) creates a hidden tag with a name = 'nameProp' and value = x.nameProp.

At face value these appear to do similar things, with one just more convenient than the other. But its actual value is for model binding. When MVC tries to associate the html to the model, it needs to have the name of the property, and for Html.Hidden, we chose 'name', and not 'nameProp', and thus the binding wouldn't work. You'd have to have a custom binding object, or get the values from the form data. If you are redisplaying the page, you'd have to set the model to the values again.

So you can use Html.Hidden, but if you get the name wrong, or if you change the property name in the model, the auto binding will fail when you submit the form. But by using a type checked expression, you'll get code completion, and when you change the property name, you will get a compile time error. And then you are guaranteed to have the correct name in the form.

One of the better features of MVC.

Generate list of all possible permutations of a string

I'm not sure why you would want to do this in the first place. The resulting set for any moderately large values of x and y will be huge, and will grow exponentially as x and/or y get bigger.

Lets say your set of possible characters is the 26 lowercase letters of the alphabet, and you ask your application to generate all permutations where length = 5. Assuming you don't run out of memory you'll get 11,881,376 (i.e. 26 to the power of 5) strings back. Bump that length up to 6, and you'll get 308,915,776 strings back. These numbers get painfully large, very quickly.

Here's a solution I put together in Java. You'll need to provide two runtime arguments (corresponding to x and y). Have fun.

public class GeneratePermutations {
    public static void main(String[] args) {
        int lower = Integer.parseInt(args[0]);
        int upper = Integer.parseInt(args[1]);

        if (upper < lower || upper == 0 || lower == 0) {

        for (int length = lower; length <= upper; length++) {
            generate(length, "");

    private static void generate(int length, String partial) {
        if (length <= 0) {
        } else {
            for (char c = 'a'; c <= 'z'; c++) {
                generate(length - 1, partial + c);

Best way to show a loading/progress indicator?

ProgressDialog is deprecated from Android Oreo. Use ProgressBar instead

ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Wait while loading...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog;
// To dismiss the dialog

OR, "Loading", "Wait while loading...");

Read more here.

By the way, Spinner has a different meaning in Android. (It's like the select dropdown in HTML)

How to convert BigInteger to String in java

Why don't you use the BigInteger(String) constructor ? That way, round-tripping via toString() should work fine.

(note also that your conversion to bytes doesn't explicitly specify a character-encoding and is platform-dependent - that could be source of grief further down the line)

Closing WebSocket correctly (HTML5, Javascript)

By using close method of web socket, where you can write any function according to requirement.

var connection = new WebSocket('ws://');
    connection.onclose = () => {
            console.log('Web Socket Connection Closed');

How to navigate through a vector using iterators? (C++)

Vector's iterators are random access iterators which means they look and feel like plain pointers.

You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [].

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

int sixth = *(it + 5);
int third = *(2 + it);
int second = it[1];

Alternatively you can use the advance function which works with all kinds of iterators. (You'd have to consider whether you really want to perform "random access" with non-random-access iterators, since that might be an expensive thing to do.)

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

std::advance(it, 5);
int sixth = *it;

How do I set up curl to permanently use a proxy?

Curl will look for a .curlrc file in your home folder when it starts. You can create (or edit) this file and add this line:

proxy =

Capture Signature using HTML5 and iPad

Perhaps the best two browser techs for this are Canvas, with Flash as a back up.

We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.

With jSignature ( ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.

Java : Convert formatted xml file to one line string

Run it through an XSLT identity transform with <xsl:output indent="no"> and <xsl:strip-space elements="*"/>

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="">
    <xsl:output indent="no" />
    <xsl:strip-space elements="*"/>
    <xsl:template match="@*|node()">
            <xsl:apply-templates select="@*|node()"/>

It will remove any of the non-significant whitespace and produce the expected output that you posted.

How do I get the last day of a month?

// Use any date you want, for the purpose of this example we use 1980-08-03.
var myDate = new DateTime(1980,8,3);
var lastDayOfMonth = new DateTime(myDate.Year, myDate.Month, DateTime.DaysInMonth(myDate.Year, myDate.Month));

Object of class mysqli_result could not be converted to string in

mysqli:query() returns a mysqli_result object, which cannot be serialized into a string.

You need to fetch the results from the object. Here's how to do it.

If you need a single value.

Fetch a single row from the result and then access column index 0 or using an associative key. Use the null-coalescing operator in case no rows are present in the result.

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

$tourresult = $result->fetch_array()[0] ?? '';
// OR
$tourresult = $result->fetch_array()['roomprice'] ?? '';

echo '<strong>Per room amount:  </strong>'.$tourresult;

If you need multiple values.

Use foreach loop to iterate over the result and fetch each row one by one. You can access each column using the column name as an array index.

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

foreach($result as $row) {
    echo '<strong>Per room amount:  </strong>'.$row['roomprice'];

How to Consolidate Data from Multiple Excel Columns All into One Column

Best and Simple solution to follow:

Select the range of the columns you want to be copied to single column

Copy the range of cells (multiple columns)

Open Notepad++

Paste the selected range of cells

Press Ctrl+H, replace \t by \n and click on replace all

all the multiple columns fall under one single column

now copy the same and paste in excel

Simple and effective solution for those who dont want to waste time coding in VBA

Check date between two other dates spring data jpa

You can also write a custom query using @Query

@Query(value = "from EntityClassTable t where yourDate BETWEEN :startDate AND :endDate")
public List<EntityClassTable> getAllBetweenDates(@Param("startDate")Date startDate,@Param("endDate")Date endDate);

Python: import module from another directory at the same level in project hierarchy

From Python 2.5 onwards, you can use

from ..Modules import LDAPManager

The leading period takes you "up" a level in your heirarchy.

See the Python docs on intra-package references for imports.

How do detect Android Tablets in general. Useragent?

While we can't say if some tablets omit "mobile", many including the Samsung Galaxy Tab do have mobile in their user-agent, making it impossible to detect between an android tablet and android phone without resorting to checking model specifics. This IMHO is a waste of time unless you plan on updating and expanding your device list on a monthly basis.

Unfortunately the best solution here is to complain to Google about this and get them to fix Chrome for Android so it adds some text to identify between a mobile device and a tablet. Hell even a single letter M OR T in a specific place in the string would be enough, but I guess that makes too much sense.

How to check not in array element

you can check using php in_array() built in function

  $os = array("Mac", "NT", "Irix", "Linux");
  if (in_array("Irix", $os)) {
    echo "Got Irix";
 if (in_array("mac", $os)) {
  echo "Got mac";

and you can also check using this

  $search_array = array('first' => 1, 'second' => 4);
  if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";

in_array() is fine if you're only checking but if you need to check that a value exists and return the associated key, array_search is a better option.

$data = array(
0 => 'Key1',
1 => 'Key2'

$key = array_search('Key2', $data);

if ($key) {
 echo 'Key is ' . $key;
} else {
 echo 'Key not found';

for more details

OS detecting makefile

The git makefile contains numerous examples of how to manage without autoconf/automake, yet still work on a multitude of unixy platforms.

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){


You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

This works well in C#

var q = from m in MyTable.Take(10)
        select m.Foo

In STL maps, is it better to use map::insert than []?

Now in c++11 I think that the best way to insert a pair in a STL map is:

typedef std::map<int, std::string> MyMap;
MyMap map;

auto& result = map.emplace(3,"Hello");

The result will be a pair with:

  • First element (result.first), points to the pair inserted or point to the pair with this key if the key already exist.

  • Second element (result.second), true if the insertion was correct or false it something went wrong.

PS: If you don´t case about the order you can use std::unordered_map ;)


Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

To keep the accordion nature intact when wanting to also use 'hide' and 'show' functions like .collapse( 'hide' ), you must initialize the collapsible panels with the parent property set in the object with toggle: false before making any calls to 'hide' or 'show'

// initialize collapsible panels
$('#accordion .collapse').collapse({
  toggle: false,
  parent: '#accordion'

// show panel one (will collapse others in accordion)
$( '#collapseOne' ).collapse( 'show' );

// show panel two (will collapse others in accordion)
$( '#collapseTwo' ).collapse( 'show' );

// hide panel two (will not collapse/expand others in accordion)
$( '#collapseTwo' ).collapse( 'hide' );

Flutter: Setting the height of the AppBar

The easiest way is to use toolbarHeight property in your AppBar

Example :

   title: Text('Flutter is great'),
   toolbarHeight: 100,

You can add flexibleSpace property in your appBar for more flexibility


enter image description here

For more controls , Use the PreferedSize widget to create your own appBar

Example :

appBar: PreferredSize(
     preferredSize: Size(100, 80), //width and height 
          // The size the AppBar would prefer if there were no other constraints.
     child: SafeArea(
       child: Container(
         height: 100,
         child: Center(child: Text('Fluter is great')),

Don't forget to use a SafeArea widget if you don't have a safeArea

Output :

enter image description here

CSS root directory

In the CSS all you have to do is put url(logical path to the image file)

Windows batch files: .bat vs .cmd?

These answers are a bit too long and focused on interactive use. The important differences for scripting are:

  • .cmd prevents inadvertent execution on non-NT systems.
  • .cmd enables built-in commands to change Errorlevel to 0 on success.

Not that exciting, eh?

There used to be a number of additional features enabled in .cmd files, called Command Extensions. However, they are now enabled by default for both .bat and .cmd files under Windows 2000 and later.

Bottom line: in 2012 and beyond, I recommend using .cmd exclusively.

How can I perform an inspect element in Chrome on my Galaxy S3 Android device?

To start with you'll need the Android SDK to get started: BUT select for existing IDE so you get the tools rather than all of Android Studio.

In Chrome Beta on your Android device do the following:

Menu > Settings > Developer Tools > Enable USB Debugging

Hit the home key on the device and go to Settings > Developer Options > Enable USB Debugging

[Note: If you can't see Developer Options, go to Settings > About Device > Then tap the Build Number a number of times and eventually you'll see a message saying you are now a developer or something similar]

Connect your phone to your Computer via USB

On your Desktop open Chrome Canary (I think stable and Beta currently have issues):

In the address bar type: chrome://flags and enable - "Enable Developer Tools experiments" and hit the Relaunch button that appears.

Once it's relaunched open a terminal and run adb devices, you should now see your device appear in the list. When it has, in Canary go to chrome://inspect there you will see your device, so now click inspect.

This will open up devtools for your Chrome on Android.

Now click on the cog in the corner, then go to Experiments > Enable Port Forwarding (If you don't see port forwarding, you might not be in Chrome Beta)

Once Port forwarding is enabled, close and open dev tools.

Go back to the cog and select Port Forwarding, then type in the port you want to forward (i.e. for locahost:9000 on my local machine I'd type 9000 [Device port] and [Target]

There is a bug open where the first port is ignored, so it might be worth hitting enter on the first line and re-entering the same details on the second line.

You can now put localhost:9000 (or your port number) in Chrome for Android and view the site and use DevTools to inspect the page.

More details under Reverse Port Forwarding section of this site:

Convert float64 column to int64 in Pandas

consider using

df['column name'].astype('Int64')

nan will be changed to NaN

Radio buttons not checked in jQuery

if ( ! $("input").is(':checked') )

Doesn't work?

You might also try iterating over the elements like so:

var iz_checked = true;
   iz_checked = iz_checked && $(this).is(':checked');
if ( ! iz_checked )

Difference between malloc and calloc?

There's no difference in the size of the memory block allocated. calloc just fills the memory block with physical all-zero-bits pattern. In practice it is often assumed that the objects located in the memory block allocated with calloc have initilial value as if they were initialized with literal 0, i.e. integers should have value of 0, floating-point variables - value of 0.0, pointers - the appropriate null-pointer value, and so on.

From the pedantic point of view though, calloc (as well as memset(..., 0, ...)) is only guaranteed to properly initialize (with zeroes) objects of type unsigned char. Everything else is not guaranteed to be properly initialized and may contain so called trap representation, which causes undefined behavior. In other words, for any type other than unsigned char the aforementioned all-zero-bits patterm might represent an illegal value, trap representation.

Later, in one of the Technical Corrigenda to C99 standard, the behavior was defined for all integer types (which makes sense). I.e. formally, in the current C language you can initialize only integer types with calloc (and memset(..., 0, ...)). Using it to initialize anything else in general case leads to undefined behavior, from the point of view of C language.

In practice, calloc works, as we all know :), but whether you'd want to use it (considering the above) is up to you. I personally prefer to avoid it completely, use malloc instead and perform my own initialization.

Finally, another important detail is that calloc is required to calculate the final block size internally, by multiplying element size by number of elements. While doing that, calloc must watch for possible arithmetic overflow. It will result in unsuccessful allocation (null pointer) if the requested block size cannot be correctly calculated. Meanwhile, your malloc version makes no attempt to watch for overflow. It will allocate some "unpredictable" amount of memory in case overflow happens.

Changing project port number in Visual Studio 2013

To specify a port for the ASP.NET Development Server

  • In Solution Explorer, click the name of the application.

  • In the Properties pane, click the down-arrow beside Use dynamic ports and select False from the dropdown list.

  • This will enable editing of the Port number property.

  • In the Properties pane, click the text box beside Port number and
    type in a port number. Click outside of the Properties pane. This
    saves the property settings.

  • Each time you run a file-system Web site within Visual Web Developer, the ASP.NET Development Server will listen on the specified port.

Hope this helps.

Get characters after last / in url

Here's a beautiful dynamic function I wrote to remove last part of url or path.

 * remove the last directories
 * @param $path the path
 * @param $level number of directories to remove
 * @return string
private function removeLastDir($path, $level)
    if(is_int($level) && $level > 0){
        $path = preg_replace('#\/[^/]*$#', '', $path);
        return $this->removeLastDir($path, (int) $level - 1);
    return $path;

Access-Control-Allow-Origin: * in tomcat

Please check your web.xml again. You might be making some silly mistake. As my application is working fine with the same init-param configuration...

Please copy paste the web.xml, if the problem still persists.

"%%" and "%/%" for the remainder and the quotient

Have a look at the examples below for a clearer understanding of the differences between the different operators:

> # Floating Division:
> 5/2
[1] 2.5
> # Integer Division:
> 5%/%2
[1] 2
> # Remainder:
> 5%%2
[1] 1

How to Pass Parameters to Activator.CreateInstance<T>()


(T)Activator.CreateInstance(typeof(T), param1, param2);

Illegal string offset Warning PHP

I solved this problem by using trim() function. the issue was with space.

so lets try

$unit_size = []; //please declare the variable type 
$unit_size = exolode("x", $unit_size);
$width  = trim ($unit_size[1] );
$height = trim ($unit_size[2] );

I hope this will help you.

How to get the children of the $(this) selector?

You could also use


which would return all imgs that are descendants of the div

How do I create a slug in Django?

You will need to use the slugify function.

>>> from django.template.defaultfilters import slugify
>>> slugify("b b b b")

You can call slugify automatically by overriding the save method:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
    def save(self, *args, **kwargs):
        self.s = slugify(self.q)
        super(Test, self).save(*args, **kwargs)

Be aware that the above will cause your URL to change when the q field is edited, which can cause broken links. It may be preferable to generate the slug only once when you create a new object:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
    def save(self, *args, **kwargs):
        if not
            # Newly created object, so set slug
            self.s = slugify(self.q)

        super(Test, self).save(*args, **kwargs)

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

There are 3 ways to allow cross domain origin (excluding jsonp):

1) Set the header in the page directly using a templating language like PHP. Keep in mind there can be no HTML before your header or it will fail.

 <?php header("Access-Control-Allow-Origin:"); ?>

2) Modify the server configuration file (apache.conf) and add this line. Note that "*" represents allow all. Some systems might also need the credential set. In general allow all access is a security risk and should be avoided:

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

3) To allow multiple domains on Apache web servers add the following to your config file

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(|$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true

4) For development use only hack your browser and allow unlimited CORS using the Chrome Allow-Control-Allow-Origin extension

5) Disable CORS in Chrome: Quit Chrome completely. Open a terminal and execute the following. Just be cautious you are disabling web security:

open -a Google\ Chrome --args --disable-web-security --user-data-dir

pandas get rows which are NOT in other dataframe

extract the dissimilar rows using the merge function
df = df.merge(same.drop_duplicates(), on=['col1','col2'], 
               how='left', indicator=True)
save the dissimilar rows in CSV
df[df['_merge'] == 'left_only'].to_csv('output.csv')

How do you post data with a link

I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:

<a href="house.php?id=<?php echo $house_id;?>">
  <?php echo $house_name;?>

Then in house.php, you would get the house id using $_GET['id'], validate it using is_numeric() and then display its info.

ASP.NET MVC - passing parameters to the controller

public ActionResult ViewNextItem(int? id) makes the id integer a nullable type, no need for string<->int conversions.

Deserialize JSON array(or list) in C#

Download Json.NET from here

name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);

Select rows where column is null

for some reasons IS NULL may not work with some column data type i was in need to get all the employees that their English full name is missing ,I've used :

**SELECT emp_id ,Full_Name_Ar,Full_Name_En from employees where Full_Name_En = ' ' or Full_Name_En is null **

is there any alternative for ng-disabled in angular2?

Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable

For radio button:

<md-radio-button disabled>Select color</md-radio-button>

For dropdown:

<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>

How do I do redo (i.e. "undo undo") in Vim?

Refer to the "undo" and "redo" part of Vim document.

:red[o] (Redo one change which was undone) and {count} Ctrl+r (Redo {count} changes which were undone) are both ok.

Also, the :earlier {count} (go to older text state {count} times) could always be a substitute for undo and redo.

No Network Security Config specified, using platform default - Android Log

The message you're getting isn't an error; it's just letting you know that you're not using a Network Security Configuration. If you want to add one, take a look at this page on the Android Developers website:

Registry Key '...' has value '1.7', but '1.6' is required. Java 1.7 is Installed and the Registry is Pointing to it

Just had the similar error when installing java 8 (jdk & jre) on a system already running Java 7.

Error: Registry key 'Software\JavaSoft\Java Runtime

Environment'\CurrentVersion' has value '1.8', but '1.7' is required.

Error: could not find java.dll Error: Could not find Java SE Runtime Environment.

My environment was set up correctly (Path & java_home correctly defined), but the problem arises from the way pre-8 Java installers worked, which is that they used to copy the three executables (java.exe, javaw.exe & javaws.exe) to the Windows system directory. These remain unless overwritten by a new pre-8 installation.

However the Java 8 installer instead creates symbolic links in a new directory, C:\ProgramData\Oracle\Java\javapath, pointing to the actual JRE 8 location.

This means that you'll actually run the old 7 exes but use the new 8 DLLs.

So, the solution is simply to delete the 3 Java exes, as above, from the windows system directory.

If you are running 32-bit Java on a 64-bit Windows, the exes would be in Windows\SysWOW64, otherwise in Windows\System32.

Clearing input in vuejs form

For reset all field in one form you can use

const app = new Vue({_x000D_
    el: '#app',    _x000D_
 return{        _x000D_
            name : null,_x000D_
     lastname : null,_x000D_
     address : null_x000D_
    methods: {_x000D_
        submitForm : function(event){_x000D_
            //process...             _x000D_
form input[type=text]{border-radius:5px; padding:6px; border:1px solid #ddd}_x000D_
form input[type=submit]{border-radius:5px; padding:8px; background:#060; color:#fff; cursor:pointer; border:none}
<script src=""></script>_x000D_
<div id="app">_x000D_
<form id="todo-field" v-on:submit="submitForm">_x000D_
        <input type="text" v-model="name"><br><br>_x000D_
        <input type="text" v-model="lastname"><br><br>_x000D_
        <input type="text" v-model="address"><br><br>_x000D_
        <input type="submit" value="Send"><br>_x000D_

Laravel 5: Retrieve JSON array from $request

 // Check for presence of a body in the request
 if (count($request->json()->all())) {
     $postbody = $request->json()->all();

This is how it's done in laravel 5.2 now.

How to print VARCHAR(MAX) using Print Statement?

Or simply:

PRINT SUBSTRING(@SQL_InsertQuery, 1, 8000)
PRINT SUBSTRING(@SQL_InsertQuery, 8001, 16000)

Adding/removing items from a JavaScript object with jQuery

First off, your quoted code is not JSON. Your code is JavaScript object literal notation. JSON is a subset of that designed for easier parsing.

Your code defines an object (data) containing an array (items) of objects (each with an id, name, and type).

You don't need or want jQuery for this, just JavaScript.

Adding an item:

    {id: "7", name: "Douglas Adams", type: "comedy"}

That adds to the end. See below for adding in the middle.

Removing an item:

There are several ways. The splice method is the most versatile:

data.items.splice(1, 3); // Removes three items starting with the 2nd,
                         // ("Witches of Eastwick", "X-Men", "Ordinary People")

splice modifies the original array, and returns an array of the items you removed.

Adding in the middle:

splice actually does both adding and removing. The signature of the splice method is:

removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
  • index - the index at which to start making changes
  • num_to_remove - starting with that index, remove this many entries
  • addN - ...and then insert these elements

So I can add an item in the 3rd position like this:

data.items.splice(2, 0,
    {id: "7", name: "Douglas Adams", type: "comedy"}

What that says is: Starting at index 2, remove zero items, and then insert this following item. The result looks like this:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "7", name: "Douglas Adams", type: "comedy"},     // <== The new item
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}

You can remove some and add some at once:

data.items.splice(1, 3,
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"}

...which means: Starting at index 1, remove three entries, then add these two entries. Which results in:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}

Delete specific line from a text file?

This can be done in three steps:

// 1. Read the content of the file
string[] readText = File.ReadAllLines(path);

// 2. Empty the file
File.WriteAllText(path, String.Empty);

// 3. Fill up again, but without the deleted line
using (StreamWriter writer = new StreamWriter(path))
    foreach (string s in readText)
        if (!s.Equals(lineToBeRemoved))

PL/SQL block problem: No data found error

This data not found causes because of some datatype we are using .

like select empid into v_test

above empid and v_test has to be number type , then only the data will be stored .

So keep track of the data type , when getting this error , may be this will help

Using BufferedReader to read Text File

This is the problem:

while (br.readLine() != null) {

You've got two calls to readLine - the first only checks that there's a line (but reads it and throws it away) and the second reads the next line. You want:

String line;
while ((line = br.readLine()) != null) {

Now we're only calling readLine() once per loop iteration, and using the line that we've read both for the "have we finished?" and "print out the line" parts.

How can I include css files using node, express, and ejs?

Use this in your server.js file

app.use(express.static(__dirname + '/public'));

and add css like

<link rel="stylesheet" type="text/css" href="css/style.css" />

dont need / before css like

<link rel="stylesheet" type="text/css" href="/css/style.css" />

Hibernate: Automatically creating/updating the db tables based on entity classes

In support to @thorinkor's answer I would extend my answer to use not only @Table (name = "table_name") annotation for entity, but also every child variable of entity class should be annotated with @Column(name = "col_name"). This results into seamless updation to the table on the go.

For those who are looking for a Java class based hibernate config, the rule applies in java based configurations also(NewHibernateUtil). Hope it helps someone else.

Bootstrap Carousel : Remove auto slide


Add this to the corresponding div ...

SQL - using alias in Group By

In at least Postgres, you can use the alias name in the group by clause:

SELECT itemName as ItemName1, substring(itemName, 1,1) as FirstLetter, Count(itemName) FROM table1 GROUP BY ItemName1, FirstLetter;

I wouldn't recommend renaming an alias as a change in capitalization, that causes confusion.

adding onclick event to dynamically added button?

Remove the () from your expressions that are not working will get the desired results you need.

but.onclick= callJavascriptFunction;

How to remove an HTML element using Javascript?

That is the right code. What is probably happening is your form is submitting, and you see the new page (where the element will exist again).

How to compile C program on command line using MinGW?

I've had this problem and couldn't find why it kept happening. The reason is simple: Once you have set up the environment paths, you have to close the CMD window, and open it again for it be aware of new environment paths.

Convert form data to JavaScript object with jQuery

I checked that there is a problem with all the other answers, that if the input name is as an array, such as name[key], then it should be generated like this:

name:{ key : value }

For example: If you have an HTML form similar to the one below:

    <input name="name" value="value" >
    <input name="name1[key1]" value="value1" >
    <input name="name2[key2]" value="value2" >
    <input name="name3[key3]" value="value3" >

But it should be generated just like the JSON below, and does not become an object like the following with all the other answers. So if anyone wants to bring something like the following JSON, try the JS code below.

    name  : 'value',
    name1 : { key1 : 'value1' },
    name2 : { key2 : 'value2' },
    name3 : { key2 : 'value2' }

$.fn.getForm2obj = function() {_x000D_
  var _ = {};_x000D_
  $.map(this.serializeArray(), function(n) {_x000D_
    const keys =[a-zA-Z0-9_]+|(?=\[\])/g);_x000D_
    if (keys.length > 1) {_x000D_
      let tmp = _;_x000D_
      pop = keys.pop();_x000D_
      for (let i = 0; i < keys.length, j = keys[i]; i++) {_x000D_
        tmp[j] = (!tmp[j] ? (pop == '') ? [] : {} : tmp[j]), tmp = tmp[j];_x000D_
      if (pop == '') tmp = (!Array.isArray(tmp) ? [] : tmp), tmp.push(n.value);_x000D_
      else tmp[pop] = n.value;_x000D_
    } else _[keys.pop()] = n.value;_x000D_
  return _;_x000D_
$('form input').change(function() {_x000D_
<script src=""></script>_x000D_
  <input name="name" value="value">_x000D_
  <input type="checkbox" name="name1[]" value="1" checked="checked">1_x000D_
  <input type="checkbox" name="name1[]" value="2">2_x000D_
  <input type="checkbox" name="name1[]" value="3">3<br>_x000D_
  <input type="radio" name="gender" value="male" checked="checked">male_x000D_
  <input type="radio" name="gender" value="female"> female_x000D_
  <input name="name2[key1]" value="value1">_x000D_
  <input name="one[another][another_one]" value="value4">_x000D_
  <input name="name3[1][name]" value="value4">_x000D_
  <input name="name3[2][name]" value="value4">_x000D_
  <input name="[]" value="value5">_x000D_

alert() not working in Chrome

Here is a snippet that does not need ajQuery and will enable alerts in a disabled iframe (like on codepen)

for (var i = 0; i < document.getElementsByTagName('iframe').length; i++) {

Here is a codepen demo working with an alert() after this fix as well:

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

i think that special characters are # and @ only... query will list both.

SET @str = '[azAB09ram#reddy@wer45' + CHAR(5) + 'a~b$' 
FROM   MASTER..spt_values S 
       CROSS APPLY (SELECT SUBSTRING(@str,NUMBER,1) AS poschar) t 
       AND NUMBER <= LEN(@str) 
       AND NOT (ASCII(t.poschar) BETWEEN 65 AND 90 
                 OR ASCII(t.poschar) BETWEEN 97 AND 122 
                 OR ASCII(t.poschar) BETWEEN 48 AND 57) 

JavaScript OR (||) variable assignment explanation

This is made to assign a default value, in this case the value of y, if the x variable is falsy.

The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.

The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

For example:

"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"

Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.

Twitter bootstrap progress bar animation on page load


  • Class name changed from bar to progress-bar in v3.1.1


<div class="container">
    <div class="progress progress-striped active">
        <div class="bar" style="width: 0%;"></div>


@import url('');

.container {
    margin-top: 30px;
    width: 400px;

jQuery used in the fiddle below and on the document.ready


    var progress = setInterval(function() {
        var $bar = $('.bar');

        if ($bar.width()>=400) {
        } else {
        $bar.text($bar.width()/4 + "%");
    }, 800);




Updated JSFiddle

Is it valid to define functions in JSON results?

The problem is that JSON as a data definition language evolved out of JSON as a JavaScript Object Notation. Since Javascript supports eval on JSON, it is legitimate to put JSON code inside JSON (in that use-case). If you're using JSON to pass data remotely, then I would say it is bad practice to put methods in the JSON because you may not have modeled your client-server interaction well. And, further, when wishing to use JSON as a data description language I would say you could get yourself into trouble by embedding methods because some JSON parsers were written with only data description in mind and may not support method definitions in the structure.

Wikipedia JSON entry makes a good case for not including methods in JSON, citing security concerns:

Unless you absolutely trust the source of the text, and you have a need to parse and accept text that is not strictly JSON compliant, you should avoid eval() and use JSON.parse() or another JSON specific parser instead. A JSON parser will recognize only JSON text and will reject other text, which could contain malevolent JavaScript. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

Writelines writes lines without newline, Just fills the file

This is actually a pretty common problem for newcomers to Python—especially since, across the standard library and popular third-party libraries, some reading functions strip out newlines, but almost no writing functions (except the log-related stuff) add them.

So, there's a lot of Python code out there that does things like:

fw.write('\n'.join(line_list) + '\n')


fw.write(line + '\n' for line in line_list)

Either one is correct, and of course you could even write your own writelinesWithNewlines function that wraps it up…

But you should only do this if you can't avoid it.

It's better if you can create/keep the newlines in the first place—as in Greg Hewgill's suggestions:

line_list.append(new_line + "\n")

And it's even better if you can work at a higher level than raw lines of text, e.g., by using the csv module in the standard library, as esuaro suggests.

For example, right after defining fw, you might do this:

cw = csv.writer(fw, delimiter='|')

Then, instead of this:

new_line = d[looking_for]+'|'+'|'.join(columns[1:])

You do this:

row_list.append(d[looking_for] + columns[1:])

And at the end, instead of this:


You do this:


Finally, your design is "open a file, then build up a list of lines to add to the file, then write them all at once". If you're going to open the file up top, why not just write the lines one by one? Whether you're using simple writes or a csv.writer, it'll make your life simpler, and your code easier to read. (Sometimes there can be simplicity, efficiency, or correctness reasons to write a file all at once—but once you've moved the open all the way to the opposite end of the program from the write, you've pretty much lost any benefits of all-at-once.)

Difference between using "chmod a+x" and "chmod 755"

Indeed there is.

chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

How to get the nth element of a python list or a default if not available

Just discovered that :

next(iter(myList), 5)

iter(l) returns an iterator on myList, next() consumes the first element of the iterator, and raises a StopIteration error except if called with a default value, which is the case here, the second argument, 5

This only works when you want the 1st element, which is the case in your example, but not in the text of you question, so...

Additionally, it does not need to create temporary lists in memory and it works for any kind of iterable, even if it does not have a name (see Xiong Chiamiov's comment on gruszczy's answer)

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

Identified this solution while reading this thread. Figured id post this for the next guy possibly.

When dealing with Laravel migration file from a package, I Ran into this issue.

My old value was


My new


How to install both Python 2.x and Python 3.x in Windows

If you use Anaconda Python, you can easily install various environments.

Say you had Anaconda Python 2.7 installed and you wanted a python 3.4 environment:

conda create -n py34 python=3.4 anaconda

Then to activate the environment:

activate py34

And to deactive:

deactivate py34

(With Linux, you should use source activate py34.)


Download Anaconda Python

Instructions for environments

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

Looks like your buttons are not declared correctly (according to the latest jQuery UI documentation anyway).

try the following:

$( ".selector" ).dialog({ 
   buttons: [{ 
      text: "Ok", 
      click: function() { 
         $( this ).dialog( "close" ); 

SQL Server Script to create a new user

Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.

Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:


Here is how you create a User with db_owner privileges using the Login you just declared:

Use YourDatabase;

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
    CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
    EXEC sp_addrolemember N'db_owner', N'NewAdminName'

Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).

However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.

UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.

Garbage collector in Android

For versions prior to 3.0 honeycomb: Yes, do call System.gc().

I tried to create Bitmaps, but was always getting "VM out of memory error". But, when I called System.gc() first, it was OK.

When creating bitmaps, Android often fails with out of memory errors, and does not try to garbage collect first. Hence, call System.gc(), and you have enough memory to create Bitmaps.

If creating Objects, I think System.gc will be called automatically if needed, but not for creating bitmaps. It just fails.

So I recommend manually calling System.gc() before creating bitmaps.

How can I make PHP display the error instead of giving me 500 Internal Server Error

Be careful to check if




is active (not a comment) somewhere else in the ini file.

My development server refused to display errors after upgrade to Kubuntu 16.04 - I had checked php.ini numerous times ... turned out that there was a diplay_errors = off; about 100 lines below my

display_errors = on;

So remember the last one counts!

How do you run a command for each line of a file?

If you want to run your command in parallel for each line you can use GNU Parallel

parallel -a <your file> <program>

Each line of your file will be passed to program as an argument. By default parallel runs as many threads as your CPUs count. But you can specify it with -j

How to start anonymous thread class

The entire new expression is an object reference, so methods can be invoked on it:

public class A {
    public static void main(String[] arg)
        new Thread()
            public void run() {

How to make a Python script run like a service or daemon in Linux

If you are using terminal(ssh or something) and you want to keep a long-time script working after you log out from the terminal, you can try this:


apt-get install screen

create a virtual terminal inside( namely abc): screen -dmS abc

now we connect to abc: screen -r abc

So, now we can run python script: python

from now on, you can directly close your terminal, however, the python script will keep running rather than being shut down

Since this's PID is a child process of the virtual screen rather than the terminal(ssh)

If you want to go back check your script running status, you can use screen -r abc again

Saving an Excel sheet in a current directory with VBA

VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.

MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"

This assumes that the sheet you want to save has never been saved and you want to define the file name in code.

Convert a Unicode string to an escaped ASCII string

For Unescape You can simply use this functions:



I suggest using this method (It works better with UTF-8):


How do I force a favicon refresh?

It may be useful to just a few people, but I had the same problem and discovered that it was related to file permessions, so I gave it a 777 permission and it worked, of course after you're sure the problem it's there, make sure to change back the permissions to safer values.

How to stick text to the bottom of the page?

You might want to put the absolutely aligned div in a relatively aligned container - this way it will still be contained into the container rather than the browser window.

<div style="position: relative;background-color: blue; width: 600px; height: 800px;">    

    <div style="position: absolute; bottom: 5px; background-color: green">
    TEST (C) 2010

How to change the background colour's opacity in CSS

Use rgba as most of the commonly used browsers supports it..

.social img:hover {
 background-color: rgba(0, 0, 0, .5)

Callback functions in Java

I think using an abstract class is more elegant, like this:


public abstract class Something {   
    public abstract void test();        
    public void usingCallback() {
        System.out.println("This is before callback method");
        System.out.println("This is after callback method");


public class CallbackTest extends Something {
    public void test() {
        System.out.println("This is inside CallbackTest!");

    public static void main(String[] args) {
        CallbackTest myTest = new CallbackTest();

This is before callback method
This is inside CallbackTest!
This is after callback method

C# - using List<T>.Find() with custom objects

You can use find with a Predicate as follows:

list.Find(x => x.Id == IdToFind);

This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).

How to undo 'git reset'?

1.Use git reflog to get all references update.

2.git reset <id_of_commit_to_which_you_want_restore>

Popup Message boxes

Use the following library: import javax.swing.JOptionPane;

Input at the top of the code-line. You must only add this, because the other things is done correctly!

Goal Seek Macro with Goal as a Formula

I think your issue is that Range("H18") doesn't contain a formula. Also, you could make your code more efficient by eliminating x. Instead, change your code to

Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");

sftpChannel.put("C:/source/local/path/", "/target/remote/path/");

Similarly for a download:

sftpChannel.get("/source/remote/path/", "C:/target/local/path/");

You may need to deal with UnknownHostKey exception.

Getting attribute of element in ng-click function in angularjs

Addition to the answer of Brett DeWoody: (which is updated now)

var dataValue =;

Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:

var dataValue =;

Works in IE, Chrome and FF, I did not test Safari.

How do I disable log messages from the Requests library?

Kbrose's guidance on finding which logger was generating log messages was immensely useful. For my Django project, I had to sort through 120 different loggers until I found that it was the elasticsearch Python library that was causing issues for me. As per the guidance in most of the questions, I disabled it by adding this to my loggers:

      'elasticsearch': {
          'handlers': ['console'],
          'level': logging.WARNING,

Posting here in case someone else is seeing the unhelpful log messages come through whenever they run an Elasticsearch query.

Accessing Objects in JSON Array (JavaScript)

You can loop the array with a for loop and the object properties with for-in loops.

for (var i=0; i<result.length; i++)
    for (var name in result[i]) {
        console.log("Item name: "+name);
        console.log("Source: "+result[i][name].sourceUuid);
        console.log("Target: "+result[i][name].targetUuid);

How npm start runs a server on port 8000

To change the port

npm start --port 8000

Java equivalent of unsigned long long?

Nope, there is not. You'll have to use the primitive long data type and deal with signedness issues, or use a class such as BigInteger.

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

To be highly positive you work with the actual email body (yet, still with the possibility you're not parsing the right part), you have to skip attachments, and focus on the plain or html part (depending on your needs) for further processing.

As the before-mentioned attachments can and very often are of text/plain or text/html part, this non-bullet-proof sample skips those by checking the content-disposition header:

b = email.message_from_string(a)
body = ""

if b.is_multipart():
    for part in b.walk():
        ctype = part.get_content_type()
        cdispo = str(part.get('Content-Disposition'))

        # skip any text/plain (txt) attachments
        if ctype == 'text/plain' and 'attachment' not in cdispo:
            body = part.get_payload(decode=True)  # decode
# not multipart - i.e. plain text, no attachments, keeping fingers crossed
    body = b.get_payload(decode=True)

BTW, walk() iterates marvelously on mime parts, and get_payload(decode=True) does the dirty work on decoding base64 etc. for you.

Some background - as I implied, the wonderful world of MIME emails presents a lot of pitfalls of "wrongly" finding the message body. In the simplest case it's in the sole "text/plain" part and get_payload() is very tempting, but we don't live in a simple world - it's often surrounded in multipart/alternative, related, mixed etc. content. Wikipedia describes it tightly - MIME, but considering all these cases below are valid - and common - one has to consider safety nets all around:

Very common - pretty much what you get in normal editor (Gmail,Outlook) sending formatted text with an attachment:

 +- multipart/related
 |   |
 |   +- multipart/alternative
 |   |   |
 |   |   +- text/plain
 |   |   +- text/html
 |   |      
 |   +- image/png
 +-- application/msexcel

Relatively simple - just alternative representation:

 +- text/plain
 +- text/html

For good or bad, this structure is also valid:

 +- text/plain
 +- multipart/related
      +- text/html
      +- image/jpeg

Hope this helps a bit.

P.S. My point is don't approach email lightly - it bites when you least expect it :)

Add or change a value of JSON key with jquery or javascript

var temp = data.oldKey; // or data['oldKey']
data.newKey = temp;
delete data.oldKey;

adb uninstall failed

I had a instance of an emulator running and a device connected.

When I ran command `adb -d uninstall PACKAGE_NAME', I got an error 'DELETE_FAILED_INTERNAL_ERROR' but when I killed the Emulator instance, I got a 'success' in un-installation process.

How to select the comparison of two columns as one column in Oracle

If you want to consider null values equality too, try the following

select column1, column2, 
      when column1 is NULL and column2 is NULL then 'true'  
      when column1=column2 then 'true' 
      else 'false' 
from table;

Difference between binary semaphore and mutex

Best Solution

The only difference is

1.Mutex -> lock and unlock are under the ownership of a thread that locks the mutex.

2.Semaphore -> No ownership i.e; if one thread calls semwait(s) any other thread can call sempost(s) to remove the lock.

jQuery Datepicker with text input that doesn't allow user input

You have two options to get this done. (As far as i know)

  1. Option A: Make your text field read only. It can be done as follows.

  2. Option B: Change the curser onfocus. Set ti to blur. it can be done by setting up the attribute onfocus="this.blur()" to your date picker text field.

Ex: <input type="text" name="currentDate" id="currentDate" onfocus="this.blur()" readonly/>

Add a space (" ") after an element using :after


It's worth noting that your code does insert a space

h2::after {
  content: " ";

However, it's immediately removed.

From Anonymous inline boxes,

White space content that would subsequently be collapsed away according to the 'white-space' property does not generate any anonymous inline boxes.

And from The 'white-space' processing model,

If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.


So if you don't want the space to be removed, set white-space to pre or pre-wrap.

h2 {_x000D_
  text-decoration: underline;_x000D_
}_x000D_ {_x000D_
  content: " ";_x000D_
  white-space: pre;_x000D_
<h2>I don't have space:</h2>_x000D_
<h2 class="space">I have space:</h2>

Do not use non-breaking spaces (U+00a0). They are supposed to prevent line breaks between words. They are not supposed to be used as non-collapsible space, that wouldn't be semantic.

How to convert std::string to LPCWSTR in C++ (Unicode)

Instead of using a std::string, you could use a std::wstring.

EDIT: Sorry this is not more explanatory, but I have to run.

Use std::wstring::c_str()

Get the latest date from grouped MySQL data

Using max(date) didn't solve my problem as there is no assurance that other columns will be from the same row as the max(date) is. Instead of that this one solved my problem and sorted group by in a correct order and values of other columns are from the same row as the max date is:

SELECT model, date 
FROM (SELECT * FROM doc ORDER BY date DESC) as sortedTable
GROUP BY model

How can I get the DateTime for the start of the week?

No one seems to have answered this correctly yet. I'll paste my solution here in case anyone needs it. The following code works regardless if first day of the week is a monday or a sunday or something else.

public static class DateTimeExtension
  public static DateTime GetFirstDayOfThisWeek(this DateTime d)
    CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
    var first = (int)ci.DateTimeFormat.FirstDayOfWeek;
    var current = (int)d.DayOfWeek;

    var result = first <= current ?
      d.AddDays(-1 * (current - first)) :
      d.AddDays(first - current - 7);

    return result;

class Program
  static void Main()
    System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
    Console.WriteLine("Current culture set to en-US");
    System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("da-DK");
    Console.WriteLine("Current culture set to da-DK");

  static void RunTests()
    Console.WriteLine("Today {1}: {0}", DateTime.Today.Date.GetFirstDayOfThisWeek(), DateTime.Today.Date.ToString("yyyy-MM-dd"));
    Console.WriteLine("Saturday 2013-03-02: {0}", new DateTime(2013, 3, 2).GetFirstDayOfThisWeek());
    Console.WriteLine("Sunday 2013-03-03: {0}", new DateTime(2013, 3, 3).GetFirstDayOfThisWeek());
    Console.WriteLine("Monday 2013-03-04: {0}", new DateTime(2013, 3, 4).GetFirstDayOfThisWeek());

Special characters like @ and & in cURL POST data

cURL > 7.18.0 has an option --data-urlencode which solves this problem. Using this, I can simply send a POST request as

curl -d name=john --data-urlencode passwd=@31&3*J

Update records in table from CTE

You don't need a CTE for this

UPDATE PEDI_InvoiceDetail
    DocTotal = v.DocTotal
inner join 
   SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
   FROM PEDI_InvoiceDetail
   GROUP BY InvoiceNumber
) v
   ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber

C multi-line macro: do/while(0) vs scope block

Andrey Tarasevich provides the following explanation:

  1. On Google Groups
  2. On

[Minor changes to formatting made. Parenthetical annotations added in square brackets []].

The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.

Consider the following code sketch:

if (<condition>)

where foo and bar are ordinary functions. Now imagine that you'd like to replace function foo with a macro of the above nature [named CALL_FUNCS]:

if (<condition>)

Now, if your macro is defined in accordance with the second approach (just { and }) the code will no longer compile, because the 'true' branch of if is now represented by a compound statement. And when you put a ; after this compound statement, you finished the whole if statement, thus orphaning the else branch (hence the compilation error).

One way to correct this problem is to remember not to put ; after macro "invocations":

if (<condition>)

This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:

#define CALL_FUNCS(x) \
do { \
  func1(x); \
  func2(x); \
  func3(x); \
} while (0)

Now this code:

if (<condition>)

will compile without any problems.

However, note the small but important difference between my definition of CALL_FUNCS and the first version in your message. I didn't put a ; after } while (0). Putting a ; at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.

I don't know why the author of the code you quoted in your original message put this ; after while (0). In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final ; into the macro (for the reasons that I explained above).

How to drop a PostgreSQL database if there are active connections to it?

Here's my hack... =D

# Make sure no one can connect to this database except you!
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "UPDATE pg_database SET datallowconn=false WHERE datname='<DATABASE_NAME>';"

# Drop all existing connections except for yours!
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "SELECT pg_terminate_backend( FROM pg_stat_activity WHERE pg_stat_activity.datname = '<DATABASE_NAME>' AND pid <> pg_backend_pid();"

# Drop database! =D
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "DROP DATABASE <DATABASE_NAME>;"

I put this answer because include a command (above) to block new connections and because any attempt with the command...


... do not works to block new connections!

Thanks to @araqnid @GoatWalker ! =D

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?

I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).

However the refused message is likely a server side problem, (usually port closed).

NodeJs : TypeError: require(...) is not a function

I've faced to something like this too. in your routes file , export the function as an object like this :

 module.exports = {
     hbd: handlebar

and in your app file , you can have access to the function by .hbd and there is no ptoblem ....!

how to check if a datareader is null or empty

In addition to the suggestions given, you can do this directly from your query like this -

SELECT ISNULL([Additional], -1) AS [Additional]

This way you can write the condition to check whether the field value is < 0 or >= 0.

What is the "-->" operator in C/C++?

It's equivalent to

while (x-- > 0)

x-- (post decrement) is equivalent to x = x-1 so, the code transforms to:

while(x > 0) {
    x = x-1;
    // logic
x--;   // The post decrement done when x <= 0

How to write hello world in assembler under Windows?

Flat Assembler does not need an extra linker. This makes assembler programming quite easy. It is also available for Linux.

This is hello.asm from the Fasm examples:

include ''


    invoke  MessageBox,HWND_DESKTOP,"Hi! I'm the example program!",invoke GetCommandLine,MB_OK
    invoke  ExitProcess,0

.end start

Fasm creates an executable:

>fasm hello.asm
flat assembler  version 1.70.03  (1048575 kilobytes memory)
4 passes, 1536 bytes.

And this is the program in IDA:

enter image description here

You can see the three calls: GetCommandLine, MessageBox and ExitProcess.

Resize image proportionally with MaxHeight and MaxWidth constraints

Much longer solution, but accounts for the following scenarios:

  1. Is the image smaller than the bounding box?
  2. Is the Image and the Bounding Box square?
  3. Is the Image square and the bounding box isn't
  4. Is the image wider and taller than the bounding box
  5. Is the image wider than the bounding box
  6. Is the image taller than the bounding box

    private Image ResizePhoto(FileInfo sourceImage, int desiredWidth, int desiredHeight)
        //throw error if bouning box is to small
        if (desiredWidth < 4 || desiredHeight < 4)
            throw new InvalidOperationException("Bounding Box of Resize Photo must be larger than 4X4 pixels.");            
        var original = Bitmap.FromFile(sourceImage.FullName);
        //store image widths in variable for easier use
        var oW = (decimal)original.Width;
        var oH = (decimal)original.Height;
        var dW = (decimal)desiredWidth;
        var dH = (decimal)desiredHeight;
        //check if image already fits
        if (oW < dW && oH < dH)
            return original; //image fits in bounding box, keep size (center with css) If we made it bigger it would stretch the image resulting in loss of quality.
        //check for double squares
        if (oW == oH && dW == dH)
            //image and bounding box are square, no need to calculate aspects, just downsize it with the bounding box
            Bitmap square = new Bitmap(original, (int)dW, (int)dH);
            return square;
        //check original image is square
        if (oW == oH)
            //image is square, bounding box isn't.  Get smallest side of bounding box and resize to a square of that center the image vertically and horizontally with Css there will be space on one side.
            int smallSide = (int)Math.Min(dW, dH);
            Bitmap square = new Bitmap(original, smallSide, smallSide);
            return square;
        //not dealing with squares, figure out resizing within aspect ratios            
        if (oW > dW && oH > dH) //image is wider and taller than bounding box
            var r = Math.Min(dW, dH) / Math.Min(oW, oH); //two dimensions so figure out which bounding box dimension is the smallest and which original image dimension is the smallest, already know original image is larger than bounding box
            var nH = oH * r; //will downscale the original image by an aspect ratio to fit in the bounding box at the maximum size within aspect ratio.
            var nW = oW * r;
            var resized = new Bitmap(original, (int)nW, (int)nH);
            return resized;
            if (oW > dW) //image is wider than bounding box
                var r = dW / oW; //one dimension (width) so calculate the aspect ratio between the bounding box width and original image width
                var nW = oW * r; //downscale image by r to fit in the bounding box...
                var nH = oH * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                return resized;
                //original image is taller than bounding box
                var r = dH / oH;
                var nH = oH * r;
                var nW = oW * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                return resized;

"A referral was returned from the server" exception when accessing AD from C#

I know this might sound silly, but I recently came across this myself, Make sure the domain controller is not read-only.

Changing the browser zoom level

Not possible in IE, as the UI Zoom button in the status bar is not scriptable. YMMV for other browsers.


Android studio mac/windows/linux:

Steps in together (mac): Android Studio > Preferences > Build, Execution, Deployment > Instant Run > Uncheck : Enable Instant Run

Steps in together (windows & linux): File > Settings > Build, Execution, Deployment > Instant Run > Uncheck : Enable Instant Run

Steps in Detail :

Steps 1: Studio > Preferences (for windows & linux got to File > settings > Build, Execution, Deployment and then same as mac)

enter image description here

Steps 2: Preferences > Build, Execution, Deployment

enter image description here

Steps 3: Build, Execution, Deployment > Instant Run

enter image description here

Steps 4: Instant Run > Uncheck : Enable Instant Run

enter image description here

Reshape an array in NumPy

numpy has a great tool for this task ("numpy.reshape") link to reshape documentation

a = [[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]


you can also use the "-1" trick

`a = a.reshape(-1,3)`

the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3

so yes.. this would also work: a = a.reshape(3,-1)

and this: a = a.reshape(-1,2) would do nothing

and this: a = a.reshape(-1,9) would change the shape to (2,9)

Formatting PowerShell Get-Date inside string

You can use the -f operator

$a = "{0:D}" -f (get-date)
$a = "{0:dddd}" -f (get-date)

Spécificator    Type                                Example (with [datetime]::now)
d   Short date                                        26/09/2002
D   Long date                                       jeudi 26 septembre 2002
t   Short Hour                                      16:49
T   Long Hour                                       16:49:31
f   Date and hour                                   jeudi 26 septembre 2002 16:50
F   Long Date and hour                              jeudi 26 septembre 2002 16:50:51
g   Default Date                                    26/09/2002 16:52
G   Long default Date and hour                      26/09/2009 16:52:12
M   Month Symbol                                    26 septembre
r   Date string RFC1123                             Sat, 26 Sep 2009 16:54:50 GMT
s   Sortable string date                            2009-09-26T16:55:58
u   Sortable string date universal local hour       2009-09-26 16:56:49Z
U   Sortable string date universal GMT hour         samedi 26 septembre 2009 14:57:22 (oups)
Y   Year symbol                                     septembre 2002

Spécificator    Type                       Example      Output Example
dd              Jour                       {0:dd}       10
ddd             Name of the day            {0:ddd}      Jeu.
dddd            Complet name of the day    {0:dddd}     Jeudi
f, ff, …        Fractions of seconds       {0:fff}      932
gg, …           position                   {0:gg}       ap. J.-C.
hh              Hour two digits            {0:hh}       10
HH              Hour two digits (24 hours) {0:HH}       22
mm              Minuts 00-59               {0:mm}       38
MM              Month 01-12                {0:MM}       12
MMM             Month shortcut             {0:MMM}      Sep.
MMMM            complet name of the month  {0:MMMM}     Septembre
ss              Seconds 00-59              {0:ss}       46
tt              AM or PM                   {0:tt}       ““
yy              Years, 2 digits            {0:yy}       02
yyyy            Years                      {0:yyyy}     2002
zz              Time zone, 2 digits        {0:zz}       +02
zzz             Complete Time zone         {0:zzz}      +02:00
:               Separator                  {0:hh:mm:ss}     10:43:20
/               Separator                  {0:dd/MM/yyyy}   10/12/2002

How to store values from foreach loop into an array?

$items = array();
$count = 0;
foreach($group_membership as $i => $username) { 
 $items[$count++] = $username; 

How to set-up a favicon?

you could take a look at the w3 how to, i think you will find it helpful

your link tag attribute should be rel="icon"

getElementById returns null?

There could be many reason why document.getElementById doesn't work

  • You have an invalid ID

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)

  • you used some id that you already used as <meta> name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at (resource:

  • you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument before looking for the element (resource: Calling a specific id inside a frame)

  • you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling

I doubt you used same ID twice or more: in that case document.getElementById should return at least the first element

const char* concatenation

If you are using C++, why don't you use std::string instead of C-style strings?

std::string one="Hello";
std::string two="World";

std::string three= one+two;

If you need to pass this string to a C-function, simply pass three.c_str()

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

How to read all rows from huge table?

I think your question is similar to this thread: JDBC Pagination which contains solutions for your need.

In particular, for PostgreSQL, you can use the LIMIT and OFFSET keywords in your request:

PS: In Java code, I suggest you to use PreparedStatement instead of simple Statements:

IPhone/IPad: How to get screen width programmatically?

Take a look at UIScreen.


CGFloat width = [UIScreen mainScreen].bounds.size.width;

Take a look at the applicationFrame property if you don't want the status bar included (won't affect the width).

UPDATE: It turns out UIScreen (-bounds or -applicationFrame) doesn't take into account the current interface orientation. A more correct approach would be to ask your UIView for its bounds -- assuming this UIView has been auto-rotated by it's View controller.

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
    CGFloat width = CGRectGetWidth(self.view.bounds);

If the view is not being auto-rotated by the View Controller then you will need to check the interface orientation to determine which part of the view bounds represents the 'width' and the 'height'. Note that the frame property will give you the rect of the view in the UIWindow's coordinate space which (by default) won't be taking the interface orientation into account.

How to sort pandas data frame using values from several columns?

DataFrame.sort is deprecated; use DataFrame.sort_values.

>>> df.sort_values(['c1','c2'], ascending=[False,True])
   c1   c2
0   3   10
3   2   15
1   2   30
4   2  100
2   1   20
>>> df.sort(['c1','c2'], ascending=[False,True])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ampawake/anaconda/envs/pseudo/lib/python2.7/site-packages/pandas/core/", line 3614, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'sort'

Is it possible to specify condition in Count()?

Here is what I did to get a data set that included both the total and the number that met the criteria, within each shipping container. That let me answer the question "How many shipping containers have more than X% items over size 51"

   COUNT (UniqueID) as Total,
   SUM (
         Size > 51 
) as NumOverSize 
   customer like '%PEPSI%' 
group by
   Schedule, PackageNum

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)



//= require rails-ujs 



"Couldn't read dependencies" error with npm

I was following a doc on line and thought this error meant a problem with the dependencies in NPM. however after a third look. I realized that it was a typo. I did not add a comma after the first dependency in package.json that the tutorial asked me to edit.

Save the plots into a PDF

import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] =

Converting Integers to Roman Numerals - Java

There is actually another way of looking at this problem, not as a number problem, but a Unary problem, starting with the base character of Roman numbers, "I". So we represent the number with just I, and then we replace the characters in ascending value of the roman characters.

public String getRomanNumber(int number) {
    return join("", nCopies(number, "I"))
            .replace("IIIII", "V")
            .replace("IIII", "IV")
            .replace("VV", "X")
            .replace("VIV", "IX")
            .replace("XXXXX", "L")
            .replace("XXXX", "XL")
            .replace("LL", "C")
            .replace("LXL", "XC")
            .replace("CCCCC", "D")
            .replace("CCCC", "CD")
            .replace("DD", "M")
            .replace("DCD", "CM");

I especially like this method of solving this problem rather than using a lot of ifs and while loops, or table lookups. It is also actually a quit intuitive solution when you thinking of the problem not as a number problem.

Binding ng-model inside ng-repeat loop in AngularJS

For each iteration of the ng-repeat loop, line is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}.

Similarly, to databind to the text, databind to the same: ng-model="line.text". You don't need to use value when using ng-model (actually you shouldn't).


For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.

Cannot run Eclipse; JVM terminated. Exit code=13

I had the same issue on Ubuntu, and solved it by unpack all *.pack files in jdk directory. for example: cd /usr/java/jdk1.7.0_03/jre/lib sudo ../bin/unpack200 rt.pack rt.jar

HTML not loading CSS file

<link href="style.css" rel="stylesheet" type="text/css"/>

Delete files older than 15 days using PowerShell

The given answers will only delete files (which admittedly is what is in the title of this post), but here's some code that will first delete all of the files older than 15 days, and then recursively delete any empty directories that may have been left behind. My code also uses the -Force option to delete hidden and read-only files as well. Also, I chose to not use aliases as the OP is new to PowerShell and may not understand what gci, ?, %, etc. are.

$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

And of course if you want to see what files/folders will be deleted before actually deleting them, you can just add the -WhatIf switch to the Remove-Item cmdlet call at the end of both lines.

The code shown here is PowerShell v2.0 compatible, but I also show this code and the faster PowerShell v3.0 code as handy reusable functions on my blog.

PHP function to get the subdomain of a URL

  $url = 'http://user:[email protected]/path?argument=value#anchor';
  $array['host']=explode('.', $array['host']);

  echo $array['host'][0]; // returns 'en'

Error with multiple definitions of function

The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.

You don't want to include cpp files. You want to include header files.

The header file should just have the class definition. The corresponding cpp file, which you will compile separately, will have the function definition.


#include <iostream>

class classA {
    friend void funct();
    classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
    int propa;
    int propb;
    void outfun(){
        std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;


#include "fun.hpp"

using namespace std;

void funct(){
    cout<<"enter funct"<<endl;
    classA tmp(1,2);
    cout<<"exit funct"<<endl;


#include <iostream>
#include "fun.hpp"
using namespace std;

int main(int nargin,char* varargin[]) {
    cout<<"call funct"<<endl;
    cout<<"exit main"<<endl;
    return 0;

Note that it is generally recommended to avoid using namespace std in header files.

YouTube iframe embed - full screen

we can get the code below the video. In the share option, we will have an option embed. If we click on the embed we will get the code snippet for that video.

which will be similar to the below code

<iframe width="560" height="315" src="" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

The above code will help you to get the full-screen option.

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapper div:

.dimmed {
  position: relative;

.dimmed:after {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);

I'm using rgba here, but of course you can use other transparency methods if you like.

How to set the background image of a html 5 canvas to .png image

As shown in this example, you can apply a background to a canvas element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL().

Here are the contents of the example, for Stack Overflow posterity:

  <meta charset="utf-8">
  <title>Canvas Background through CSS</title>
  <style type="text/css" media="screen">
    canvas, img { display:block; margin:1em auto; border:1px solid black; }
    canvas { background:url(lotsalasers.jpg) }
<canvas width="800" height="300"></canvas>
<script type="text/javascript" charset="utf-8">
  var can = document.getElementsByTagName('canvas')[0];
  var ctx = can.getContext('2d');
  ctx.strokeStyle = '#f00';
  ctx.lineWidth   = 6;
  ctx.lineJoin    = 'round';
  var img = document.getElementsByTagName('img')[0];
  img.src = can.toDataURL();

How to pass data to view in Laravel?

You can pass your table data to view using compact.

$users = RoleModel::get();
 return view('super-admin',compact('users'));

What is Domain Driven Design?

I believe the following pdf will give you the bigger picture. Domain Driven Design by Eric Evans

NOTE: Think of a project you can work on, apply the little things you understood and see best practices. It will help you to grow your ability to the micro service architecture design approach too.

image.onload event and browser cache

There are two possible solutions for these kind of situations:

  1. Use the solution suggested on this post
  2. Add a unique suffix to the image src to force browser downloading it again, like this:

    var img = new Image();
    img.src = "img.jpg?_="+(new Date().getTime());
    img.onload = function () {
        alert("image is loaded");

In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again

how to set default main class in java?

Press F11 to Build and the Run the program. Once you run the program, you will have a list of classes. Select your main class from the list and click ok to run.

What is offsetHeight, clientHeight, scrollHeight?

* offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.

* clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.

* scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.

Same is the case for all of these with width instead of height.

java.util.NoSuchElementException - Scanner reading user input

You need to remove the scanner closing lines: scan.close();

It happened to me before and that was the reason.

ojdbc14.jar vs. ojdbc6.jar

I have same problem!

Found following in oracle site link text

As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.

If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.

'const int' vs. 'int const' as function parameters in C++ and C

This isn't a direct answer but a related tip. To keep things straight, I always use the convection "put const on the outside", where by "outside" I mean the far left or far right. That way there is no confusion -- the const applies to the closest thing (either the type or the *). E.g.,

int * const foo = ...; // Pointer cannot change, pointed to value can change
const int * bar = ...; // Pointer can change, pointed to value cannot change
int * baz = ...; // Pointer can change, pointed to value can change
const int * const qux = ...; // Pointer cannot change, pointed to value cannot change

Convert Java Date to UTC String


Just use Instant of java.time.


This just printed:


Instant.toString always gives UTC time.

The output is usually sortable, but there are unfortunate exceptions. toString gives you enough groups of three decimals to render the precision it holds. On the Java 9 on my Mac the precision of seems to be microseconds, but we should expect that in approximately one case out of a thousand it will hit a whole number of milliseconds and print only three decimals. Strings with unequal numbers of decimals will be sorted in the wrong order (unless you write a custom comparator to take this into account).

Instant is one of the classes in java.time, the modern Java date and time API, which I warmly recommend that you use instead of the outdated Date class. java.time is built into Java 8 and later and has also been backported to Java 6 and 7.

How to read data from excel file using c#

CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats

Good luck!

JAXB :Need Namespace Prefix to all the elements

Solved by adding

    namespace = "",
    elementFormDefault = XmlNsForm.QUALIFIED,
    xmlns = {
        @XmlNs(prefix="ns1", namespaceURI="")

package authenticator.beans.login;
import javax.xml.bind.annotation.*;


Took help of jaxb-namespaces-missing : Answer provided by Blaise Doughan

Iterating through a list to render multiple widgets in Flutter?

when you return some thing, the code exits out of the loop with what ever you are, in your code, in the first iteration, name is "one". so, as soon as it reaches return new Text(name), code exits the loop with return new Text("one"). so, try to print it or use asynchronous returns.

How to put sshpass command inside a bash script?

This worked for me:


FILELOCAL=/var/www/folder/$(date +'%Y%m%d_%H-%M-%S').csv    

    cd $FOLDER

Probably you have to install sshpass:

sudo apt-get install sshpass

Form onSubmit determine which submit button was pressed

Bare bones, but confirmed working, example:

<script type="text/javascript">
var clicked;
function mysubmit() {
<form action="" onsubmit="mysubmit();return false">
    <input type="submit" onclick="clicked='Save'" value="Save" />
    <input type="submit" onclick="clicked='Add'" value="Add" />

getFilesDir() vs Environment.getDataDirectory()

Environment returns user data directory. And getFilesDir returns application data directory.

How to get HTML 5 input type="date" working in Firefox and/or IE 10

There's a simple way to get rid of this restriction by using the datePicker component provided by jQuery.

  1. Include jQuery and jQuery UI libraries (I'm still using an old one)

    • src="js/jquery-1.7.2.js"
    • src="js/jquery-ui-1.7.2.js"
  2. Use the following snip

    $(function() {
         $( "#id_of_the_component" ).datepicker({ dateFormat: 'yy-mm-dd'}); 

See jQuery UI DatePicker - Change Date Format if needed.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

Errors: "Bad encrypt / decrypt" "gitencrypt_smudge: FAILURE: openssl error decrypting file"

There are various error strings that are thrown from openssl, depending on respective versions, and scenarios. Below is the checklist I use in case of openssl related issues:

  1. Ideally, openssl is able to encrypt/decrypt using same key (+ salt) & enc algo only.
  2. Ensure that openssl versions (used to encrypt/decrypt), are compatible. For eg. the hash used in openssl changed at version 1.1.0 from MD5 to SHA256. This produces a different key from the same password. Fix: add "-md md5" in 1.1.0 to decrypt data from lower versions, and add "-md sha256 in lower versions to decrypt data from 1.1.0

  3. Ensure that there is a single openssl version installed in your machine. In case there are multiple versions installed simultaneously (in my machine, these were installed :- 'LibreSSL 2.6.5' and 'openssl 1.1.1d'), make the sure that only the desired one appears in your PATH variable.

Sort ObservableCollection<string> through C#

myObservableCollection.ToList().Sort((x, y) => x.Property.CompareTo(y.Property));

How to resolve 'npm should be run outside of the node repl, in your normal shell'

As mscdex said NPM comes with the nodejs msi installed file. I happened to just install the node js installer (standalone). To separately add NPM I followed following step

  1. Download the latest zip file of NPM from here.
  2. Extract it in the same file as that of node js installer.
  3. If you have added the directory containing to node js installer to PATH env variable then now even npm should be a recognized command.

Skip first line(field) in loop using CSV file?

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

with open(filename, 'r') as f:
    for line in f:


with open(filename,'r') as f:
    lines = f.readlines()[1:]

Can we add div inside table above every <tr>?

You can not use tag to make group of more than one tag. If you want to make group of tag for any purpose like in ajax to change particular group or in CSS to change style of particular tag etc. then use


  <tbody id="foods">
      <td>Group 1</td>
      <td>Group 1</td>

  <tbody id="drinks">
      <td>Group 2</td>
      <td>Group 2</td>