Programs & Examples On #Bare metal

In a bare-metal environment, the software runs directly on the hardware (CPU, microprocessor, etc) without the intermediary layer of an operating system.

Java - Find shortest path between 2 points in a distance weighted map

Like SplinterReality said: There's no reason not to use Dijkstra's algorithm here.

The code below I nicked from here and modified it to solve the example in the question.

import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

class Vertex implements Comparable<Vertex>
{
    public final String name;
    public Edge[] adjacencies;
    public double minDistance = Double.POSITIVE_INFINITY;
    public Vertex previous;
    public Vertex(String argName) { name = argName; }
    public String toString() { return name; }
    public int compareTo(Vertex other)
    {
        return Double.compare(minDistance, other.minDistance);
    }

}


class Edge
{
    public final Vertex target;
    public final double weight;
    public Edge(Vertex argTarget, double argWeight)
    { target = argTarget; weight = argWeight; }
}

public class Dijkstra
{
    public static void computePaths(Vertex source)
    {
        source.minDistance = 0.;
        PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
        vertexQueue.add(source);

        while (!vertexQueue.isEmpty()) {
            Vertex u = vertexQueue.poll();

            // Visit each edge exiting u
            for (Edge e : u.adjacencies)
            {
                Vertex v = e.target;
                double weight = e.weight;
                double distanceThroughU = u.minDistance + weight;
                if (distanceThroughU < v.minDistance) {
                    vertexQueue.remove(v);

                    v.minDistance = distanceThroughU ;
                    v.previous = u;
                    vertexQueue.add(v);
                }
            }
        }
    }

    public static List<Vertex> getShortestPathTo(Vertex target)
    {
        List<Vertex> path = new ArrayList<Vertex>();
        for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
            path.add(vertex);

        Collections.reverse(path);
        return path;
    }

    public static void main(String[] args)
    {
        // mark all the vertices 
        Vertex A = new Vertex("A");
        Vertex B = new Vertex("B");
        Vertex D = new Vertex("D");
        Vertex F = new Vertex("F");
        Vertex K = new Vertex("K");
        Vertex J = new Vertex("J");
        Vertex M = new Vertex("M");
        Vertex O = new Vertex("O");
        Vertex P = new Vertex("P");
        Vertex R = new Vertex("R");
        Vertex Z = new Vertex("Z");

        // set the edges and weight
        A.adjacencies = new Edge[]{ new Edge(M, 8) };
        B.adjacencies = new Edge[]{ new Edge(D, 11) };
        D.adjacencies = new Edge[]{ new Edge(B, 11) };
        F.adjacencies = new Edge[]{ new Edge(K, 23) };
        K.adjacencies = new Edge[]{ new Edge(O, 40) };
        J.adjacencies = new Edge[]{ new Edge(K, 25) };
        M.adjacencies = new Edge[]{ new Edge(R, 8) };
        O.adjacencies = new Edge[]{ new Edge(K, 40) };
        P.adjacencies = new Edge[]{ new Edge(Z, 18) };
        R.adjacencies = new Edge[]{ new Edge(P, 15) };
        Z.adjacencies = new Edge[]{ new Edge(P, 18) };


        computePaths(A); // run Dijkstra
        System.out.println("Distance to " + Z + ": " + Z.minDistance);
        List<Vertex> path = getShortestPathTo(Z);
        System.out.println("Path: " + path);
    }
}

The code above produces:

Distance to Z: 49.0
Path: [A, M, R, P, Z]

Capture Video of Android's Screen

Take a look at Remote Manager. But seems to me it doesn't work correctly with devices which have big screen. Although, you can try DEMO before.

How do I write a "tab" in Python?

As it wasn't mentioned in any answers, just in case you want to align and space your text, you can use the string format features. (above python 2.5) Of course \t is actually a TAB token whereas the described method generates spaces.

Example:

print "{0:30} {1}".format("hi", "yes")
> hi                             yes

Another Example, left aligned:

print("{0:<10} {1:<10} {2:<10}".format(1.0, 2.2, 4.4))
>1.0        2.2        4.4 

How to SFTP with PHP?

The ssh2 functions aren't very good. Hard to use and harder yet to install, using them will guarantee that your code has zero portability. My recommendation would be to use phpseclib, a pure PHP SFTP implementation.

How to add RSA key to authorized_keys file?

I know I am replying too late but for anyone else who needs this, run following command from your local machine

cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

this has worked perfectly fine. All you need to do is just to replace

[email protected]

with your own user for that particular host

Formula to determine brightness of RGB color

Please define brightness. If you're looking for how close to white the color is you can use Euclidean Distance from (255, 255, 255)

java.io.FileNotFoundException: the system cannot find the file specified

Relative paths can be used, but they can be tricky. The best solution is to know where your files are being saved, that is, print the folder:

import java.io.File;
import java.util.*;

public class Hangman1 {

    public static void main(String[] args) throws Exception {
        File myFile = new File("word.txt");
        System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());

        Scanner input = new Scanner(myFile);
        String in = "";
        in = input.nextLine();
    }

}

This code should print the folder where it is looking for. Place the file there and you'll be good to go.

Unsigned values in C

In the hexadecimal it can't get a negative value. So it shows it like ffffffff.

The advantage to using the unsigned version (when you know the values contained will be non-negative) is that sometimes the computer will spot errors for you (the program will "crash" when a negative value is assigned to the variable).

connecting to MySQL from the command line

This worked for me ::-

mysql --host=hostNameorIp --user=username --password=password  

or

mysql --host=hostNameorIp --user=username --password=password database_name

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

I ran into this in IntelliJ and fixed it by adding the following to my pom:

<!-- logging dependencies -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>${logback.version}</version>
        <exclusions>
            <exclusion>
                <!-- Defined below -->
                <artifactId>slf4j-api</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>

HTML5 LocalStorage: Checking if a key exists

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

if(localStorage.getItem("username") === null){

What is the use of hashCode in Java?

Although hashcode does nothing with your business logic, we have to take care of it in most cases. Because when your object is put into a hash based container(HashSet, HashMap...), the container puts/gets the element's hashcode.

How to filter a RecyclerView with a SearchView

Recyclerview with searchview and clicklistener

Add an interface in your adapter.

public interface SelectedUser{

    void selectedUser(UserModel userModel);

}

implement the interface in your mainactivity and override the method. @Override public void selectedUser(UserModel userModel) {

    startActivity(new Intent(MainActivity.this, SelectedUserActivity.class).putExtra("data",userModel));



}

Full tutorial and source code: Recyclerview with searchview and onclicklistener

Update query using Subquery in Sql Server

because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:

SELECT *
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Then note that we have two table aliases a and b. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b, the statement will be:

UPDATE  b
SET     b.marks = a.marks
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a only (leaving b intact) for those records that match by name:

DELETE a
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

You can use the SQL Fiddle created by JW as a playground

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

Yet another node based simple command line server

https://github.com/greggman/servez-cli

Written partly in response to http-server having issues, particularly on windows.

installation

Install node.js then

npm install -g servez

usage

servez [options] [path]

With no path it serves the current folder.

By default it serves index.html for folder paths if it exists. It serves a directory listing for folders otherwise. It also serves CORS headers. You can optionally turn on basic authentication with --username=somename --password=somepass and you can serve https.

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

tl;dr

java.sql.Timestamp.from (
    LocalDate.of ( 2007 , 9 , 23 )
             .atStartOfDay( ZoneId.of ( "America/Montreal" ) )
             .toInstant()
)

java.time

Let’s update this page by showing code using the java.time framework built into Java 8 and later.

These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They supplant the notoriously troublesome old date-time classes bundled with early versions of Java.

In java.time, an Instant is a moment on the timeline in UTC. A ZonedDateTime is an Instant adjusted into a time zone (ZoneId).

Time zone is crucial here. A date of September 23, 2007 cannot be translated to a moment on the timeline without applying a time zone. Consider that a new day dawns earlier in Paris than in Montréal where it is still “yesterday”.

Also, a java.sql.Timestamp represents both a date and time-of-day. So we must inject a time-of-day to go along with the date. We assume you want the first moment of the day as the time-of-day. Note that this is not always the time 00:00:00.0 because of Daylight Saving Time and possibly other anomalies.

Note that unlike the old java.util.Date class, and unlike Joda-Time, the java.time types have a resolution of nanoseconds rather than milliseconds. This matches the resolution of java.sql.Timestamp.

Note that the java.sql.Timestamp has a nasty habit of implicitly applying your JVM’s current default time zone to its date-time value when generating a string representation via its toString method. Here you see my America/Los_Angeles time zone applied. In contrast, the java.time classes are more sane, using standard ISO 8601 formats.

LocalDate d = LocalDate.of ( 2007 , 9 , 23 ) ;
ZoneId z = ZoneId.of ( "America/Montreal" ) ;
ZonedDateTime zdt = d.atStartOfDay( z ) ;
Instant instant = zdt.toInstant() ;
java.sql.Timestamp ts = java.sql.Timestamp.from ( instant ) ;

Dump to console.

System.out.println ( "d: " + d + " = zdt: " + zdt + " = instant: " + instant + " = ts: " + ts );

When run.

d: 2007-09-23 = zdt: 2007-09-23T00:00-04:00[America/Montreal] = instant: 2007-09-23T04:00:00Z = ts: 2007-09-22 21:00:00.0

By the way, as of JDBC 4.2, you can use the java.time types directly. No need for java.sql.Timestamp.

  • PreparedStatement.setObject
  • ResultSet.getObject

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to create empty text file from a batch file?

fsutil file createnew file.cmd 0

how do I join two lists using linq or lambda expressions

 public class State
        {
            public int SID { get; set; }
            public string SName { get; set; }
            public string SCode { get; set; }
            public string SAbbrevation { get; set; }
        }

        public class Country
        {
            public int CID { get; set; }
            public string CName { get; set; }
            public string CAbbrevation { get; set; }
        }


 List<State> states = new List<State>()
            {
               new  State{  SID=1,SName="Telangana",SCode="+91",SAbbrevation="TG"},
               new  State{  SID=2,SName="Texas",SCode="512",SAbbrevation="TS"},
            };

            List<Country> coutries = new List<Country>()
            {
               new Country{CID=1,CName="India",CAbbrevation="IND"},
               new Country{CID=2,CName="US of America",CAbbrevation="USA"},
            };

            var res = coutries.Join(states, a => a.CID, b => b.SID, (a, b) => new {a.CName,b.SName}).ToList();

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

I like to make use of the css :before and a data-* attribute for the list

HTML:

<ul data-header="heading"> 
<li>list item </li>
<li>list item </li>
<li>list item </li>
</ul>

CSS:

ul:before{
    content:attr(data-header);
    font-size:120%;
    font-weight:bold;
    margin-left:-15px;
}

This will make a list with the header on it that is whatever text is specified as the list's data-header attribute. You can then easily style it to your needs.

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

shared global variables in C

In the header file

header file

#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef  MAIN_FILE
int global;
#else
extern int global;
#endif
#endif

In the file with the file you want the global to live:

#define MAIN_FILE
#include "share.h"

In the other files that need the extern version:

#include "share.h"

Is it possible to add an HTML link in the body of a MAILTO link

Section 2 of RFC 2368 says that the body field is supposed to be in text/plain format, so you can't do HTML.

However even if you use plain text it's possible that some modern mail clients would render a URL as a clickable link anyway, though.

How can I tell if a Java integer is null?

For me just using the Integer.toString() method works for me just fine. You can convert it over if you just want to very if it is null. Example below:

private void setCarColor(int redIn, int blueIn, int greenIn)
{
//Integer s = null;
if (Integer.toString(redIn) == null || Integer.toString(blueIn) == null ||     Integer.toString(greenIn) == null )

Set a default font for whole iOS app?

Swift 5

Base on Fábio Oliveira's answer (https://stackoverflow.com/a/23042694/2082851), I make my own swift 4.

In short, this extension exchanges default functions init(coder:), systemFont(ofSize:), boldSystemFont(ofSize:), italicSystemFont(ofSize:) with my custom methods.

Note that it's not fully implement, but you can exchange more methods base on my implementation.

import UIKit

struct AppFontName {
    static let regular = "CourierNewPSMT"
    static let bold = "CourierNewPS-BoldMT"
    static let italic = "CourierNewPS-ItalicMT"
}

extension UIFontDescriptor.AttributeName {
    static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
}

extension UIFont {
    static var isOverrided: Bool = false

    @objc class func mySystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: AppFontName.regular, size: size)!
    }

    @objc class func myBoldSystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: AppFontName.bold, size: size)!
    }

    @objc class func myItalicSystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: AppFontName.italic, size: size)!
    }

    @objc convenience init(myCoder aDecoder: NSCoder) {
        guard
            let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor,
            let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String else {
                self.init(myCoder: aDecoder)
                return
        }
        var fontName = ""
        switch fontAttribute {
        case "CTFontRegularUsage":
            fontName = AppFontName.regular
        case "CTFontEmphasizedUsage", "CTFontBoldUsage":
            fontName = AppFontName.bold
        case "CTFontObliqueUsage":
            fontName = AppFontName.italic
        default:
            fontName = AppFontName.regular
        }
        self.init(name: fontName, size: fontDescriptor.pointSize)!
    }

    class func overrideInitialize() {
        guard self == UIFont.self, !isOverrided else { return }

        // Avoid method swizzling run twice and revert to original initialize function
        isOverrided = true

        if let systemFontMethod = class_getClassMethod(self, #selector(systemFont(ofSize:))),
            let mySystemFontMethod = class_getClassMethod(self, #selector(mySystemFont(ofSize:))) {
            method_exchangeImplementations(systemFontMethod, mySystemFontMethod)
        }

        if let boldSystemFontMethod = class_getClassMethod(self, #selector(boldSystemFont(ofSize:))),
            let myBoldSystemFontMethod = class_getClassMethod(self, #selector(myBoldSystemFont(ofSize:))) {
            method_exchangeImplementations(boldSystemFontMethod, myBoldSystemFontMethod)
        }

        if let italicSystemFontMethod = class_getClassMethod(self, #selector(italicSystemFont(ofSize:))),
            let myItalicSystemFontMethod = class_getClassMethod(self, #selector(myItalicSystemFont(ofSize:))) {
            method_exchangeImplementations(italicSystemFontMethod, myItalicSystemFontMethod)
        }

        if let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:))), // Trick to get over the lack of UIFont.init(coder:))
            let myInitCoderMethod = class_getInstanceMethod(self, #selector(UIFont.init(myCoder:))) {
            method_exchangeImplementations(initCoderMethod, myInitCoderMethod)
        }
    }
}


class AppDelegate: UIResponder, UIApplicationDelegate {
    // Avoid warning of Swift
    // Method 'initialize()' defines Objective-C class method 'initialize', which is not guaranteed to be invoked by Swift and will be disallowed in future versions
    override init() {
        super.init()
        UIFont.overrideInitialize()
    }
    ...
}

Multiple file extensions in OpenFileDialog

This is from MSDN sample:

(*.bmp, *.jpg)|*.bmp;*.jpg

So for your case

openFileDialog1.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg|TIFF (*.tif,*.tiff)|*.tif;*.tiff"

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

All columns from a matrix into a new list:

N = len(matrix) 
column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]

Save array in mysql database

You can use MySQL JSON datatype to store the array

mysql> CREATE TABLE t1 (jdoc JSON);

Query OK, 0 rows affected (0.20 sec)

mysql> INSERT INTO t1 VALUES('{"key1": "value1", "key2": "value2"}');

Query OK, 1 row affected (0.01 sec)

To get the above object in PHP

json_encode(["key1"=> "value1", "key2"=> "value2"]);

More in https://dev.mysql.com/doc/refman/8.0/en/json.html

Combining two lists and removing duplicates, without removing duplicates in original list

Simplest to me is:

first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]

merged_list = list(set(first_list+second_list))
print(merged_list)

#prints [1, 2, 5, 7, 9]

Eclipse: All my projects disappeared from Project Explorer

1) File > import > Existing projects into workspace 2) Choose your workspace folder 3) select all of your projects 4) finish

All are OK with above way !!!

Search in lists of lists by given index

>>> the_list =[ ['a','b'], ['a','c'], ['b''d'] ]
>>> any('c' == x[1] for x in the_list)
True

Changing datagridview cell color dynamically

Thanks it working

here i am done with this by qty field is zero means it shown that cells are in red color

        int count = 0;

        foreach (DataGridViewRow row in ItemDg.Rows)
        {
            int qtyEntered = Convert.ToInt16(row.Cells[1].Value);
            if (qtyEntered <= 0)
            {
                ItemDg[0, count].Style.BackColor = Color.Red;//to color the row
                ItemDg[1, count].Style.BackColor = Color.Red;

                ItemDg[0, count].ReadOnly = true;//qty should not be enter for 0 inventory                       
            }
            ItemDg[0, count].Value = "0";//assign a default value to quantity enter
            count++;
        }

    }

How do I cancel form submission in submit button onclick event?

Sometimes onsubmit wouldn't work with asp.net.

I solved it with very easy way.

if we have such a form

<form method="post" name="setting-form" >
   <input type="text" id="UserName" name="UserName" value="" 
      placeholder="user name" >
   <input type="password" id="Password" name="password" value="" placeholder="password" >
   <div id="remember" class="checkbox">
    <label>remember me</label>
    <asp:CheckBox ID="RememberMe" runat="server" />
   </div>
   <input type="submit" value="login" id="login-btn"/>
</form>

You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.

$(document).ready(function () {
            $("#login-btn").click(function (event) {
                event.preventDefault();
                alert("do what ever you want");
            });
 });

How to Position a table HTML?

You would want to use CSS to achieve that.

say you have a table with the attribute id="my_table"

You would want to write the following in your css file

#my_table{
    margin-top:10px //moves your table 10pixels down
    margin-left:10px //moves your table 10pixels right
}

if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px to the style attribute in your table element like so

<table style="margin-top:10px; margin-left:10px;">
    ....
</table>

There are a lot of resources on the net describing CSS and HTML in detail

Why does make think the target is up to date?

Maybe you have a file/directory named test in the directory. If this directory exists, and has no dependencies that are more recent, then this target is not rebuild.

To force rebuild on these kind of not-file-related targets, you should make them phony as follows:

.PHONY: all test clean

Note that you can declare all of your phony targets there.

A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request.

How do I catch a PHP fatal (`E_ERROR`) error?

If you are using PHP >= 5.1.0 Just do something like this with the ErrorException class:

<?php
    // Define an error handler
    function exception_error_handler($errno, $errstr, $errfile, $errline ) {
        throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
    }

    // Set your error handler
    set_error_handler("exception_error_handler");

    /* Trigger exception */
    try
    {
        // Try to do something like finding the end of the internet
    }
    catch(ErrorException $e)
    {
        // Anything you want to do with $e
    }
?>

Free tool to Create/Edit PNG Images?

I use Pixlr - an online photo editor, it has great filters and user friendly interface.

How do I access ViewBag from JS

You can achieve the solution, by doing this:

JavaScript:

var myValue = document.getElementById("@(ViewBag.CC)").value;

or if you want to use jQuery, then:

jQuery

var myValue = $('#' + '@(ViewBag.CC)').val();

throwing exceptions out of a destructor

Throwing out of a destructor can result in a crash, because this destructor might be called as part of "Stack unwinding". Stack unwinding is a procedure which takes place when an exception is thrown. In this procedure, all the objects that were pushed into the stack since the "try" and until the exception was thrown, will be terminated -> their destructors will be called. And during this procedure, another exception throw is not allowed, because it's not possible to handle two exceptions at a time, thus, this will provoke a call to abort(), the program will crash and the control will return to the OS.

SVN 405 Method Not Allowed

The quickest way for me to fix it was to duplicate the affected folder, and commit it with an alternative name. Then svn mv duplicateFolder originalFolder. Pretty easy.

So, take folder1 and make a folder1Copy:

svn delete folder1
svn add folder1Copy

Commit and update:

svn mv folder1Copy/ folder1/

Commit again and it's fixed.

How to capitalize the first letter of word in a string using Java?

String s=t.getText().trim();
int l=s.length();
char c=Character.toUpperCase(s.charAt(0));
s=c+s.substring(1);
for(int i=1; i<l; i++)
    {
        if(s.charAt(i)==' ')
        {
            c=Character.toUpperCase(s.charAt(i+1));
            s=s.substring(0, i) + c + s.substring(i+2);
        }
    }
    t.setText(s);

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

Long story short, it probably doesn't matter. Use whichever you think looks nicest.

Longer answer, using Oracle's Java 7 JDK specifically, since this isn't defined at the JLS:

String.valueOf or Character.toString work the same way, so use whichever you feel looks nicer. In fact, Character.toString simply calls String.valueOf (source).

So the question is, should you use one of those or String.substring. Here again it doesn't matter much. String.substring uses the original string's char[] and so allocates one object fewer than String.valueOf. This also prevents the original string from being GC'ed until the one-character string is available for GC (which can be a memory leak), but in your example, they'll both be available for GC after each iteration, so that doesn't matter. The allocation you save also doesn't matter -- a char[1] is cheap to allocate, and short-lived objects (as the one-char string will be) are cheap to GC, too.

If you have a large enough data set that the three are even measurable, substring will probably give a slight edge. Like, really slight. But that "if... measurable" contains the real key to this answer: why don't you just try all three and measure which one is fastest?

Specify JDK for Maven to use

Using this command below also worked for me, using it right after installation of Java 8 from here https://www.oracle.com/java/technologies/javase-downloads.html

export JAVA_HOME=$(/usr/libexec/java_home)

$lookup on ObjectId's in an array

I have to disagree, we can make $lookup work with IDs array if we preface it with $match stage.

_x000D_
_x000D_
// replace IDs array with lookup results_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
            localField: "products",_x000D_
            foreignField: "_id",_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

It becomes more complicated if we want to pass the lookup result to a pipeline. But then again there's a way to do so (already suggested by @user12164):

_x000D_
_x000D_
// replace IDs array with lookup results passed to pipeline_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
             let: { products: "$products"},_x000D_
             pipeline: [_x000D_
                 { $match: { $expr: {$in: ["$_id", "$$products"] } } },_x000D_
                 { $project: {_id: 0} } // suppress _id_x000D_
             ],_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

Indexes of all occurrences of character in a string

String string = "bannanas";
ArrayList<Integer> list = new ArrayList<Integer>();
char character = 'n';
for(int i = 0; i < string.length(); i++){
    if(string.charAt(i) == character){
       list.add(i);
    }
}

Result would be used like this :

    for(Integer i : list){
        System.out.println(i);
    }

Or as a array :

list.toArray();

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

How to download file from database/folder using php

You can also use the following code:

<?php
$filename = $_GET["nama"];
$contenttype = "application/force-download";
header("Content-Type: " . $contenttype);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
readfile("your file uploaded path".$filename);
exit();
?>

Firebase (FCM) how to get token

In firebase-messaging:17.1.0 and newer the FirebaseInstanceIdService is deprecated, you can get the onNewToken on the FirebaseMessagingService class as explained on https://stackoverflow.com/a/51475096/1351469

But if you want to just get the token any time, then now you can do it like this:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( this.getActivity(),  new OnSuccessListener<InstanceIdResult>() {
  @Override
  public void onSuccess(InstanceIdResult instanceIdResult) {
    String newToken = instanceIdResult.getToken();
    Log.e("newToken",newToken);
  }
});

HTTP Error 404 when running Tomcat from Eclipse

Check the server configuration and folders' routes:

  1. Open servers view (Window -> Open view... -> Others... -> Search for 'servers'.

  2. Right click on server (mine is Tomcat v6.0) -> properties -> Click on 'Swicth Location' (check that location's like /servers...

  3. Double click on the server. This will open a new servers page. In the 'Servers Locations' area, check the 'Use Tomcat Installation (takes control of Tomcat Installation)' option.

  4. Restart your server.

  5. Enjoy!

Insert entire DataTable into database at once instead of row by row?

I would prefer user defined data type : it is super fast.

Step 1 : Create User Defined Table in Sql Server DB

CREATE TYPE [dbo].[udtProduct] AS TABLE(
  [ProductID] [int] NULL,
  [ProductName] [varchar](50) NULL,
  [ProductCode] [varchar](10) NULL
)
GO

Step 2 : Create Stored Procedure with User Defined Type

CREATE PROCEDURE ProductBulkInsertion 
@product udtProduct readonly
AS
BEGIN
    INSERT INTO Product
    (ProductID,ProductName,ProductCode)
    SELECT ProductID,ProductName,ProductCode
    FROM @product
END

Step 3 : Execute Stored Procedure from c#

SqlCommand sqlcmd = new SqlCommand("ProductBulkInsertion", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("@product", productTable);
sqlcmd.ExecuteNonQuery();

Possible Issue : Alter User Defined Table

Actually there is no sql server command to alter user defined type But in management studio you can achieve this from following steps

1.generate script for the type.(in new query window or as a file) 2.delete user defied table. 3.modify the create script and then execute.

Format number to 2 decimal places

When formatting number to 2 decimal places you have two options TRUNCATE and ROUND. You are looking for TRUNCATE function.

Examples:

Without rounding:

TRUNCATE(0.166, 2)
-- will be evaluated to 0.16

TRUNCATE(0.164, 2)
-- will be evaluated to 0.16

docs: http://www.w3resource.com/mysql/mathematical-functions/mysql-truncate-function.php

With rounding:

ROUND(0.166, 2)
-- will be evaluated to 0.17

ROUND(0.164, 2)
-- will be evaluated to 0.16

docs: http://www.w3resource.com/mysql/mathematical-functions/mysql-round-function.php

What does 'IISReset' do?

When you change an ASP.NET website's configuration file, it restarts the application to reflect the changes...

When you do an IIS reset, that restarts all applications running on that IIS instance.

How can I send an email through the UNIX mailx command?

If you want to send more than two person or DL :

echo "Message Body" | mailx -s "Message Title" -r [email protected] [email protected],[email protected]

here:

  • -s = subject or mail title
  • -r = sender mail or DL

How can I rollback a git repository to a specific commit?

Most suggestions are assuming that you need to somehow destroy the last 20 commits, which is why it means "rewriting history", but you don't have to.

Just create a new branch from the commit #80 and work on that branch going forward. The other 20 commits will stay on the old orphaned branch.

If you absolutely want your new branch to have the same name, remember that branch are basically just labels. Just rename your old branch to something else, then create the new branch at commit #80 with the name you want.

Loading a .json file into c# program

See Microsofts JavaScriptSerializer

The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.

Namespace: System.Web.Script.Serialization

Assembly: System.Web.Extensions (in System.Web.Extensions.dll)

How to capture a backspace on the onkeydown event

Nowadays, code to do this should look something like:

document.getElementById('foo').addEventListener('keydown', function (event) {
    if (event.keyCode == 8) {
        console.log('BACKSPACE was pressed');

        // Call event.preventDefault() to stop the character before the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
    if (event.keyCode == 46) {
        console.log('DELETE was pressed');

        // Call event.preventDefault() to stop the character after the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
});

although in the future, once they are broadly supported in browsers, you may want to use the .key or .code attributes of the KeyboardEvent instead of the deprecated .keyCode.

Details worth knowing:

  • Calling event.preventDefault() in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document instead of a text field).

  • Documentation on how the value of the keyCode attribute is determined can be found in section B.2.1 How to determine keyCode for keydown and keyup events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.

  • There is an effort underway to deprecate the .keyCode attribute in favour of .key and .code. The W3 describe the .keyCode property as "legacy", and MDN as "deprecated".

    One benefit of the change to .key and .code is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace" and "Delete" and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.

    On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.

    The .key attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete". The .code attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace".

    Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:

    document.getElementById('foo').addEventListener('keydown', function (event) {
        if (event.code == 'Delete') {
            console.log('The physical key pressed was the DELETE key');
        }
        if (event.code == 'Backspace') {
            console.log('The physical key pressed was the BACKSPACE key');
        } 
        if (event.key == 'Delete') {
            console.log('The keypress meant the same as pressing DELETE');
            // This can happen for one of two reasons:
            // 1. The user pressed the DELETE key
            // 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
            //    FN+BACKSPACE deletes the character in front of the text cursor,
            //    instead of the one behind it.
        }
        if (event.key == 'Backspace') {
            console.log('The keypress meant the same as pressing BACKSPACE');
        }
    });
    

How to edit default dark theme for Visual Studio Code?

As others have stated, you'll need to override the editor.tokenColorCustomizations or the workbench.colorCustomizations setting in the settings.json file. Here you can choose a base theme, like Abyss, and only override the things you want to change. You can either override very few things like the function, string colors etc. very easily.

E.g. for workbench.colorCustomizations

"workbench.colorCustomizations": {
    "[Default Dark+]": {
        "editor.background": "#130e293f",
    }
}

E.g. for editor.tokenColorCustomizations:

"editor.tokenColorCustomizations": {
    "[Abyss]": {
        "functions": "#FF0000",
        "strings": "#FF0000"
    }
}
// Don't do this, looks horrible.

However, deep customisations like change the colour of the var keyword will require you to provide the override values under the textMateRules key.

E.g. below:

"editor.tokenColorCustomizations": {
    "[Abyss]": {
        "textMateRules": [
            {
                "scope": "keyword.operator",
                "settings": {
                    "foreground": "#FFFFFF"
                }
            },
            {
                "scope": "keyword.var",
                "settings": {
                    "foreground": "#2871bb",
                    "fontStyle": "bold"
                }
            }
        ]
    }
}

You can also override globally across themes:

"editor.tokenColorCustomizations": {
    "textMateRules": [
        {
            "scope": [
                //following will be in italics (=Pacifico)
                "comment",
                "entity.name.type.class", //class names
                "keyword", //import, export, return…
                //"support.class.builtin.js", //String, Number, Boolean…, this, super
                "storage.modifier", //static keyword
                "storage.type.class.js", //class keyword
                "storage.type.function.js", // function keyword
                "storage.type.js", // Variable declarations
                "keyword.control.import.js", // Imports
                "keyword.control.from.js", // From-Keyword
                //"entity.name.type.js", // new … Expression
                "keyword.control.flow.js", // await
                "keyword.control.conditional.js", // if
                "keyword.control.loop.js", // for
                "keyword.operator.new.js", // new
            ],
            "settings": {
                "fontStyle": "italic"
            }
        }
    ]
}

More details here: https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide

Default Values to Stored Procedure in Oracle

Default-Values are only considered for parameters NOT given to the function.

So given a function

procedure foo( bar1 IN number DEFAULT 3,
     bar2 IN number DEFAULT 5,
     bar3 IN number DEFAULT 8 );

if you call this procedure with no arguments then it will behave as if called with

foo( bar1 => 3,
     bar2 => 5,
     bar3 => 8 );

but 'NULL' is still a parameter.

foo( 4,
     bar3 => NULL );

This will then act like

foo( bar1 => 4,
     bar2 => 5,
     bar3 => Null );

( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )

one way to treat NULL the same as a default value would be to default the value to NULL

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL );

and using a variable with the desired value then

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL )
AS
     v_bar1    number := NVL( bar1, 3);
     v_bar2    number := NVL( bar2, 5);
     v_bar3    number := NVL( bar3, 8);

Using ConfigurationManager to load config from an arbitrary location

In addition to Ishmaeel's answer, the method OpenMappedMachineConfiguration() will always return a Configuration object. So to check to see if it loaded you should check the HasFile property where true means it came from a file.

How to get an enum value from a string value in Java?

Yes, Blah.valueOf("A") will give you Blah.A.

Note that the name must be an exact match, including case: Blah.valueOf("a") and Blah.valueOf("A ") both throw an IllegalArgumentException.

The static methods valueOf() and values() are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType shows both methods.

jQuery $(document).ready and UpdatePanels?

FWIW, I experienced a similar issue w/mootools. Re-attaching my events was the correct move, but needed to be done at the end of the request..eg

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {... 

Just something to keep in mind if beginRequest causes you to get null reference JS exceptions.

Cheers

How to obtain the number of CPUs/cores in Linux from the command line?

cat /proc/cpuinfo | grep processor

This worked fine. When I tried the first answer I got 3 CPU's as the output. I know that I have 4 CPUs on the system so I just did a grep for processor and the output looked like this:

[root@theservername ~]# cat /proc/cpuinfo | grep processor
processor       : 0
processor       : 1
processor       : 2
processor       : 3

ES6 export all values from object

Every answer requires changing of the import statements.

If you want to be able to use:

import {a} from './my-module'           // a === 1
import * as myModule from './my-module' // myModule.a === 1

as in the question, and in your my-module you have everything that you need to export in one object (which can be useful e.g. if you want to validate the exported values with Joi or JSON Schema) then your my-module would have to be either:

let values = { a: 1, b: 2, c: 3 }
let {a, b, c} = values;
export {a, b, c};

Or:

let values = { a: 1, b: 2, c: 3 }
export let {a, b, c} = values;

Not pretty, but it compiles to what you need.

See: Babel example

How do I check if a file exists in Java?

File f = new File(filePathString); 

This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:

f.createNewFile();

So f.exists() can be used to check whether such a file exists or not.

Facebook login "given URL not allowed by application configuration"

Your settings must be incorrect.

Go to http://www.facebook.com/developers/ and edit the application you're working on.

On the "website" tab, look for "Site URL". This should be set to your website's URL "http://yoursite.com/"

Note that if you're using subdomains, you'll also need to update "Site Domain" to be "yoursite.com"

How to wait in a batch script?

You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use

ping -n 11 127.0.0.1 > nul

This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)

Resizing UITableView to fit content

I did in a bit different way, Actually my TableView was inside scrollview so i had to give height constraint as 0.

Then at runtime I made following changes,

       func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            self.viewWillLayoutSubviews()
       }
    
       override func viewWillLayoutSubviews() {
            super.updateViewConstraints()
             DispatchQueue.main.async {
               self.tableViewHeightConstraint?.constant = self.myTableView.contentSize.height
               self.view.layoutIfNeeded()
          }
       }

How do I create documentation with Pydoc?

Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':

yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'

yourcode_dir$ pydoc -w original
wrote original.html

Exception: Can't bind to 'ngFor' since it isn't a known native property

Use this

<div *ngFor="let talk of talks> 
   {{talk.title}} 
   {{talk.speaker}}
   <p>{{talk.description}} 
</div>

You need to specify variable to iterate over an array of an object

How do I line up 3 divs on the same row?

See my code

_x000D_
_x000D_
.float-left {_x000D_
    float:left;_x000D_
    width:300px; // or 33% for equal width independent of parent width_x000D_
}
_x000D_
<div>_x000D_
    <h2 align="center">San Andreas: Multiplayer</h2>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN ONE GOES HERE</div>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN TWO GOES HERE</div>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN THREE GOES HERE</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Error: Could not find or load main class in intelliJ IDE

I had this problem and I tried everything under the sun that I could think of and on this site.

None of my Java classes were being picked up after I pulled from a remote branch. All the classes had red Js by their names in the Project Hierarchy, not blue Cs.

In the end, I tried to follow this tutorial and a few steps in tried something not described and fixed the issue: https://www.jetbrains.com/help/idea/creating-and-managing-modules.html

Here's what I did:

  1. Goto File | Project Structure, or press Crtl+Shift+Alt+S
  2. Select Modules under the Project Settings section.
  3. In the Sources tab click Sources on the 'Mark as:' line.
  4. Click the Apply button.

For some reason, all my classes then had blue C's.

Someone with a better understanding of how IntelliJ and/or IDE's might be able to explain the phenomenon, but all I know is now it can see all the classes and more importantly the main one, and run.

CSS centred header image

you don't need to set the width of header in css, just put the background image as center using this code:

background: url("images/logo.png") no-repeat top center;

or you can just use img tag and put align="center" in the div

How can I set a dynamic model name in AngularJS?

http://jsfiddle.net/DrQ77/

You can simply put javascript expression in ng-model.

How to make a .NET Windows Service start right after the installation?

Visual Studio

If you are creating a setup project with VS, you can create a custom action who called a .NET method to start the service. But, it is not really recommended to use managed custom action in a MSI. See this page.

ServiceController controller  = new ServiceController();
controller.MachineName = "";//The machine where the service is installed;
controller.ServiceName = "";//The name of your service installed in Windows Services;
controller.Start();

InstallShield or Wise

If you are using InstallShield or Wise, these applications provide the option to start the service. Per example with Wise, you have to add a service control action. In this action, you specify if you want to start or stop the service.

Wix

Using Wix you need to add the following xml code under the component of your service. For more information about that, you can check this page.

<ServiceInstall 
    Id="ServiceInstaller"  
    Type="ownProcess"  
    Vital="yes"  
    Name=""  
    DisplayName=""  
    Description=""  
    Start="auto"  
    Account="LocalSystem"   
    ErrorControl="ignore"   
    Interactive="no">  
        <ServiceDependency Id="????"/> ///Add any dependancy to your service  
</ServiceInstall>

Creating a simple XML file using python

For the simplest choice, I'd go with minidom: http://docs.python.org/library/xml.dom.minidom.html . It is built in to the python standard library and is straightforward to use in simple cases.

Here's a pretty easy to follow tutorial: http://www.boddie.org.uk/python/XML_intro.html

jQuery select option elements by value

$("#h273yrjdfhgsfyiruwyiywer").children('[value="' + i + '"]').prop("selected", true);

How do you detect where two line segments intersect?

Based on @Gareth Rees answer, version for Python:

import numpy as np

def np_perp( a ) :
    b = np.empty_like(a)
    b[0] = a[1]
    b[1] = -a[0]
    return b

def np_cross_product(a, b):
    return np.dot(a, np_perp(b))

def np_seg_intersect(a, b, considerCollinearOverlapAsIntersect = False):
    # https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect/565282#565282
    # http://www.codeproject.com/Tips/862988/Find-the-intersection-point-of-two-line-segments
    r = a[1] - a[0]
    s = b[1] - b[0]
    v = b[0] - a[0]
    num = np_cross_product(v, r)
    denom = np_cross_product(r, s)
    # If r x s = 0 and (q - p) x r = 0, then the two lines are collinear.
    if np.isclose(denom, 0) and np.isclose(num, 0):
        # 1. If either  0 <= (q - p) * r <= r * r or 0 <= (p - q) * s <= * s
        # then the two lines are overlapping,
        if(considerCollinearOverlapAsIntersect):
            vDotR = np.dot(v, r)
            aDotS = np.dot(-v, s)
            if (0 <= vDotR  and vDotR <= np.dot(r,r)) or (0 <= aDotS  and aDotS <= np.dot(s,s)):
                return True
        # 2. If neither 0 <= (q - p) * r = r * r nor 0 <= (p - q) * s <= s * s
        # then the two lines are collinear but disjoint.
        # No need to implement this expression, as it follows from the expression above.
        return None
    if np.isclose(denom, 0) and not np.isclose(num, 0):
        # Parallel and non intersecting
        return None
    u = num / denom
    t = np_cross_product(v, s) / denom
    if u >= 0 and u <= 1 and t >= 0 and t <= 1:
        res = b[0] + (s*u)
        return res
    # Otherwise, the two line segments are not parallel but do not intersect.
    return None

T-SQL and the WHERE LIKE %Parameter% clause

The correct answer is, that, because the '%'-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName (be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'

or, in your example:

DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'

How to know if an object has an attribute in Python

Here's a very intuitive approach :

if 'property' in dir(a):
    a.property

Dictionary returning a default value if the key does not exist

No, nothing like that exists. The extension method is the way to go, and your name for it (GetValueOrDefault) is a pretty good choice.

Drawing a line/path on Google Maps

This can be done by using intents too:

  final Intent intent = new Intent(Intent.ACTION_VIEW,
    Uri.parse(
            "http://maps.google.com/maps?" +
            "saddr="+YOUR_START_LONGITUDE+","+YOUR_START_LATITUDE+"&daddr="YOUR_END_LONGITUDE+","+YOUR_END_LATITUDE));
         intent.setClassName(
          "com.google.android.apps.maps",
          "com.google.android.maps.MapsActivity");
   startActivity(intent);

Casting an int to a string in Python

Here answer for your code as whole:

key =10

files = ("ME%i.txt" % i for i in range(key))

#opening
files = [ open(filename, 'w') for filename in files]

# processing
for i, file in zip(range(key),files):
    file.write(str(i))
# closing
for openfile in files:
    openfile.close()

How to ping an IP address

I know this has been answered with previous entries, but for anyone else that comes to this question, I did find a way that did not require having use the "ping" process in windows and then scrubbing the output.

What I did was use JNA to invoke Window's IP helper library to do an ICMP echo

See my own answer to my own similar issue

Homebrew install specific version of formula?

Here is how I downgrade KOPS (which does not support versioning)

# brew has a git repo on your localhost
cd /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core

git remote -v
origin  https://github.com/Homebrew/homebrew-core (fetch)
origin  https://github.com/Homebrew/homebrew-core (push)

# find the version of kops.rb you need
git log Formula/kops.rb

# checkout old commit
# kops: update 1.18.1 bottle.
git checkout 2f0ede7f27dfc074d5b5493894f3468f27cc73f0 -- Formula/kops.rb

brew unlink kops
brew install kops

# now we have old version installed
ls -1 /usr/local/Cellar/kops/
1.18.1
1.18.2

which kops
/usr/local/bin/kops
ls -l /usr/local/bin/kops
/usr/local/bin/kops -> ../Cellar/kops/1.18.1/bin/kops
kops version
Version 1.18.1

# revert to the newest version
brew uninstall kops
git checkout -f
brew link kops
kops version
Version 1.18.2

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.

That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'? Absolutely!

String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"

Everything seems to work fine to me! indexOf can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.

It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!

String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;

It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):

In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).


Would this be the culprit to the funky characters?

Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.

That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.


Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence) overload.

System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU

The replaceAll solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.

How do I seed a random class to avoid getting duplicate random values

this workes for me:

private int GetaRandom()
    {
        Thread.Sleep(1);
        return new Random(DateTime.Now.Millisecond).Next();
    }

How to extract the hostname portion of a URL in JavaScript

Regex provides much more flexibility.

    //document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah
    //1.
     var r = new RegExp(/http:\/\/[^/]+/);
     var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com

    //2. 
     var r = new RegExp(/http:\/\/[^/]+\/[^/]+/);
     var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com/asdf

Angular ng-if not true

you are not using the $scope you must use $ctrl.area or $scope.area instead of area

java.lang.IllegalArgumentException: contains a path separator

I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!

 public class MyClass {    

 private String state;
 public File myFilename;

 @Override
 protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
    super.onCreate(savedInstanceState);
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
        if (!myFilename.exists()) {
            myFilename.mkdirs();
        }
    }
 }

 public void myMethod {

 File fileTo = new File(myFilename.toString() + "/myPic.png");  
 // use fileTo object to save your file in your new directory that was created in the onCreate method
 }
}

Condition within JOIN or WHERE

The relational algebra allows interchangeability of the predicates in the WHERE clause and the INNER JOIN, so even INNER JOIN queries with WHERE clauses can have the predicates rearrranged by the optimizer so that they may already be excluded during the JOIN process.

I recommend you write the queries in the most readable way possible.

Sometimes this includes making the INNER JOIN relatively "incomplete" and putting some of the criteria in the WHERE simply to make the lists of filtering criteria more easily maintainable.

For example, instead of:

SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
    AND c.State = 'NY'
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
    AND a.Status = 1

Write:

SELECT *
FROM Customers c
INNER JOIN CustomerAccounts ca
    ON ca.CustomerID = c.CustomerID
INNER JOIN Accounts a
    ON ca.AccountID = a.AccountID
WHERE c.State = 'NY'
    AND a.Status = 1

But it depends, of course.

Bootstrap: Open Another Modal in Modal

My code works well using data-dismiss.

<li class="step1">
    <a href="#" class="button-popup" data-dismiss="modal" data-toggle="modal" data-target="#lightbox1">
        <p class="text-label">Step 1</p>
        <p class="text-text">Plan your Regime</p>
    </a>

</li>
<li class="step2">
    <a href="#" class="button-popup" data-dismiss="modal" data-toggle="modal" data-target="#lightbox2">
        <p class="text-label">Step 2</p>
        <p class="text-text">Plan your menu</p>
    </a>
</li>
<li class="step3 active">
    <a href="#" class="button-popup" data-toggle="modal" data-dismiss="modal" data-target="#lightbox3">
        <p class="text-label">Step 3</p>
        <p class="text-text">This Step is Undone.</p>
    </a>
</li>

How do I show the changes which have been staged?

From version 1.7 and later it should be:

git diff --staged

Gradle failed to resolve library in Android Studio

For me follwing steps helped.

It seems to be bug of Android Studio 3.4/3.5 and it was "fixed" by disabling:

File ? Settings ? Experimental ? Gradle ? Only sync the active variant

day of the week to day number (Monday = 1, Tuesday = 2)

What about using idate()? idate()

$integer = idate('w', $timestamp);

Batch file include external file for variables

So you just have to do this right?:

@echo off
echo text shizzle
echo.
echo pause^>nul (press enter)
pause>nul

REM writing to file
(
echo XD
echo LOL
)>settings.cdb
cls

REM setting the variables out of the file
(
set /p input=
set /p input2=
)<settings.cdb
cls

REM echo'ing the variables
echo variables:
echo %input%
echo %input2%
pause>nul

if %input%==XD goto newecho
DEL settings.cdb
exit

:newecho
cls
echo If you can see this, good job!
DEL settings.cdb
pause>nul
exit

How to kill/stop a long SQL query immediately?

sp_who2 'active'

Check values under CPUTime and DiskIO. Note the SPID of process having large value comparatively.

kill {SPID value}

What is the canonical way to trim a string in Ruby without creating a new string?

There's no need to both strip and chomp as strip will also remove trailing carriage returns - unless you've changed the default record separator and that's what you're chomping.

Olly's answer already has the canonical way of doing this in Ruby, though if you find yourself doing this a lot you could always define a method for it:

def strip_or_self!(str)
  str.strip! || str
end

Giving:

@title = strip_or_self!(tokens[Title]) if tokens[Title]

Also keep in mind that the if statement will prevent @title from being assigned if the token is nil, which will result in it keeping its previous value. If you want or don't mind @title always being assigned you can move the check into the method and further reduce duplication:

def strip_or_self!(str)
  str.strip! || str if str
end

As an alternative, if you're feeling adventurous you can define a method on String itself:

class String
  def strip_or_self!
    strip! || self
  end
end

Giving one of:

@title = tokens[Title].strip_or_self! if tokens[Title]

@title = tokens[Title] && tokens[Title].strip_or_self!

Display A Popup Only Once Per User

The code to show only one time the popup (Bootstrap Modal in the case) :

modal.js

 $(document).ready(function() {
     if (Cookies('pop') == null) {
         $('#ModalIdName').modal('show');
         Cookies('pop', '365');
     }
 });

Here is the full code snipet for Rails :

Add the script above to your js repo (in Rails : app/javascript/packs)

In Rails we have a specific packing way for script, so :

  1. Download the js-cookie plugin (needed to work with Javascript Cokkies) https://github.com/js-cookie/js-cookie (the name should be : 'js.cookie.js')

    /*!
     * JavaScript Cookie v2.2.0
     * https://github.com/js-cookie/js-cookie
     *
     * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
     * Released under the MIT license
     */
    ;(function (factory) {
      var registeredInModuleLoader = false;
      if (typeof define === 'function' && define.amd) {
        define(factory);
        registeredInModul
     ...
    
  2. Add //= require js.cookie to application.js

It will works perfectly for 365 days!

WPF Data Binding and Validation Rules Best Practices

Also check this article. Supposedly Microsoft released their Enterprise Library (v4.0) from their patterns and practices where they cover the validation subject but god knows why they didn't included validation for WPF, so the blog post I'm directing you to, explains what the author did to adapt it. Hope this helps!

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh

Reactjs convert html string to jsx

There are now safer methods to accomplish this. The docs have been updated with these methods.

Other Methods

  1. Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

    <div>{'First · Second'}</div>

  2. Safer - Use the Unicode number for the entity inside a Javascript string.

    <div>{'First \u00b7 Second'}</div>

    or

    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. Or a mixed array with strings and JSX elements.

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

Docker container not starting (docker start)

You are trying to run bash, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d, but you can do this by adding -it to the command line, which ensures that the container has a valid tty associated with it and that stdin remains connected:

docker run -it -d -p 52022:22 basickarl/docker-git-test

You would more commonly run some sort of long-lived non-interactive process (like sshd, or a web server, or a database server, or a process manager like systemd or supervisor) when starting detached containers.

If you are trying to run a service like sshd, you cannot simply run service ssh start. This will -- depending on the distribution you're running inside your container -- do one of two things:

  • It will try to contact a process manager like systemd or upstart to start the service. Because there is no service manager running, this will fail.

  • It will actually start sshd, but it will be started in the background. This means that (a) the service sshd start command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.

If you want to run just ssh in a container, consider an example like this.

If you want to run sshd and other processes inside the container, you will need to investigate some sort of process supervisor.

How do I create an executable in Visual Studio 2013 w/ C++?

  1. Click BUILD > Configuration Manager...
  2. Under Project contexts > Configuration, select "Release"
  3. BUILD > Build Solution or Rebuild Solution

Add class to an element in Angular 4

Use [ngClass] and conditionally apply class based on the id.

In your HTML file:

<li>
    <img [ngClass]="{'this-is-a-class': id === 1 }" id="1"  
         src="../../assets/images/1.jpg" (click)="addClass(id=1)"/>
</li>
<li>
    <img [ngClass]="{'this-is-a-class': id === 2 }" id="2"  
         src="../../assets/images/2.png" (click)="addClass(id=2)"/>
</li>

In your TypeScript file:

addClass(id: any) {
    this.id = id;
}

How can I use Helvetica Neue Condensed Bold in CSS?

In case anyone is still looking for Helvetica Neue Condensed Bold, you essentially have two options.

  1. fonts.com: License the real font as a webfont from fonts.com. Free (with a badge), $10/month for 250k pageviews and $100/month for 2.5M pageviews. You can download the font to your desktop with the most expensive plan (but if you're on a Mac you already have it).
  2. myfonts.com / fontspring.com: Buy a pretty close alternative like Nimbus Sans Novus D from MyFont ($160 for unlimited pageviews), or Franklin Gothic FS Demi Condensed, from fontspring.com (about $21.95, flat one time fee with unlimited pageviews). In both cases you also get to download the font for your desktop so you can use it in Photoshop for comps.

A very cheap compromise is to buy Franklin from fontspring and then use "HelveticaNeue-CondensedBold" as the preferred font in your CSS.

h2 {"HelveticaNeue-CondensedBold", "FranklinGothicFSDemiCondensed", Arial, sans-serif;}

Then if a Mac user loads your site they see Helvetica Neue, but if they're on another platform they see Franklin.

UPDATE: I discovered a much closer match to Helvetica Neue Condensed Bold is Nimbus Sans Novus D Condensed bold. In fact, it is also derived from Helvetica. You can get it at MyFonts.com for $20 (desktop) and $20 (web, 10k pageviews). Web with unlimited pageviews is $160. I have used this font throughout (i.e. NOT exploiting the Mac's built in "NimbusSansNovusDBoldCondensed" at all) because it leads to a design that is more uniform across browsers. Built in HN and Nimbus Sans are very similar in all respects but point size. Nimbus needs a few extra points to get an identical size match.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

Below code can be used to Remove New Line and Table Space in text column

Select replace(replace(TEXT,char(10),''),char(13),'')

Anaconda site-packages

Linux users can find the locations of all the installed packages like this:

pip list | xargs -exec pip show

JQuery/Javascript: check if var exists

Before each of your conditional statements, you could do something like this:

var pagetype = pagetype || false;
if (pagetype === 'something') {
    //do stuff
}

Oracle: is there a tool to trace queries, like Profiler for sql server?

alter system set timed_statistics=true

--or

alter session set timed_statistics=true --if want to trace your own session

-- must be big enough:

select value from v$parameter p
where name='max_dump_file_size' 

-- Find out sid and serial# of session you interested in:

 select sid, serial# from v$session
 where ...your_search_params...

--you can begin tracing with 10046 event, the fourth parameter sets the trace level(12 is the biggest):

 begin
    sys.dbms_system.set_ev(sid, serial#, 10046, 12, '');
 end;

--turn off tracing with setting zero level:

begin
   sys.dbms_system.set_ev(sid, serial#, 10046, 0, '');
end;

/*possible levels: 0 - turned off 1 - minimal level. Much like set sql_trace=true 4 - bind variables values are added to trace file 8 - waits are added 12 - both bind variable values and wait events are added */

--same if you want to trace your own session with bigger level:

alter session set events '10046 trace name context forever, level 12';

--turn off:

alter session set events '10046 trace name context off';

--file with raw trace information will be located:

 select value from v$parameter p
 where name='user_dump_dest'

--name of the file(*.trc) will contain spid:

 select p.spid from v$session s, v$process p
 where s.paddr=p.addr
 and ...your_search_params...

--also you can set the name by yourself:

alter session set tracefile_identifier='UniqueString'; 

--finally, use TKPROF to make trace file more readable:

C:\ORACLE\admin\databaseSID\udump>
C:\ORACLE\admin\databaseSID\udump>tkprof my_trace_file.trc output=my_file.prf
TKPROF: Release 9.2.0.1.0 - Production on Wed Sep 22 18:05:00 2004
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
C:\ORACLE\admin\databaseSID\udump>

--to view state of trace file use:

set serveroutput on size 30000;
declare
  ALevel binary_integer;
begin
  SYS.DBMS_SYSTEM.Read_Ev(10046, ALevel);
  if ALevel = 0 then
    DBMS_OUTPUT.Put_Line('sql_trace is off');
  else
    DBMS_OUTPUT.Put_Line('sql_trace is on');
  end if;
end;
/

Just kind of translated http://www.sql.ru/faq/faq_topic.aspx?fid=389 Original is fuller, but anyway this is better than what others posted IMHO

How to extract string following a pattern with grep, regex or perl

If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.

Is there an equivalent of lsusb for OS X

In mac osx , you can use the following command:

system_profiler SPUSBDataType

How can I include all JavaScript files in a directory via JavaScript file?

@jellyfishtree it would be a better if you create one php file which includes all your js files from the directory and then only include this php file via a script tag. This has a better performance because the browser has to do less requests to the server. See this:

javascripts.php:

<?php
   //sets the content type to javascript 
   header('Content-type: text/javascript');

   // includes all js files of the directory
   foreach(glob("packages/*.js") as $file) {
      readfile($file);
   }
?>


index.php:

<script type="text/javascript" src="javascripts.php"></script>

That's it!
Have fun! :)

How to add default value for html <textarea>?

Please note that if you made changes to textarea, after it had rendered; You will get the updated value instead of the initialized value.

<!doctype html>
<html lang="en">
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
        <script>
            $(function () {
                $('#btnShow').click(function () {
                    alert('text:' + $('#addressFieldName').text() + '\n value:' + $('#addressFieldName').val());
                });
            });
            function updateAddress() {
                $('#addressFieldName').val('District: Peshawar \n');
            }
        </script>
    </head>
    <body>
        <?php
        $address = "School: GCMHSS NO.1\nTehsil: ,\nDistrict: Haripur";
        ?>
        <textarea id="addressFieldName" rows="4" cols="40" tabindex="5" ><?php echo $address; ?></textarea>
        <?php echo '<script type="text/javascript">updateAddress();</script>'; ?>
        <input type="button" id="btnShow" value='show' />
    </body>
</html>

As you can see the value of textarea will be different than the text in between the opening and closing tag of concern textarea.

duplicate 'row.names' are not allowed error

It seems the problem can arise from more than one reasons. Following two steps worked when I was having same error.

  1. I saved my file as MS-DOS csv. ( Earlier it was saved in as just csv , excel starter 2010 ). Opened the csv in notepad++. No coma was inconsistent (consistency as described above @Brian).
  2. Noticed I was not using argument sep="," . I used and it worked ( even though that is default argument!)

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

How I can print to stderr in C?

Do you know sprintf? It's basically the same thing with fprintf. The first argument is the destination (the file in the case of fprintf i.e. stderr), the second argument is the format string, and the rest are the arguments as usual.

I also recommend this printf (and family) reference.

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

In this version, month, day, and year determines which days to block on the calendar.

$(document).ready(function (){
  var d         = new Date();
  var natDays   = [[1,1,2009],[1,1,2010],[12,31,2010],[1,19,2009]];

  function nationalDays(date) {
    var m = date.getMonth();
    var d = date.getDate();
    var y = date.getFullYear();

    for (i = 0; i < natDays.length; i++) {
      if ((m == natDays[i][0] - 1) && (d == natDays[i][1]) && (y == natDays[i][2]))
      {
        return [false];
      }
    }
    return [true];
  }
  function noWeekendsOrHolidays(date) {
    var noWeekend = $.datepicker.noWeekends(date);
      if (noWeekend[0]) {
        return nationalDays(date);
      } else {
        return noWeekend;
    }
  }
  $(function() { 
    $(".datepicker").datepicker({

      minDate: new Date(d.getFullYear(), 1 - 1, 1),
      maxDate: new Date(d.getFullYear()+1, 11, 31),

      hideIfNoPrevNext: true,
      beforeShowDay: noWeekendsOrHolidays,
     });
  });
});

No provider for Http StaticInjectorError

In ionic 4.6 I use the following technique and it works. I am adding this answer so that if anybody is facing similar issues in newer ionic version app, it may help them.

i) Open app.module.ts and add the following code block to import HttpModule and HttpClientModule

import { HttpModule } from '@angular/http';
import {   HttpClientModule } from '@angular/common/http';

ii) In @NgModule import sections add below lines:

HttpModule,
HttpClientModule,

So, in my case @NgModule, looks like this:

@NgModule({
  declarations: [AppComponent ],
  entryComponents: [ ],
  imports: [
    BrowserModule,
    HttpModule,
    HttpClientModule,
    IonicModule.forRoot(),
    AppRoutingModule, 
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

That's it!

nodejs mongodb object id to string

I'm using mongojs, and i have this example:

db.users.findOne({'_id': db.ObjectId(user_id)  }, function(err, user) {
   if(err == null && user != null){
      user._id.toHexString(); // I convert the objectId Using toHexString function.
   }
})

I hope this help.

How to Execute stored procedure from SQL Plus?

You forgot to put z as an bind variable.

The following EXECUTE command runs a PL/SQL statement that references a stored procedure:

SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')

Note that the value returned by the stored procedure is being return into :Z

What does it mean when an HTTP request returns status code 0?

In case anyone else comes across this problem, this was giving me issues due to the AJAX request and a normal form request being sent. I solved it with the following line:

<form onsubmit="submitfunc(); return false;">

The key there is the return false, which causes the form not to send. You could also just return false from inside of submitfunc(), but I find explicitly writing it to be clearer.

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

Get first letter of a string from column

.str.get

This is the simplest to specify string methods

# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df

        A    B
0     xyz  123
1     abc  456
2  foobar  789

df.dtypes

A    object
B     int64
dtype: object

For string (read:object) type columns, use

df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)

.str handles NaNs by returning NaN as the output.

For non-numeric columns, an .astype conversion is required beforehand, as shown in @Ed Chum's answer.

# Note that this won't work well if the data has NaNs. 
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

List Comprehension and Indexing

There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.

# For string columns
df['C'] = [x[0] for x in df['A']]

# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

If your data has NaNs, then you will need to handle this appropriately with an if/else in the list comprehension,

df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2

        A      B
0     xyz  123.0
1     NaN  456.0
2  foobar    NaN

# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]

# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]

        A      B    C    D
0     xyz  123.0    x    1
1     NaN  456.0  NaN    4
2  foobar    NaN    f  NaN

Let's do some timeit tests on some larger data.

df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True) 

%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])

%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])

12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

List comprehensions are 4x faster.

How do I control how Emacs makes backup files?

Emacs backup/auto-save files can be very helpful. But these features are confusing.

Backup files

Backup files have tildes (~ or ~9~) at the end and shall be written to the user home directory. When make-backup-files is non-nil Emacs automatically creates a backup of the original file the first time the file is saved from a buffer. If you're editing a new file Emacs will create a backup the second time you save the file.

No matter how many times you save the file the backup remains unchanged. If you kill the buffer and then visit the file again, or the next time you start a new Emacs session, a new backup file will be made. The new backup reflects the file's content after reopened, or at the start of editing sessions. But an existing backup is never touched again. Therefore I find it useful to created numbered backups (see the configuration below).

To create backups explicitly use save-buffer (C-x C-s) with prefix arguments.

diff-backup and dired-diff-backup compares a file with its backup or vice versa. But there is no function to restore backup files. For example, under Windows, to restore a backup file

C:\Users\USERNAME\.emacs.d\backups\!drive_c!Users!USERNAME!.emacs.el.~7~

it has to be manually copied as

C:\Users\USERNAME\.emacs.el

Auto-save files

Auto-save files use hashmarks (#) and shall be written locally within the project directory (along with the actual files). The reason is that auto-save files are just temporary files that Emacs creates until a file is saved again (like with hurrying obedience).

  • Before the user presses C-x C-s (save-buffer) to save a file Emacs auto-saves files - based on counting keystrokes (auto-save-interval) or when you stop typing (auto-save-timeout).
  • Emacs also auto-saves whenever it crashes, including killing the Emacs job with a shell command.

When the user saves the file, the auto-saved version is deleted. But when the user exits the file without saving it, Emacs or the X session crashes, the auto-saved files still exist.

Use revert-buffer or recover-file to restore auto-save files. Note that Emacs records interrupted sessions for later recovery in files named ~/.emacs.d/auto-save-list. The recover-session function will use this information.

The preferred method to recover from an auto-saved filed is M-x revert-buffer RET. Emacs will ask either "Buffer has been auto-saved recently. Revert from auto-save file?" or "Revert buffer from file FILENAME?". In case of the latter there is no auto-save file. For example, because you have saved before typing another auto-save-intervall keystrokes, in which case Emacs had deleted the auto-save file.

Auto-save is nowadays disabled by default because it can slow down editing when connected to a slow machine, and because many files contain sensitive data.

Configuration

Here is a configuration that IMHO works best:

(defvar --backup-directory (concat user-emacs-directory "backups"))
(if (not (file-exists-p --backup-directory))
        (make-directory --backup-directory t))
(setq backup-directory-alist `(("." . ,--backup-directory)))
(setq make-backup-files t               ; backup of a file the first time it is saved.
      backup-by-copying t               ; don't clobber symlinks
      version-control t                 ; version numbers for backup files
      delete-old-versions t             ; delete excess backup files silently
      delete-by-moving-to-trash t
      kept-old-versions 6               ; oldest versions to keep when a new numbered backup is made (default: 2)
      kept-new-versions 9               ; newest versions to keep when a new numbered backup is made (default: 2)
      auto-save-default t               ; auto-save every buffer that visits a file
      auto-save-timeout 20              ; number of seconds idle time before auto-save (default: 30)
      auto-save-interval 200            ; number of keystrokes between auto-saves (default: 300)
      )

Sensitive data

Another problem is that you don't want to have Emacs spread copies of files with sensitive data. Use this mode on a per-file basis. As this is a minor mode, for my purposes I renamed it sensitive-minor-mode.

To enable it for all .vcf and .gpg files, in your .emacs use something like:

(setq auto-mode-alist
      (append
       (list
        '("\\.\\(vcf\\|gpg\\)$" . sensitive-minor-mode)
        )
       auto-mode-alist))

Alternatively, to protect only some files, like some .txt files, use a line like

// -*-mode:asciidoc; mode:sensitive-minor; fill-column:132-*-

in the file.

Add a dependency in Maven

Actually, on investigating this, I think all these answers are incorrect. Your question is misleading because of our level of understanding of maven. And I say our because I'm just getting introduced to maven.

In Eclipse, when you want to add a jar file to your project, normally you download the jar manually and then drop it into the lib directory. With maven, you don't do it this way. Here's what you do:

  • Go to mvnrepository
  • Search for the library you want to add
  • Copy the dependency statement into your pom.xml
  • rebuild via mvn

Now, maven will connect and download the jar along with the list of dependencies, and automatically resolve any additional dependencies that jar may have had. So if the jar also needed commons-logging, that will be downloaded as well.

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

How to Disable GUI Button in Java

Once you've created the frame the part of the code with your conditional isn't going to get entered. To put it another way, at the time you execute the test if (btn1Clicked == true) , the button has not only not been clicked yet, it hasn't even been displayed to the user.

Lose the booleans and move the line with the btnConvertDocuments.setEnabled(false) into your actionListener. Make the buttons instance variables, do not make them static variables. (Alternatively you could keep the buttons as local variables and assign each of them their own anonymous inner class listener.)

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

"psql: could not connect to server: Connection refused" Error when connecting to remote database

Following configuration, you need to set:

To open the port 5432 edit your /etc/postgresql/9.1/main/postgresql.conf and change

# Connection Settings -

listen_addresses = '*'          # what IP address(es) to listen on;

In /etc/postgresql/10/main/pg_hba.conf

# IPv4 local connections:
host    all             all             0.0.0.0/0           md5

Now restart your DBMS

sudo service postgresql restart

Now you can connect with

psql -h hostname(IP) -p port -U username -d database

Where is the default log location for SharePoint/MOSS?

For Sharepoint 2007

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS

Vagrant error : Failed to mount folders in Linux guest

I found this issue addressed here vagrant issues. Two ways to do it:

  1. Run this on guest (i.e. after you ssh into vbox via vagrant ssh )

    sudo ln -s /opt/VBoxGuestAdditions-4.3.10/lib/VBoxGuestAdditions /usr/lib/VBoxGuestAdditions
    

    Then run vagrant reload to correctly mount the folders.

  2. As @klang pointed out, update the VBoxGuestAdditions.iso file on your mac:

    wget https://www.virtualbox.org/download/testcase/VBoxGuestAdditions_4.3.11-93070.iso??
    sudo cp VBoxGuestAdditions_4.3.11-93070.iso /Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso
    

UPDATE (16may2014)

Since the iso is no longer available, you can use the 4.3.12 one (http://dlc.sun.com.edgesuite.net/virtualbox/4.3.12/VBoxGuestAdditions_4.3.12.iso)

note : the binary vbox4.3.12 for os X is not available at this time

Responsive background image in div full width

Here is one way of getting the design that you want.

Start with the following HTML:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
                 <h1>This is centered text.</h1>
            </div>
            <div class="main">main area</div>
        </div>
    </div>
</div>

Note that the background image is now part of the regular flow of the document.

Apply the following CSS:

.bg-image {
    position: relative;
}
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
}
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
}
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;
}

How This Works

The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block and margin: 0 auto.

The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1 element to be the full width of the parent and use text-align: center to center the text. Use the top or bottom offsets to place the text where it is needed.

If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.

See demo at: http://jsfiddle.net/audetwebdesign/EGgaN/

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        TaskStart.ToString("dd-MMMM-yyyy");
        rpt.SetParameterValue("TaskStartDate", TaskStart);
    }
}

You always accessed your first row in your dataset.

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

How do I get total physical memory size using PowerShell without WMI?

Id like to say that instead of going with the systeminfo this would help over to get the total physical memory in GB's the machine

Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {"{0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}

you can pass this value to the variable and get the gross output for the total physical memory in the machine

   $totalmemory = Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {"{0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}
   $totalmemory

Are (non-void) self-closing tags valid in HTML5?

However -just for the record- this is invalid:

<address class="vcard">
  <svg viewBox="0 0 800 400">
    <rect width="800" height="400" fill="#000">
  </svg>
</address>

And a slash here would make it valid again:

    <rect width="800" height="400" fill="#000"/>

Failed to resolve: com.android.support:appcompat-v7:26.0.0

  1. Add this in build.gradle(Project:projectname)

    allprojects {
      repositories {
        jcenter()
        maven { url "https://maven.google.com" }
      }
    }
    
  2. Add this in build.gradle(Module:app)

    dependencies {
      compile 'com.android.support:appcompat-v7:26.1.0'
    }
    

Remove NaN from pandas series

If you have a pandas serie with NaN, and want to remove it (without loosing index):

serie = serie.dropna()

# create data for example
data = np.array(['g', 'e', 'e', 'k', 's']) 
ser = pd.Series(data)
ser.replace('e', np.NAN)
print(ser)

0      g
1    NaN
2    NaN
3      k
4      s
dtype: object

# the code
ser = ser.dropna()
print(ser)

0    g
3    k
4    s
dtype: object

Import one schema into another new schema - Oracle

The issue was with the dmp file itself. I had to re-export the file and the command works fine. Thank you @Justin Cave

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

This code will do what you're looking for. It's based on examples found here and here.

The autofmt_xdate() call is particularly useful for making the x-axis labels readable.

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)

fig.autofmt_xdate()

plt.savefig("figure.pdf")

enter image description here

System.Collections.Generic.List does not contain a definition for 'Select'

This question's bit old, but, there's a tricky scenario which also leads to this error:

In controller:

ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());

The above code will lead to an error in this part: .Select(a=>a.ToString()) because of the below reason: You're passing a ViewBag.id to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:

GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)

So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.

Is it possible to have a default parameter for a mysql stored procedure?

No, this is not supported in MySQL stored routine syntax.

Feel free to submit a feature request at bugs.mysql.com.

Interface defining a constructor signature?

You could do this with generics trick, but it still is vulnerable to what Jon Skeet wrote:

public interface IHasDefaultConstructor<T> where T : IHasDefaultConstructor<T>, new()
{
}

Class that implements this interface must have parameterless constructor:

public class A : IHasDefaultConstructor<A> //Notice A as generic parameter
{
    public A(int a) { } //compile time error
}

String length in bytes in JavaScript

In NodeJS, Buffer.byteLength is a method specifically for this purpose:

let strLengthInBytes = Buffer.byteLength(str); // str is UTF-8

Note that by default the method assumes the string is in UTF-8 encoding. If a different encoding is required, pass it as the second argument.

Encapsulation vs Abstraction?

in a simple sentence, I cay say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change. You might consider abstraction is same as encapsulation. But encapsulation means the act of enclosing one or more items within a container, not hiding details. If you make the argument that "everything that was encapsulated was also hidden." This is obviously not true. For example, even though information may be encapsulated within record structures and arrays, this information is usually not hidden (unless hidden via some other mechanism).

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

adding onclick event to dynamically added button?

I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:

//Bad code.
var btn = document.createElement('button');
btn.onClick = function() {  console.log("hey");  }

to this:

//Working Code.  I don't like it, but it works. 
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);

document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){  console.log("hey");  }

I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.

Where is `%p` useful with printf?

The size of the pointer may be something different than that of int. Also an implementation could produce better than simple hex value representation of the address when you use %p.

Make Div overlay ENTIRE page (not just viewport)?

The viewport is all that matters, but you likely want the entire website to stay darkened even while scrolling. For this, you want to use position:fixed instead of position:absolute. Fixed will keep the element static on the screen as you scroll, giving the impression that the entire body is darkened.

Example: http://jsbin.com/okabo3/edit

div.fadeMe {
  opacity:    0.5; 
  background: #000; 
  width:      100%;
  height:     100%; 
  z-index:    10;
  top:        0; 
  left:       0; 
  position:   fixed; 
}
<body>
  <div class="fadeMe"></div>
  <p>A bunch of content here...</p>
</body>

MySQL VARCHAR size?

VARCHAR means that it's a variable-length character, so it's only going to take as much space as is necessary. But if you knew something about the underlying structure, it may make sense to restrict VARCHAR to some maximum amount.

For instance, if you were storing comments from the user, you may limit the comment field to only 4000 characters; if so, it doesn't really make any sense to make the sql table have a field that's larger than VARCHAR(4000).

http://dev.mysql.com/doc/refman/5.0/en/char.html

ssh remote host identification has changed

updated your ssh key, getting the above message is normal.

Just edit ~/.ssh/known_hosts and delete line 4, as the message pointed you

Offending RSA key in /Users/isaacalves/.ssh/known_hosts:4

or use ssh-keygen to delete the invalid key

ssh-keygen -R "you server hostname or ip"

Why would one mark local variables and method parameters as "final" in Java?

Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.

Finalizing local var's seems somewhat overkill IMO.

Open Jquery modal dialog on click event

$(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();

    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").hide();
                }
            });
    }); //close click
});

Better to use .hide() instead of .remove(). With .remove() it returns undefined if you have pressed the link once, then close the modal and if you press the modal link again, it returns undefined with .remove.

With .hide() it doesnt and it works like a breeze. Ty for the snippet in the first hand!

Return Index of an Element in an Array Excel VBA

Is this what you are looking for?

public function GetIndex(byref iaList() as integer, byval iInteger as integer) as integer

dim i as integer

 for i=lbound(ialist) to ubound(ialist)
  if iInteger=ialist(i) then
   GetIndex=i
   exit for
  end if
 next i

end function

git still shows files as modified after adding to .gitignore

The solutions offered here and in other places didn't work for me, so I'll add to the discussion for future readers. I admittedly don't fully understand the procedure yet, but have finally solved my (similar) problem and want to share.

I had accidentally cached some doc-directories with several hundred files when working with git in IntelliJ IDEA on Windows 10, and after adding them to .gitignore (and PROBABLY moving them around a bit) I couldn't get them removed from the Default Changelist.

I first commited the actual changes I had made, then went about solving this - took me far too long. I tried git rm -r --cached . but would always get path-spec ERRORS, with different variations of the path-spec as well as with the -f and -r flags.

git status would still show the filenames, so I tried using some of those verbatim with git rm -cached, but no luck. Stashing and unstashing the changes seemed to work, but they got queued again after a time (I'm a bity hazy on the exact timeframe). I have finally removed these entries for good using

git reset

I assume this is only a GOOD IDEA when you have no changes staged/cached that you actually want to commit.

What is the difference between a cer, pvk, and pfx file?

I actually came across something like this not too long ago... check it out over on msdn (see the first answer)

in summary:

.cer - certificate stored in the X.509 standard format. This certificate contains information about the certificate's owner... along with public and private keys.

.pvk - files are used to store private keys for code signing. You can also create a certificate based on .pvk private key file.

.pfx - stands for personal exchange format. It is used to exchange public and private objects in a single file. A pfx file can be created from .cer file. Can also be used to create a Software Publisher Certificate.

I summarized the info from the page based on the suggestion from the comments.

Turn a number into star rating display using jQuery and CSS

using jquery without prototype, update the js code to

$( ".stars" ).each(function() { 
    // Get the value
    var val = $(this).data("rating");
    // Make sure that the value is in 0 - 5 range, multiply to get width
    var size = Math.max(0, (Math.min(5, val))) * 16;
    // Create stars holder
    var $span = $('<span />').width(size);
    // Replace the numerical value with stars
    $(this).html($span);
});

I also added a data attribute by the name of data-rating in the span.

<span class="stars" data-rating="4" ></span>

How to open a txt file and read numbers in Java

   try{

    BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }finally{
     in.close();
    }

This will read line by line,

If your no. are saperated by newline char. then in place of

 System.out.println (strLine);

You can have

try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}  

If it is separated by spaces then

try{
    String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
    }catch(NumberFormatException npe){
    //do something
    }  

Only get hash value using md5sum (without filename)

Another way:

md5=$(md5sum ${my_iso_file} | sed '/ .*//' )

Error handling with PHPMailer

We wrote a wrapper class that captures the buffer and converts the printed output to an exception. this lets us upgrade the phpmailer file without having to remember to comment out the echo statements each time we upgrade.

The wrapper class has methods something along the lines of:

public function AddAddress($email, $name = null) {
    ob_start();
    parent::AddAddress($email, $name);
    $error = ob_get_contents();
    ob_end_clean();
    if( !empty($error) ) {
        throw new Exception($error);
    }
}

copying all contents of folder to another folder using batch file?

FYI...if you use TortoiseSVN and you want to create a simple batch file to xcopy (or directory mirror) entire repositories into a "safe" location on a periodic basis, then this is the specific code that you might want to use. It copies over the hidden directories/files, maintains read-only attributes, and all subdirectories and best of all, doesn't prompt for input. Just make sure that you assign folder1 (safe repo) and folder2 (usable repo) correctly.

@echo off
echo "Setting variables..."
set folder1="Z:\Path\To\Backup\Repo\Directory"
set folder2="\\Path\To\Usable\Repo\Directory"
echo "Removing sandbox version..."
IF EXIST %folder1% (
    rmdir %folder1% /s /q
)
echo "Copying official repository into backup location..."
xcopy /e /i /v /h /k %folder2% %folder1%

And, that's it folks!

Add to your scheduled tasks and never look back.

How to get files in a relative path in C#

Write it like this:

string[] files = Directory.GetFiles(@".\Archive", "*.zip");

. is for relative to the folder where you started your exe, and @ to allow \ in the name.

When using filters, you pass it as a second parameter. You can also add a third parameter to specify if you want to search recursively for the pattern.

In order to get the folder where your .exe actually resides, use:

var executingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

ArrayList of int array in java

You have to use <Integer> instead of <int>:

int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
    arl.add(i);        
    System.out.println("Arraylist contains:" + arl.get(0));
}

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

VB.NET VERSION

Okay, so I have just spent several hours looking for a viable method for posting multiple parameters to an MVC 4 WEB API, but most of what I found was either for a 'GET' action or just flat out did not work. However, I finally got this working and I thought I'd share my solution.

  1. Use NuGet packages to download JSON-js json2 and Json.NET. Steps to install NuGet packages:

    (1) In Visual Studio, go to Website > Manage NuGet Packages... enter image description here

    (2) Type json (or something to that effect) into the search bar and find JSON-js json2 and Json.NET. Double-clicking them will install the packages into the current project.enter image description here

    (3) NuGet will automatically place the json file in ~/Scripts/json2.min.js in your project directory. Find the json2.min.js file and drag/drop it into the head of your website. Note: for instructions on installing .js (javascript) files, read this solution.

  2. Create a class object containing the desired parameters. You will use this to access the parameters in the API controller. Example code:

    Public Class PostMessageObj
    
    Private _body As String
    Public Property body As String
        Get
            Return _body
        End Get
        Set(value As String)
            _body = value
        End Set
    End Property
    
    
    Private _id As String
    Public Property id As String
        Get
            Return _id
        End Get
        Set(value As String)
            _id = value
        End Set
    End Property
    End Class
    
  3. Then we setup the actual MVC 4 Web API controller that we will be using for the POST action. In it, we will use Json.NET to deserialize the string object when it is posted. Remember to use the appropriate namespaces. Continuing with the previous example, here is my code:

    Public Sub PostMessage(<FromBody()> ByVal newmessage As String)
    
    Dim t As PostMessageObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of PostMessageObj)(newmessage)
    
    Dim body As String = t.body
    Dim i As String = t.id
    
    End Sub
    
  4. Now that we have our API controller set up to receive our stringified JSON object, we can call the POST action freely from the client-side using $.ajax; Continuing with the previous example, here is my code (replace localhost+rootpath appropriately):

    var url = 'http://<localhost+rootpath>/api/Offers/PostMessage';
    var dataType = 'json'
    var data = 'nothn'
    var tempdata = { body: 'this is a new message...Ip sum lorem.',
        id: '1234'
    }
    var jsondata = JSON.stringify(tempdata)
    $.ajax({
        type: "POST",
        url: url,
        data: { '': jsondata},
        success: success(data),
        dataType: 'text'
    });
    

As you can see we are basically building the JSON object, converting it into a string, passing it as a single parameter, and then rebuilding it via the JSON.NET framework. I did not include a return value in our API controller so I just placed an arbitrary string value in the success() function.


Author's notes

This was done in Visual Studio 2010 using ASP.NET 4.0, WebForms, VB.NET, and MVC 4 Web API Controller. For anyone having trouble integrating MVC 4 Web API with VS2010, you can download the patch to make it possible. You can download it from Microsoft's Download Center.

Here are some additional references which helped (mostly in C#):

Setting up and using environment variables in IntelliJ Idea

Path Variables dialog has nothing to do with the environment variables.

Environment variables can be specified in your OS or customized in the Run configuration:

env

"Can't find Project or Library" for standard VBA functions

In my case, it was that the function was AMBIGUOUS as it was defined in the VBA library (present in my references), and also in the Microsoft Office Object Library (also present). I removed the Microsoft Office Object Library, and voila! No need to use the VBA. prefix.

set font size in jquery

$("#"+styleTarget).css('font-size', newFontSize);

How to deal with certificates using Selenium?

Whenever I run into this issue with newer browsers, I just use AppRobotic Personal edition to click specific screen coordinates, or tab through the buttons and click.

Basically it's just using its macro functionality, but won't work on headless setups though.

Search all tables, all columns for a specific value SQL Server

The below Query works but very slow... copied from vyaskn.tripod.com

Declare @SearchStr nvarchar(100)

SET  @SearchStr='Search String' BEGIN

CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128),
 @SearchStr2 nvarchar(110)  SET  @TableName = ''    SET @SearchStr2 =
 QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL    
BEGIN       
  SET @ColumnName = ''      
  SET @TableName =  (
    SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' +
    QUOTENAME(TABLE_NAME)) FROM INFORMATION_SCHEMA.TABLES 
    WHERE
    TABLE_TYPE = 'BASE TABLE'
    AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
    AND OBJECTPROPERTY(
      OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)),
        'IsMSShipped') = 0)

  WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)      
  BEGIN
    SET @ColumnName = (
      SELECT MIN(QUOTENAME(COLUMN_NAME))
      FROM INFORMATION_SCHEMA.COLUMNS
      WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
        AND TABLE_NAME = PARSENAME(@TableName, 1)
      AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
      AND QUOTENAME(COLUMN_NAME) > @ColumnName)
      IF @ColumnName IS NOT NULL            
      BEGIN
      INSERT INTO #Results
      EXEC
      (
        'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + 
          ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
        ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
      )             
      END       
    END     
  END

  SELECT ColumnName, ColumnValue FROM #Results END

How to get row number from selected rows in Oracle

The below query helps to get the row number in oracle,

SELECT ROWNUM AS SNO,ID,NAME,EMAIL,BRANCH FROM student WHERE NAME LIKE '%ram%';

Why can't a text column have a default value in MySQL?

For Ubuntu 16.04:

How to disable strict mode in MySQL 5.7:

Edit file /etc/mysql/mysql.conf.d/mysqld.cnf

If below line exists in mysql.cnf

sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Then Replace it with

sql_mode='MYSQL40'

Otherwise

Just add below line in mysqld.cnf

sql_mode='MYSQL40'

This resolved problem.

Set background image according to screen resolution

Delete your "body background image code" then paste this code:

html { 
    background: url(../img/background.jpg) no-repeat center center fixed #000; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Add another class to a div

You can append a class to the className member, with a leading space.

document.getElementById('hello').className += ' new-class';

See https://developer.mozilla.org/En/DOM/Element.className

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

They are not really same mutexes, lock_guard<muType> has nearly the same as std::mutex, with a difference that it's lifetime ends at the end of the scope (D-tor called) so a clear definition about these two mutexes :

lock_guard<muType> has a mechanism for owning a mutex for the duration of a scoped block.

And

unique_lock<muType> is a wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

Here is an example implemetation :

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <chrono>

using namespace std::chrono;

class Product{

   public:

       Product(int data):mdata(data){
       }

       virtual~Product(){
       }

       bool isReady(){
       return flag;
       }

       void showData(){

        std::cout<<mdata<<std::endl;
       }

       void read(){

         std::this_thread::sleep_for(milliseconds(2000));

         std::lock_guard<std::mutex> guard(mmutex);

         flag = true;

         std::cout<<"Data is ready"<<std::endl;

         cvar.notify_one();

       }

       void task(){

       std::unique_lock<std::mutex> lock(mmutex);

       cvar.wait(lock, [&, this]() mutable throw() -> bool{ return this->isReady(); });

       mdata+=1;

       }

   protected:

    std::condition_variable cvar;
    std::mutex mmutex;
    int mdata;
    bool flag = false;

};

int main(){

     int a = 0;
     Product product(a);

     std::thread reading(product.read, &product);
     std::thread setting(product.task, &product);

     reading.join();
     setting.join();


     product.showData();
    return 0;
}

In this example, i used the unique_lock<muType> with condition variable

Why does NULL = NULL evaluate to false in SQL server

To quote the Christmas analogy again:

In SQL, NULL basically means "closed box" (unknown). So, the result of comparing two closed boxes will also be unknown (null).

I understand, for a developer, this is counter-intuitive, because in programming languages, often NULL rather means "empty box" (known). And comparing two empty boxes will naturally yield true / equal.

This is why JavaScript for example distinguishes between null and undefined.

How to hide soft keyboard on android after clicking outside EditText?

I managed to hide the keyboard from inside onItemClick AutoCompleteTextView

public void onItemClick(AdapterView<?> adapterViewIn, View viewIn, int indexSelected, long arg3) {
     InputMethodManager imm = (InputMethodManager) getSystemService(viewIn.getContext().INPUT_METHOD_SERVICE);
     imm.hideSoftInputFromWindow(viewIn.getApplicationWindowToken(), 0);
     // your code HERE
}

Ignore invalid self-signed ssl certificate in node.js with https.request?

Add the following environment variable:

NODE_TLS_REJECT_UNAUTHORIZED=0

e.g. with export:

export NODE_TLS_REJECT_UNAUTHORIZED=0

(with great thanks to Juanra)

Best way to check for "empty or null value"

If database having large number of records then null check can take more time you can use null check in different ways like : 1) where columnname is null 2) where not exists() 3) WHERE (case when columnname is null then true end)

How to initialize a list of strings (List<string>) with many string values

One really cool feature is that list initializer works just fine with custom classes too: you have just to implement the IEnumerable interface and have a method called Add.

So for example if you have a custom class like this:

class MyCustomCollection : System.Collections.IEnumerable
{
    List<string> _items = new List<string>();

    public void Add(string item)
    {
        _items.Add(item);
    }

    public IEnumerator GetEnumerator()
    {
        return _items.GetEnumerator();
    }
}

this will work:

var myTestCollection = new MyCustomCollection()
{
    "item1",
    "item2"
}

How can I combine multiple nested Substitute functions in Excel?

To simply combine them you can place them all together like this:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,"_AB","_"),"_CD","_"),"_EF","_"),"_40K",""),"_60K",""),"_S_","_"),"_","-")

(note that this may pass the older Excel limit of 7 nested statements. I'm testing in Excel 2010


Another way to do it is by utilizing Left and Right functions.

This assumes that the changing data on the end is always present and is 8 characters long

=SUBSTITUTE(LEFT(A2,LEN(A2)-8),"_","-")

This will achieve the same resulting string


If the string doesn't always end with 8 characters that you want to strip off you can search for the "_S" and get the current location. Try this:

=SUBSTITUTE(LEFT(A2,FIND("_S",A2,1)),"_","-")

Finding local maxima/minima with Numpy in a 1D numpy array

import numpy as np
x=np.array([6,3,5,2,1,4,9,7,8])
y=np.array([2,1,3,5,3,9,8,10,7])
sortId=np.argsort(x)
x=x[sortId]
y=y[sortId]
minm = np.array([])
maxm = np.array([])
i = 0
while i < length-1:
    if i < length - 1:
        while i < length-1 and y[i+1] >= y[i]:
            i+=1

        if i != 0 and i < length-1:
            maxm = np.append(maxm,i)

        i+=1

    if i < length - 1:
        while i < length-1 and y[i+1] <= y[i]:
            i+=1

        if i < length-1:
            minm = np.append(minm,i)
        i+=1


print minm
print maxm

minm and maxm contain indices of minima and maxima, respectively. For a huge data set, it will give lots of maximas/minimas so in that case smooth the curve first and then apply this algorithm.

How to get a value from a Pandas DataFrame and not the index and object type

Nobody mentioned it, but you can also simply use loc with the index and column labels.

df.loc[2, 'Letters']
# 'C'

Or, if you prefer to use "Numbers" column as reference, you can also set is as an index.

df.set_index('Numbers').loc[3, 'Letters']

How do I navigate to a parent route from a child route?

constructor(private router: Router) {}

navigateOnParent() {
  this.router.navigate(['../some-path-on-parent']);
}

The router supports

  • absolute paths /xxx - started on the router of the root component
  • relative paths xxx - started on the router of the current component
  • relative paths ../xxx - started on the parent router of the current component

Eclipse HotKey: how to switch between tabs?

Switch like Windows in OS (go to window which last had focus)

CTRL-F6 in Eclipse, like ALT-TAB (on windows), brings up a list of tabs/windows available (if you keep the CTRL / ALT key depressed) and highlights the one you will jump to when you let go of this key. You do not have to select the window. If you want to traverse several tabs at once hold down the CTRL button and tap the TAB button. This is identical behaviour to ALT-TAB on Windows.

In this sense, CTRL-SHIFT-F6 in eclipse is the ALT-SHIFT-TAB analog. Personally, I change these bindings in Eclipse to be like Visual Studio. I.e. CTRL-TAB and CTRL-SHIFT-TAB and I do it like this:

Window>Preferences>General>Keys

Then set "Next Editor"=Ctrl+Tab and "Previous Editor"=Ctrl+Shift+Tab. Don't forget to click "Unbind Command" before setting the new binding.

Switch like browser (go to tab on the right of current tab)

This is CTRL-PageDown to go right, CTRL-PageUp to go left. Frustratingly, when you get to the end of the list of tabs (say far right hand tab) and then try to go right again Eclipse does not cycle round to the first tab (far left) like most browsers would.

How to run wget inside Ubuntu Docker image?

You need to install it first. Create a new Dockerfile, and install wget in it:

FROM ubuntu:14.04
RUN  apt-get update \
  && apt-get install -y wget \
  && rm -rf /var/lib/apt/lists/*

Then, build that image:

docker build -t my-ubuntu .

Finally, run it:

docker run my-ubuntu wget https://downloads-packages.s3.amazonaws.com/ubuntu-14.04/gitlab_7.8.2-omnibus.1-1_amd64.deb

How do I join two lines in vi?

Press Shift + 4 ("$") on the first line, then Shift + j ("J").

And if you want help, go into vi, and then press F1.

MySQL order by before group by

No. It makes no sense to order the records before grouping, since grouping is going to mutate the result set. The subquery way is the preferred way. If this is going too slow you would have to change your table design, for example by storing the id of of the last post for each author in a seperate table, or introduce a boolean column indicating for each author which of his post is the last one.

Save multiple sheets to .pdf

I recommend adding the following line after the export to PDF:

ThisWorkbook.Sheets("Sheet1").Select

(where eg. Sheet1 is the single sheet you want to be active afterwards)

Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)

What happened to Lodash _.pluck?

There isn't a need for _.map or _.pluck since ES6 has taken off.

Here's an alternative using ES6 JavaScript:

clips.map(clip => clip.id)

In log4j, does checking isDebugEnabled before logging improve performance?

Option 2 is better.

Per se it does not improve performance. But it ensures performance does not degrade. Here's how.

Normally we expect logger.debug(someString);

But usually, as the application grows, changes many hands, esp novice developers, you could see

logger.debug(str1 + str2 + str3 + str4);

and the like.

Even if log level is set to ERROR or FATAL, the concatenation of strings do happen ! If the application contains lots of DEBUG level messages with string concatenations, then it certainly takes a performance hit especially with jdk 1.4 or below. (Iam not sure if later versions of jdk internall do any stringbuffer.append()).

Thats why Option 2 is safe. Even the string concatenations dont happen.

How to set dropdown arrow in spinner?

One simple way is to wrap your Spinner + Drop Down Arrow Image inside a Layout. Set the background of Spinner as transparent so that the default arrow icon gets hidden. Something like this:

 <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background"
        android:orientation="horizontal">

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="4"
            android:gravity="center"
            android:background="@android:color/transparent"
            android:spinnerMode="dropdown" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:onClick="showDropDown"
            android:src="@drawable/ic_chevron_down_blue" />

    </LinearLayout>

Here background.xml is a drawable to produce a box type background.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/transparent" />
    <corners android:radius="2dp" />
    <stroke
        android:width="1dp"
        android:color="#BDBDBD" />
</shape>

The above code produces this type of a Spinner and icon.

Spinner with a custom drop down arrow

What is the meaning of ToString("X2")?

It formats the string as two uppercase hexadecimal characters.

In more depth, the argument "X2" is a "format string" that tells the ToString() method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.

byte.ToString() without any arguments returns the number in its natural decimal representation, with no padding.

Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString() methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString().

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

How to get start and end of previous month in VB

Public Shared Function GetFOMPrev(ByVal tdate As Date) As Date
    Return tdate.AddDays(-(tdate.Day - 1))
End Function

Public Shared Function GetEOMPrev(ByVal tdate As Date) As Date
    Return tdate.AddDays(-tdate.Day)
End Function

Usage:

'Get End of Month of Previous Month - Pass today's date
EOM = GetEOMPrev(Date.Today)

'Get First of Month of Previous Month - Pass date just calculated
FOM = GetFOMPrev(EOM)

Find out how much memory is being used by an object in Python

For big objects you may use a somewhat crude but effective method: check how much memory your Python process occupies in the system, then delete the object and compare.

This method has many drawbacks but it will give you a very fast estimate for very big objects.