Programs & Examples On #Dataadapter

DataAdapter is a .Net framework class that facilitates communication between a DataTable and a database.

How to use a DataAdapter with stored procedure and parameter

    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
        builder.DataSource = <sql server name>;
        builder.UserID = <user id>; //User id used to login into SQL
        builder.Password = <password>; //password used to login into SQL
        builder.InitialCatalog = <database name>; //Name of Database

        DataTable orderTable = new DataTable();

        //<sp name> stored procedute name which you want to exceute
        using (var con = new SqlConnection(builder.ConnectionString))
        using (SqlCommand cmd = new SqlCommand(<sp name>, con)) 
        using (var da = new SqlDataAdapter(cmd))
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            //Data adapter(da) fills the data retuned from stored procedure 
           //into orderTable
            da.Fill(orderTable);
        }

XML element with attribute and content using JAXB

The correct scheme should be:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport" 
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" 
jaxb:version="2.0">

<complexType name="sportType">
    <simpleContent>
        <extension base="string">
            <attribute name="type" type="string" />
            <attribute name="gender" type="string" />
        </extension>
    </simpleContent>
</complexType>

<element name="sports">
    <complexType>
        <sequence>
            <element name="sport" minOccurs="0" maxOccurs="unbounded"
                type="tns:sportType" />
        </sequence>
    </complexType>
</element>

Code generated for SportType will be:

package org.example.sport;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {
    @XmlValue
    protected String value;
    @XmlAttribute
    protected String type;
    @XmlAttribute
    protected String gender;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
    return type;
    }


    public void setType(String value) {
        this.type = value;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String value) {
        this.gender = value;
    }
}

Using LINQ to concatenate strings

This answer shows usage of LINQ (Aggregate) as requested in the question and is not intended for everyday use. Because this does not use a StringBuilder it will have horrible performance for very long sequences. For regular code use String.Join as shown in the other answer

Use aggregate queries like this:

string[] words = { "one", "two", "three" };
var res = words.Aggregate(
   "", // start with empty string to handle empty list case.
   (current, next) => current + ", " + next);
Console.WriteLine(res);

This outputs:

, one, two, three

An aggregate is a function that takes a collection of values and returns a scalar value. Examples from T-SQL include min, max, and sum. Both VB and C# have support for aggregates. Both VB and C# support aggregates as extension methods. Using the dot-notation, one simply calls a method on an IEnumerable object.

Remember that aggregate queries are executed immediately.

More information - MSDN: Aggregate Queries


If you really want to use Aggregate use variant using StringBuilder proposed in comment by CodeMonkeyKing which would be about the same code as regular String.Join including good performance for large number of objects:

 var res = words.Aggregate(
     new StringBuilder(), 
     (current, next) => current.Append(current.Length == 0? "" : ", ").Append(next))
     .ToString();

Construct pandas DataFrame from items in nested dictionary

So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d

import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}

The command

pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06

where pd.Panel(d)[item] yields a dataframe

pd.Panel(d)['SPX Index']
2014-11-03  2014-11-04  2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33

You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.

pd.Panel(d).to_frame().reset_index()
major   minor      RAY Index    SPX Index
PX_LAST 2014-11-03  1199.460    2017.81
PX_LAST 2014-11-04  1195.323    2012.10
PX_LAST 2014-11-05  1200.936    2023.57
PX_LAST 2014-11-06  1206.061    2031.21
PX_OPEN 2014-11-03  1200.140    2018.21
PX_OPEN 2014-11-04  1197.690    2015.81
PX_OPEN 2014-11-05  1195.320    2015.29
PX_OPEN 2014-11-06  1200.620    2023.33

Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html

Just as an example

pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major        minor  2014-11-03  2014-11-04  2014-11-05  2014-11-06
RAY Index   PX_LAST 1199.46    1195.323     1200.936    1206.061
RAY Index   PX_OPEN 1200.14    1197.690     1195.320    1200.620
SPX Index   PX_LAST 2017.81    2012.100     2023.570    2031.210
SPX Index   PX_OPEN 2018.21    2015.810     2015.290    2023.330

Hope this helps.

In Python, is there an elegant way to print a list in a custom format without explicit looping?

In python 3s print function:

lst = [1, 2, 3]
print('My list:', *lst, sep='\n- ')

Output:

My list:
- 1
- 2
- 3

Con: The sep must be a string, so you can't modify it based on which element you're printing. And you need a kind of header to do this (above it was 'My list:').

Pro: You don't have to join() a list into a string object, which might be advantageous for larger lists. And the whole thing is quite concise and readable.

import android packages cannot be resolved

try this in eclipse: Window - Preferences - Android - SDK Location and setup SDK path

Check if element at position [x] exists in the list

int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);

ESLint - "window" is not defined. How to allow global variables in package.json

If you are using Angular you can get it off with:

"env": {
    "browser": true,
    "node": true
},
"rules" : {
    "angular/window-service": 0
 }

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

To add my 2 cents, the exception can occur even if you call your code through System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke().
The point is that you have to call Invoke() of the Dispatcher of the control that you're trying to access, which in some cases may not be the same as System.Windows.Threading.Dispatcher.CurrentDispatcher. So instead you should use YourControl.Dispatcher.Invoke() to be safe. I was banging my head for a couple of hours before I realized this.

Update

For future readers, it looks like this has changed in the newer versions of .NET (4.0 and above). Now you no longer have to worry about the correct dispatcher when updating UI-backing properties in your VM. WPF engine will marshal cross-thread calls on the correct UI thread. See more details here. Thanks to @aaronburro for the info and link. You may also want to read our conversation below in comments.

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

If 'localhost' doesn't work but 127.0.0.1 does. Make sure your local hosts file points to the correct location. (/etc/hosts for linux/mac, C:\Windows\System32\drivers\etc\hosts for windows).

Also, make sure your user is allowed to connect to whatever database you're trying to select.

Android Camera Preview Stretched

You must set cameraView.getLayoutParams().height and cameraView.getLayoutParams().width according to the aspect ratio you want.

How to allow only a number (digits and decimal point) to be typed in an input?

Here is a derivative that will also block the decimal point to be entered twice

HTML

    <input tabindex="1" type="text" placeholder="" name="salary" id="salary" data-ng-model="salary" numbers-only="numbers-only" required="required">

Angular

    var app = angular.module("myApp", []);

    app.directive('numbersOnly', function() {
    return {
            require : 'ngModel', link : function(scope, element, attrs,  modelCtrl) {
        modelCtrl.$parsers.push(function(inputValue) {

            if (inputValue == undefined) {
                return ''; //If value is required
            }

            // Regular expression for everything but [.] and [1 - 10] (Replace all)
            var transformedInput = inputValue.replace(/[a-z!@#$%^&*()_+\-=\[\]{};':"\\|,<>\/?]/g, '');

            // Now to prevent duplicates of decimal point
            var arr = transformedInput.split('');

            count = 0; //decimal counter
            for ( var i = 0; i < arr.length; i++) {
                if (arr[i] == '.') {
                    count++; //  how many do we have? increment
                }
            }

            // if we have more than 1 decimal point, delete and leave only one at the end
            while (count > 1) {
                for ( var i = 0; i < arr.length; i++) {
                    if (arr[i] == '.') {
                        arr[i] = '';
                        count = 0;
                        break;
                    }
                }
            }

            // convert the array back to string by relacing the commas
            transformedInput = arr.toString().replace(/,/g, '');

            if (transformedInput != inputValue) {
                modelCtrl.$setViewValue(transformedInput);
                modelCtrl.$render();
            }

            return transformedInput;
        });
    }
};
});

How to get the HTML's input element of "file" type to only accept pdf files?

It can be useful to prevent the distracted user to make an involuntary bad choice, but in any case, you have to do the check on the server side anyway.
The best way is to be clear in the upload page. After that, if the user stupidly upload a big file with the wrong type, that's their loss of time, no?

Sorting a list with stream.sorted() in Java

Java 8 provides different utility api methods to help us sort the streams better.

If your list is a list of Integers(or Double, Long, String etc.,) then you can simply sort the list with default comparators provided by java.

List<Integer> integerList = Arrays.asList(1, 4, 3, 4, 5);

Creating comparator on fly:

integerList.stream().sorted((i1, i2) -> i1.compareTo(i2)).forEach(System.out::println);

With default comparator provided by java 8 when no argument passed to sorted():

integerList.stream().sorted().forEach(System.out::println); //Natural order

If you want to sort the same list in reverse order:

 integerList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); // Reverse Order

If your list is a list of user defined objects, then:

List<Person> personList = Arrays.asList(new Person(1000, "First", 25, 30000),
        new Person(2000, "Second", 30, 45000),
        new Person(3000, "Third", 35, 25000));

Creating comparator on fly:

personList.stream().sorted((p1, p2) -> ((Long)p1.getPersonId()).compareTo(p2.getPersonId()))
        .forEach(person -> System.out.println(person.getName()));

Using Comparator.comparingLong() method(We have comparingDouble(), comparingInt() methods too):

personList.stream().sorted(Comparator.comparingLong(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));

Using Comparator.comparing() method(Generic method which compares based on the getter method provided):

personList.stream().sorted(Comparator.comparing(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));

We can do chaining too using thenComparing() method:

personList.stream().sorted(Comparator.comparing(Person::getPersonId).thenComparing(Person::getAge)).forEach(person -> System.out.println(person.getName())); //Sorting by person id and then by age.

Person class

public class Person {
    private long personId;
    private String name;
    private int age;
    private double salary;

    public long getPersonId() {
        return personId;
    }

    public void setPersonId(long personId) {
        this.personId = personId;
    }

    public Person(long personId, String name, int age, double salary) {
        this.personId = personId;
        this.name = name;
        this.age = age;

        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

Fetch API with Cookie

If you are reading this in 2019, credentials: "same-origin" is the default value.

fetch(url).then

How to draw a filled circle in Java?

public void paintComponent(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2d = (Graphics2D)g;
   // Assume x, y, and diameter are instance variables.
   Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
   g2d.fill(circle);
   ...
}

Here are some docs about paintComponent (link).

You should override that method in your JPanel and do something similar to the code snippet above.

In your ActionListener you should specify x, y, diameter and call repaint().

regular expression: match any word until first space

Perhaps you could try ([^ ]+) .*, which should give you everything to the first blank in your first group.

Ifelse statement in R with multiple conditions

another solution using dplyr is:

df <- ## your data ##
df <- df %>%
        mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))

Install php-mcrypt on CentOS 6

For me, this worked :
yum install php-mcrypt*
and then, restart httpd service
service httpd restart

I tryed @VenomFangs solution but the first step was not needed for me. I already had a newer EPEL version installed. So, the first step following was not usefull, I backed to the snapshot I did before doing modifications and I just used the install and restart above commands.

wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
sudo rpm -Uvh remi-release-6*.rpm epel-release-6*.rpm

CentOS Linux release 7.2.1511 (Core)

PS : I know this is not the subject, but if somebody needs it, the keyword can help. I needed to do this because of this error on prestashop. Two keywords I would be glad to use to find this informations are : "php_mycrypt.dll" "php_mcrypt.dll"
Fatal error: Call to undefined function mcrypt_encrypt() in /classes/Rijndael.php on line 46

EDIT 10/06/2016 :
Another Prestashop solution to try in "Advanced Parameters", "Performance", "Ciphering" (FR : Chiffrement), "Use the custom BlowFish class." instead of "Use Rijndael with mcrypt lib. (you must install the Mcrypt extension)."

How to pass data to all views in Laravel 5?

I found this to be the easiest one. Create a new provider and user the '*' wildcard to attach it to all views. Works in 5.3 as well :-)

<?php

namespace App\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function ($view)
        {
            $user = request()->user();

            $view->with('user', $user);
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Matching a space in regex

Use it like this to allow for single space.

$newtag = preg_replace("/[^a-zA-Z0-9\s]/", "", $tag)

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

If you want to make a change global to the whole notebook:

import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]

Best way to include CSS? Why use @import?

From a page speed standpoint, @import from a CSS file should almost never be used, as it can prevent stylesheets from being downloaded concurrently. For instance, if stylesheet A contains the text:

@import url("stylesheetB.css");

then the download of the second stylesheet may not start until the first stylesheet has been downloaded. If, on the other hand, both stylesheets are referenced in <link> elements in the main HTML page, both can be downloaded at the same time. If both stylesheets are always loaded together, it can also be helpful to simply combine them into a single file.

There are occasionally situations where @import is appropriate, but they are generally the exception, not the rule.

printf not printing on console

  1. In your project folder, create a “.gdbinit” text file. It will contain your gdb debugger configuration
  2. Edit “.gdbinit”, and add the line (without the quotes) : “set new-console on”
  3. After building the project right click on the project Debug > “Debug Configurations”, as shown below Debug configuration

  4. In the “debugger” tab, ensure the “GDB command file” now points to your “.gdbinit” file. Else, input the path to your “.gdbinit” configuration file : Gdb configuration

  5. Click “Apply” and “Debug”. A native DOS command line should be launched as shown below Console

Automatic prune with Git fetch or pull

Since git 1.8.5 (Q4 2013):

"git fetch" (hence "git pull" as well) learned to check "fetch.prune" and "remote.*.prune" configuration variables and to behave as if the "--prune" command line option was given.

That means that, if you set remote.origin.prune to true:

git config remote.origin.prune true

Any git fetch or git pull will automatically prune.

Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename misbehave.
See "How do I rename a git remote?".


See more at commit 737c5a9:

Without "git fetch --prune", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune".

To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "fetch.prune" and "remote.<name>.prune":

  • "fetch.prune" allows to enable prune for all fetch operations.
  • "remote.<name>.prune" allows to change the behaviour per remote.

The latter will naturally override the former, and the --[no-]prune option from the command line will override the configured default.

Since --prune is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.

Find the closest ancestor element that has a specific class

This does the trick:

function findAncestor (el, cls) {
    while ((el = el.parentElement) && !el.classList.contains(cls));
    return el;
}

The while loop waits until el has the desired class, and it sets el to el's parent every iteration so in the end, you have the ancestor with that class or null.

Here's a fiddle, if anyone wants to improve it. It won't work on old browsers (i.e. IE); see this compatibility table for classList. parentElement is used here because parentNode would involve more work to make sure that the node is an element.

Bash function to find newest file matching pattern

Dark magic function incantation for those who want the find ... xargs ... head ... solution above, but in easy to use function form so you don't have to think:

#define the function
find_newest_file_matching_pattern_under_directory(){
    echo $(find $1 -name $2 -print0 | xargs -0 ls -1 -t | head -1)
}

#setup:
#mkdir /tmp/files_to_move
#cd /tmp/files_to_move
#touch file1.txt
#touch file2.txt

#invoke the function:
newest_file=$( find_newest_file_matching_pattern_under_directory /tmp/files_to_move/ bc* )
echo $newest_file

Prints:

file2.txt

Which is:

The filename with the oldest modified timestamp of the file under the given directory matching the given pattern.

"Keep Me Logged In" - the best approach

OK, let me put this bluntly: if you're putting user data, or anything derived from user data into a cookie for this purpose, you're doing something wrong.

There. I said it. Now we can move on to the actual answer.

What's wrong with hashing user data, you ask? Well, it comes down to exposure surface and security through obscurity.

Imagine for a second that you're an attacker. You see a cryptographic cookie set for the remember-me on your session. It's 32 characters wide. Gee. That may be an MD5...

Let's also imagine for a second that they know the algorithm that you used. For example:

md5(salt+username+ip+salt)

Now, all an attacker needs to do is brute force the "salt" (which isn't really a salt, but more on that later), and he can now generate all the fake tokens he wants with any username for his IP address! But brute-forcing a salt is hard, right? Absolutely. But modern day GPUs are exceedingly good at it. And unless you use sufficient randomness in it (make it large enough), it's going to fall quickly, and with it the keys to your castle.

In short, the only thing protecting you is the salt, which isn't really protecting you as much as you think.

But Wait!

All of that was predicated that the attacker knows the algorithm! If it's secret and confusing, then you're safe, right? WRONG. That line of thinking has a name: Security Through Obscurity, which should NEVER be relied upon.

The Better Way

The better way is to never let a user's information leave the server, except for the id.

When the user logs in, generate a large (128 to 256 bit) random token. Add that to a database table which maps the token to the userid, and then send it to the client in the cookie.

What if the attacker guesses the random token of another user?

Well, let's do some math here. We're generating a 128 bit random token. That means that there are:

possibilities = 2^128
possibilities = 3.4 * 10^38

Now, to show how absurdly large that number is, let's imagine every server on the internet (let's say 50,000,000 today) trying to brute-force that number at a rate of 1,000,000,000 per second each. In reality your servers would melt under such load, but let's play this out.

guesses_per_second = servers * guesses
guesses_per_second = 50,000,000 * 1,000,000,000
guesses_per_second = 50,000,000,000,000,000

So 50 quadrillion guesses per second. That's fast! Right?

time_to_guess = possibilities / guesses_per_second
time_to_guess = 3.4e38 / 50,000,000,000,000,000
time_to_guess = 6,800,000,000,000,000,000,000

So 6.8 sextillion seconds...

Let's try to bring that down to more friendly numbers.

215,626,585,489,599 years

Or even better:

47917 times the age of the universe

Yes, that's 47917 times the age of the universe...

Basically, it's not going to be cracked.

So to sum up:

The better approach that I recommend is to store the cookie with three parts.

function onLogin($user) {
    $token = GenerateRandomToken(); // generate a token, should be 128 - 256 bit
    storeTokenForUser($user, $token);
    $cookie = $user . ':' . $token;
    $mac = hash_hmac('sha256', $cookie, SECRET_KEY);
    $cookie .= ':' . $mac;
    setcookie('rememberme', $cookie);
}

Then, to validate:

function rememberMe() {
    $cookie = isset($_COOKIE['rememberme']) ? $_COOKIE['rememberme'] : '';
    if ($cookie) {
        list ($user, $token, $mac) = explode(':', $cookie);
        if (!hash_equals(hash_hmac('sha256', $user . ':' . $token, SECRET_KEY), $mac)) {
            return false;
        }
        $usertoken = fetchTokenByUserName($user);
        if (hash_equals($usertoken, $token)) {
            logUserIn($user);
        }
    }
}

Note: Do not use the token or combination of user and token to lookup a record in your database. Always be sure to fetch a record based on the user and use a timing-safe comparison function to compare the fetched token afterwards. More about timing attacks.

Now, it's very important that the SECRET_KEY be a cryptographic secret (generated by something like /dev/urandom and/or derived from a high-entropy input). Also, GenerateRandomToken() needs to be a strong random source (mt_rand() is not nearly strong enough. Use a library, such as RandomLib or random_compat, or mcrypt_create_iv() with DEV_URANDOM)...

The hash_equals() is to prevent timing attacks. If you use a PHP version below PHP 5.6 the function hash_equals() is not supported. In this case you can replace hash_equals() with the timingSafeCompare function:

/**
 * A timing safe equals comparison
 *
 * To prevent leaking length information, it is important
 * that user input is always used as the second parameter.
 *
 * @param string $safe The internal (safe) value to be checked
 * @param string $user The user submitted (unsafe) value
 *
 * @return boolean True if the two strings are identical.
 */
function timingSafeCompare($safe, $user) {
    if (function_exists('hash_equals')) {
        return hash_equals($safe, $user); // PHP 5.6
    }
    // Prevent issues if string length is 0
    $safe .= chr(0);
    $user .= chr(0);

    // mbstring.func_overload can make strlen() return invalid numbers
    // when operating on raw binary strings; force an 8bit charset here:
    if (function_exists('mb_strlen')) {
        $safeLen = mb_strlen($safe, '8bit');
        $userLen = mb_strlen($user, '8bit');
    } else {
        $safeLen = strlen($safe);
        $userLen = strlen($user);
    }

    // Set the result to the difference between the lengths
    $result = $safeLen - $userLen;

    // Note that we ALWAYS iterate over the user-supplied length
    // This is to prevent leaking length information
    for ($i = 0; $i < $userLen; $i++) {
        // Using % here is a trick to prevent notices
        // It's safe, since if the lengths are different
        // $result is already non-0
        $result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i]));
    }

    // They are only identical strings if $result is exactly 0...
    return $result === 0;
}

How can I truncate a double to only two decimal places in Java?

This worked for me:

double input = 104.8695412  //For example

long roundedInt = Math.round(input * 100);
double result = (double) roundedInt/100;

//result == 104.87

I personally like this version because it actually performs the rounding numerically, rather than by converting it to a String (or similar) and then formatting it.

Cannot install packages using node package manager in Ubuntu

Uninstall whatever node version you have

sudo apt-get --purge remove node
sudo apt-get --purge remove nodejs-legacy
sudo apt-get --purge remove nodejs

install nvm (Node Version Manager) https://github.com/creationix/nvm

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash

Now you can install whatever version of node you want and switch between the versions.

Get properties of a class

Some answers are partially wrong, and some facts in them are partially wrong as well.

Answer your question: Yes! You can.

In Typescript

class A {
    private a1;
    private a2;


}

Generates the following code in Javascript:

var A = /** @class */ (function () {
    function A() {
    }
    return A;
}());

as @Erik_Cupal said, you could just do:

let a = new A();
let array = return Object.getOwnPropertyNames(a);

But this is incomplete. What happens if your class has a custom constructor? You need to do a trick with Typescript because it will not compile. You need to assign as any:

let className:any = A;
let a = new className();// the members will have value undefined

A general solution will be:

class A {
    private a1;
    private a2;
    constructor(a1:number, a2:string){
        this.a1 = a1;
        this.a2 = a2;
    }
}

class Describer{

   describeClass( typeOfClass:any){
       let a = new typeOfClass();
       let array = Object.getOwnPropertyNames(a);
       return array;//you can apply any filter here
   }
}

For better understanding this will reference depending on the context.

Read remote file with node.js (http.get)

http.get(options).on('response', function (response) {
    var body = '';
    var i = 0;
    response.on('data', function (chunk) {
        i++;
        body += chunk;
        console.log('BODY Part: ' + i);
    });
    response.on('end', function () {

        console.log(body);
        console.log('Finished');
    });
});

Changes to this, which works. Any comments?

What jar should I include to use javax.persistence package in a hibernate based application?

For JPA 2.1 the javax.persistence package can be found in here:

<dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.1-api</artifactId>
   <version>1.0.0.Final</version>
</dependency>

See: hibernate-jpa-2.1-api on Maven Central The pattern seems to be to change the artefact name as the JPA version changes. If this continues new versions can be expected to arrive in Maven Central here: Hibernate JPA versions

The above JPA 2.1 APi can be used in conjunction with Hibernate 4.3.7, specifically:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>4.3.7.Final</version>
</dependency>

Redefine tab as 4 spaces

or shorthand for vim modeline:

vim :set ts=4 sw=4 sts=4 et :

Calculating and printing the nth prime number

I can see that you have received many correct answers and very detailed one. I believe you are not testing it for very large prime numbers. And your only concern is to avoid printing intermediary prime number by your program.

A tiny change your program will do the trick.

Keep your logic same way and just pull out the print statement outside of loop. Break outer loop after n prime numbers.

import java.util.Scanner;
/**
 * Calculates the nth prime number
 * @author {Zyst}
 */
public class Prime {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int n, 
            i = 2, 
            x = 2;

        System.out.printf("This program calculates the nth Prime number\n");
        System.out.printf("Please enter the nth prime number you want to find:");
        n = input.nextInt();

        for(i = 2, x = 2; n > 0; i++) {
            for(x = 2; x < i; x++) {
                if(i % x == 0) {
                    break;
                }
            }
            if(x == i) {
                n--;
            }
        }
        System.out.printf("\n%d is prime", x);

    }
}

format statement in a string resource file

For me it worked like that in Kotlin:

my string.xml

 <string name="price" formatted="false">Price:U$ %.2f%n</string>

my class.kt

 var formatPrice: CharSequence? = null
 var unitPrice = 9990
 formatPrice = String.format(context.getString(R.string.price), unitPrice/100.0)
 Log.d("Double_CharSequence", "$formatPrice")

D/Double_CharSequence: Price :U$ 99,90

For an even better result, we can do so

 <string name="price_to_string">Price:U$ %1$s</string>

 var formatPrice: CharSequence? = null
 var unitPrice = 199990
 val numberFormat = (unitPrice/100.0).toString()
 formatPrice = String.format(context.getString(R.string.price_to_string), formatValue(numberFormat))

  fun formatValue(value: String) :String{
    val mDecimalFormat = DecimalFormat("###,###,##0.00")
    val s1 = value.toDouble()
    return mDecimalFormat.format(s1)
 }

 Log.d("Double_CharSequence", "$formatPrice")

D/Double_CharSequence: Price :U$ 1.999,90

How an 'if (A && B)' statement is evaluated?

for logical && both the parameters must be true , then it ll be entered in if {} clock otherwise it ll execute else {}. for logical || one of parameter or condition is true is sufficient to execute if {}.

if( (A) && (B) ){
     //if A and B both are true
}else{
}
if( (A) ||(B) ){
     //if A or B is true 
}else{
}

Spring .properties file: get element as an Array

And incase you a different delimiter other than comma, you can use that as well.

@Value("#{'${my.config.values}'.split(',')}")
private String[] myValues;   // could also be a List<String>

and

in your application properties you could have

my.config.values=value1, value2, value3

Add a string of text into an input field when user clicks a button

Don't forget to keep the input field on focus for future typing with input.focus(); inside the function.

CSS - display: none; not working

Remove display: block; in the div #tfl style property

<div id="tfl" style="display: block; width: 187px; height: 260px;

Inline style take priority then css file

Angular - POST uploaded file

your http service file:

import { Injectable } from "@angular/core";
import { ActivatedRoute, Router } from '@angular/router';
import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import {Observable} from 'rxjs/Rx';
import { Constants } from './constants';
declare var $: any;

@Injectable()
export class HttpClient {
  requestUrl: string;
  responseData: any;
  handleError: any;

  constructor(private router: Router, 
  private http: Http, 
  private constants: Constants, 
  ) {
    this.http = http;
  }

  postWithFile (url: string, postData: any, files: File[]) {

    let headers = new Headers();
    let formData:FormData = new FormData();
    formData.append('files', files[0], files[0].name);
    // For multiple files
    // for (let i = 0; i < files.length; i++) {
    //     formData.append(`files[]`, files[i], files[i].name);
    // }

    if(postData !=="" && postData !== undefined && postData !==null){
      for (var property in postData) {
          if (postData.hasOwnProperty(property)) {
              formData.append(property, postData[property]);
          }
      }
    }
    var returnReponse = new Promise((resolve, reject) => {
      this.http.post(this.constants.root_dir + url, formData, {
        headers: headers
      }).subscribe(
          res => {
            this.responseData = res.json();
            resolve(this.responseData);
          },
          error => {
            this.router.navigate(['/login']);
            reject(error);
          }
      );
    });
    return returnReponse;
  }
}

call your function (Component file):

onChange(event) {
    let file = event.srcElement.files;
    let postData = {field1:"field1", field2:"field2"}; // Put your form data variable. This is only example.
    this._service.postWithFile(this.baseUrl + "add-update",postData,file).then(result => {
        console.log(result);
    });
}

your html code:

<input type="file" class="form-control" name="documents" (change)="onChange($event)" [(ngModel)]="stock.documents" #documents="ngModel">

How do I pass variables and data from PHP to JavaScript?

Here is is the trick:

  1. Here is your 'PHP' to use that variable:

    <?php
        $name = 'PHP variable';
        echo '<script>';
        echo 'var name = ' . json_encode($name) . ';';
        echo '</script>';
    ?>
    
  2. Now you have a JavaScript variable called 'name', and here is your JavaScript code to use that variable:

    <script>
         console.log("I am everywhere " + name);
    </script>
    

How to change theme for AlertDialog

I was struggling with this - you can style the background of the dialog using android:alertDialogStyle="@style/AlertDialog" in your theme, but it ignores any text settings you have. As @rflexor said above it cannot be done with the SDK prior to Honeycomb (well you could use Reflection).

My solution, in a nutshell, was to style the background of the dialog using the above, then set a custom title and content view (using layouts that are the same as those in the SDK).

My wrapper:

import com.mypackage.R;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomAlertDialogBuilder extends AlertDialog.Builder {

    private final Context mContext;
    private TextView mTitle;
    private ImageView mIcon;
    private TextView mMessage;

    public CustomAlertDialogBuilder(Context context) {
        super(context);
        mContext = context; 

        View customTitle = View.inflate(mContext, R.layout.alert_dialog_title, null);
        mTitle = (TextView) customTitle.findViewById(R.id.alertTitle);
        mIcon = (ImageView) customTitle.findViewById(R.id.icon);
        setCustomTitle(customTitle);

        View customMessage = View.inflate(mContext, R.layout.alert_dialog_message, null);
        mMessage = (TextView) customMessage.findViewById(R.id.message);
        setView(customMessage);
    }

    @Override
    public CustomAlertDialogBuilder setTitle(int textResId) {
        mTitle.setText(textResId);
        return this;
    }
    @Override
    public CustomAlertDialogBuilder setTitle(CharSequence text) {
        mTitle.setText(text);
        return this;
    }

    @Override
    public CustomAlertDialogBuilder setMessage(int textResId) {
        mMessage.setText(textResId);
        return this;
    }

    @Override
    public CustomAlertDialogBuilder setMessage(CharSequence text) {
        mMessage.setText(text);
        return this;
    }

    @Override
    public CustomAlertDialogBuilder setIcon(int drawableResId) {
        mIcon.setImageResource(drawableResId);
        return this;
    }

    @Override
    public CustomAlertDialogBuilder setIcon(Drawable icon) {
        mIcon.setImageDrawable(icon);
        return this;
    }

}

alert_dialog_title.xml (taken from the SDK)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
    <LinearLayout
            android:id="@+id/title_template"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center_vertical"
            android:layout_marginTop="6dip"
            android:layout_marginBottom="9dip"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="10dip">

            <ImageView android:id="@+id/icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:paddingTop="6dip"
                android:paddingRight="10dip"
                android:src="@drawable/ic_dialog_alert" />
            <TextView android:id="@+id/alertTitle"
                style="@style/?android:attr/textAppearanceLarge"
                android:singleLine="true"
                android:ellipsize="end"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <ImageView android:id="@+id/titleDivider"
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            android:scaleType="fitXY"
            android:gravity="fill_horizontal"
            android:src="@drawable/divider_horizontal_bright" />
</LinearLayout>

alert_dialog_message.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/scrollView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="2dip"
            android:paddingBottom="12dip"
            android:paddingLeft="14dip"
            android:paddingRight="10dip">
    <TextView android:id="@+id/message"
                style="?android:attr/textAppearanceMedium"
                android:textColor="@color/dark_grey"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="5dip" />
</ScrollView>

Then just use CustomAlertDialogBuilder instead of AlertDialog.Builder to create your dialogs, and just call setTitle and setMessage as usual.

Inputting a default image in case the src attribute of an html <img> is not valid?

I don't think it is possible using just HTML. However using javascript this should be doable. Bassicly we loop over each image, test if it is complete and if it's naturalWidth is zero then that means that it not found. Here is the code:

fixBrokenImages = function( url ){
    var img = document.getElementsByTagName('img');
    var i=0, l=img.length;
    for(;i<l;i++){
        var t = img[i];
        if(t.naturalWidth === 0){
            //this image is broken
            t.src = url;
        }
    }
}

Use it like this:

 window.onload = function() {
    fixBrokenImages('example.com/image.png');
 }

Tested in Chrome and Firefox

How to auto-indent code in the Atom editor?

The accepted answer works, but you have to do a "Select All" first -- every time -- and I'm way too lazy for that.

And it turns out, it's not super trivial -- I figured I'd post this here in an attempt to save like-minded individuals the 30 minutes it takes to track all this down. -- Also note: this approach restores the original selection when it's done (and it happens so fast, you don't even notice the selection was ever changed).

1.) First, add a custom command to your init script (File->Open Your Init Script, then paste this at the bottom):

atom.commands.add 'atom-text-editor', 'custom:reformat', ->
    editor = atom.workspace.getActiveTextEditor();
    oldRanges = editor.getSelectedBufferRanges();
    editor.selectAll();
    atom.commands.dispatch(atom.views.getView(editor), 'editor:auto-indent')
    editor.setSelectedBufferRanges(oldRanges);

2.) Bind "custom:reformat" to a key (File->Open Your Keymap, then paste this at the bottom):

'atom-text-editor':
    'ctrl-alt-d': 'custom:reformat'

3.) Restart Atom (the init.coffee script only runs when atom is first launched).

Good Hash Function for Strings

// djb2 hash function
unsigned long hash(unsigned char *str)
{
    unsigned long hash = 5381;
    int c;

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

source Logic behind djb2 hash function - SO

How to bind inverse boolean properties in WPF?

You can use a ValueConverter that inverts a bool property for you.

XAML:

IsEnabled="{Binding Path=IsReadOnly, Converter={StaticResource InverseBooleanConverter}}"

Converter:

[ValueConversion(typeof(bool), typeof(bool))]
    public class InverseBooleanConverter: IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            if (targetType != typeof(bool))
                throw new InvalidOperationException("The target must be a boolean");

            return !(bool)value;
        }

        public object ConvertBack(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        #endregion
    }

What does "\r" do in the following script?

\r is the ASCII Carriage Return (CR) character.

There are different newline conventions used by different operating systems. The most common ones are:

  • CR+LF (\r\n);
  • LF (\n);
  • CR (\r).

The \n\r (LF+CR) looks unconventional.

edit: My reading of the Telnet RFC suggests that:

  1. CR+LF is the standard newline sequence used by the telnet protocol.
  2. LF+CR is an acceptable substitute:

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

Convert String into a Class Object

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

Your question is ambiguous. It could mean at least two different things, one of which is ... well ... a serious misconception on your part.


If you did this:

SomeClass object = ...
String s = object.toString();

then the answer is that there is no simple way to turn s back into an instance of SomeClass. You couldn't do it even if the toString() method gave you one of those funky "SomeClass@xxxxxxxx" strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object's identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)

The only way you could turn the output of toString back into an object would be to:

  • code the SomeClass.toString() method so that included all relevant state for the object in the String it produced, and
  • code a constructor or factory method that explicitly parsed a String in the format produced by the toString() method.

This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.


If you did something like this:

SomeClass object = ...
Class c = object.getClass();
String cn = c.toString();

then you could get the same Class object back (i.e. the one that is in c) as follows:

Class c2 = Class.forName(cn);

This gives you the Class but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)


If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn't be using toString() method at all. Here are some alternatives that you can use:

  • The Java Object Serialization APIs as described in the links in @Nishant's answer.
  • JSON serialization as described in @fatnjazzy's answer.
  • An XML serialization library like XStream.
  • An ORM mapping.

Each of these approaches has advantages and disadvantages ... which I won't go into here.

SQL Server Group By Month

Another approach, that doesn't involve adding columns to the result, is to simply zero-out the day component of the date, so 2016-07-13 and 2016-07-16 would both be 2016-07-01 - thus making them equal by month.

If you have a date (not a datetime) value, then you can zero it directly:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] )

If you have datetime values, you'll need to use CONVERT to remove the time-of-day portion:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) )

jQuery form validation on button click

$(document).ready(function() {
    $("#form1").validate({
        rules: {
            field1: "required"
        },
        messages: {
            field1: "Please specify your name"
        }
    })
});

<form id="form1" name="form1">
     Field 1: <input id="field1" type="text" class="required">
    <input id="btn" type="submit" value="Validate">
</form>

You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.

Java Spring Boot: How to map my app root (“/”) to index.html?

I had the same problem. Spring boot knows where static html files are located.

  1. Add index.html into resources/static folder
  2. Then delete full controller method for root path like @RequestMapping("/") etc
  3. Run app and check http://localhost:8080 (Should work)

jQuery get values of checked checkboxes into array

     var ids = [];

$('input[id="find-table"]:checked').each(function() {
   ids.push(this.value); 
});

This one worked for me!

Create Log File in Powershell

You might just want to use the new TUN.Logging PowerShell module, this can also send a log mail. Just use the Start-Log and/or Start-MailLog cmdlets to start logging and then just use Write-HostLog, Write-WarningLog, Write-VerboseLog, Write-ErrorLog etc. to write to console and log file/mail. Then call Send-Log and/or Stop-Log at the end and voila, you got your logging. Just install it from the PowerShell Gallery via

Install-Module -Name TUN.Logging

Or just follow the link: https://www.powershellgallery.com/packages/TUN.Logging

Documentation of the module can be found here: https://github.com/echalone/TUN/blob/master/PowerShell/Modules/TUN.Logging/TUN.Logging.md

Add new column in Pandas DataFrame Python

You just do an opposite comparison. if Col2 <= 1. This will return a boolean Series with False values for those greater than 1 and True values for the other. If you convert it to an int64 dtype, True becomes 1 and False become 0,

df['Col3'] = (df['Col2'] <= 1).astype(int)

If you want a more general solution, where you can assign any number to Col3 depending on the value of Col2 you should do something like:

df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)

Or:

df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55

What could cause java.lang.reflect.InvocationTargetException?

The error vanished after I did Clean->Run xDoclet->Run xPackaging.

In my workspace, in ecllipse.

Laravel: PDOException: could not find driver

You need to enable these extensions in the php.ini file

Before:

;extension=pdo_mysql
;extension=mysqli
;extension=pdo_sqlite
;extension=sqlite3

After:

extension=pdo_mysql
extension=mysqli
extension=pdo_sqlite
extension=sqlite3

It is advisable that you also activate the fileinfo extension, many packages require this.

How can I find where I will be redirected using cURL?

Sometimes you need to get HTTP headers but at the same time you don't want return those headers.**

This skeleton takes care of cookies and HTTP redirects using recursion. The main idea here is to avoid return HTTP headers to the client code.

You can build a very strong curl class over it. Add POST functionality, etc.

<?php

class curl {

  static private $cookie_file            = '';
  static private $user_agent             = '';  
  static private $max_redirects          = 10;  
  static private $followlocation_allowed = true;

  function __construct()
  {
    // set a file to store cookies
    self::$cookie_file = 'cookies.txt';

    // set some general User Agent
    self::$user_agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';

    if ( ! file_exists(self::$cookie_file) || ! is_writable(self::$cookie_file))
    {
      throw new Exception('Cookie file missing or not writable.');
    }

    // check for PHP settings that unfits
    // correct functioning of CURLOPT_FOLLOWLOCATION 
    if (ini_get('open_basedir') != '' || ini_get('safe_mode') == 'On')
    {
      self::$followlocation_allowed = false;
    }    
  }

  /**
   * Main method for GET requests
   * @param  string $url URI to get
   * @return string      request's body
   */
  static public function get($url)
  {
    $process = curl_init($url);    

    self::_set_basic_options($process);

    // this function is in charge of output request's body
    // so DO NOT include HTTP headers
    curl_setopt($process, CURLOPT_HEADER, 0);

    if (self::$followlocation_allowed)
    {
      // if PHP settings allow it use AUTOMATIC REDIRECTION
      curl_setopt($process, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($process, CURLOPT_MAXREDIRS, self::$max_redirects); 
    }
    else
    {
      curl_setopt($process, CURLOPT_FOLLOWLOCATION, false);
    }

    $return = curl_exec($process);

    if ($return === false)
    {
      throw new Exception('Curl error: ' . curl_error($process));
    }

    // test for redirection HTTP codes
    $code = curl_getinfo($process, CURLINFO_HTTP_CODE);
    if ($code == 301 || $code == 302)
    {
      curl_close($process);

      try
      {
        // go to extract new Location URI
        $location = self::_parse_redirection_header($url);
      }
      catch (Exception $e)
      {
        throw $e;
      }

      // IMPORTANT return 
      return self::get($location);
    }

    curl_close($process);

    return $return;
  }

  static function _set_basic_options($process)
  {

    curl_setopt($process, CURLOPT_USERAGENT, self::$user_agent);
    curl_setopt($process, CURLOPT_COOKIEFILE, self::$cookie_file);
    curl_setopt($process, CURLOPT_COOKIEJAR, self::$cookie_file);
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
    // curl_setopt($process, CURLOPT_VERBOSE, 1);
    // curl_setopt($process, CURLOPT_SSL_VERIFYHOST, false);
    // curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
  }

  static function _parse_redirection_header($url)
  {
    $process = curl_init($url);    

    self::_set_basic_options($process);

    // NOW we need to parse HTTP headers
    curl_setopt($process, CURLOPT_HEADER, 1);

    $return = curl_exec($process);

    if ($return === false)
    {
      throw new Exception('Curl error: ' . curl_error($process));
    }

    curl_close($process);

    if ( ! preg_match('#Location: (.*)#', $return, $location))
    {
      throw new Exception('No Location found');
    }

    if (self::$max_redirects-- <= 0)
    {
      throw new Exception('Max redirections reached trying to get: ' . $url);
    }

    return trim($location[1]);
  }

}

Initializing default values in a struct

You can do it by using a constructor, like this:

struct Date
{
int day;
int month;
int year;

Date()
{
    day=0;
    month=0;
    year=0;
}
};

or like this:

struct Date
{
int day;
int month;
int year;

Date():day(0),
       month(0),
       year(0){}
};

In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).

How to get rid of underline for Link component of React Router?

I have resolve a problem maybe like your. I tried to inspect element in firefox. I will show you some results:

  1. It is only the element I have inspect. The "Link" component will be convert to "a" tag, and "to" props will be convert to the "href" property:

  1. And when I tick in :hov and option :hover and here is result:

As you see a:hover have text-decoration: underline. I only add to my css file:

a:hover {
 text-decoration: none;
}

and problem is resolved. But I also set text-decoration: none in some another classes (like you :D), that may be make some effects (I guess).

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

This error occurred when you are putting JPA dependencies in your spring-boot configuration file like in maven or gradle. The solution is: Spring-Boot Documentation

You have to specify the DB connection string and driver details in application.properties file. This will solve the issue. This might help to someone.

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

How do I check out an SVN project into Eclipse as a Java project?

If it wasn't checked in as a Java Project, you can add the java nature as shown here.

Using ConfigurationManager to load config from an arbitrary location

Try this:

System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Path to your config file
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);

Why am I getting error CS0246: The type or namespace name could not be found?

I also got this error due to a missing reference. The reason I did not notice is because Resharper offers to add a using and a reference. Adding the using succeeds (but it's highlighted grey), syntax highlighting of missing classes works (sometimes), but adding the reference fails silently.

When manually adding the reference an error pops up, explaining why adding the reference fails (circular reference). Resharper did not pass this error on to the GUI.

What are major differences between C# and Java?

Generics:

With Java generics, you don't actually get any of the execution efficiency that you get with .NET because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. For instance if you have a Foo<T> class the java compiler generates Byte Code as if it was Foo<Object>. This means casting and also boxing/unboxing will have to be done in the "background".

I've been playing with Java/C# for a while now and, in my opinion, the major difference at the language level are, as you pointed, delegates.

Sort a list of tuples by 2nd item (integer value)

The fact that the sort values in the OP are integers isn't relevant to the question per se. In other words, the accepted answer would work if the sort value was text. I bring this up to also point out that the sort can be modified during the sort (for example, to account for upper and lower case).

>>> sorted([(121, 'abc'), (231, 'def'), (148, 'ABC'), (221, 'DEF')], key=lambda x: x[1])
[(148, 'ABC'), (221, 'DEF'), (121, 'abc'), (231, 'def')]
>>> sorted([(121, 'abc'), (231, 'def'), (148, 'ABC'), (221, 'DEF')], key=lambda x: str.lower(x[1]))
[(121, 'abc'), (148, 'ABC'), (231, 'def'), (221, 'DEF')]

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

CSS/HTML: What is the correct way to make text italic?

Perhaps it has no special meaning and only needs to be rendered in italics to separate it presentationally from the text preceding it.

If it has no special meaning, why does it need to be separated presentationally from the text preceding it? This run of text looks a bit weird, because I’ve italicised it for no reason.

I do take your point though. It’s not uncommon for designers to produce designs that vary visually, without varying meaningfully. I’ve seen this most often with boxes: designers will give us designs including boxes with various combinations of colours, corners, gradients and drop-shadows, with no relation between the styles, and the meaning of the content.

Because these are reasonably complex styles (with associated Internet Explorer issues) re-used in different places, we create classes like box-1, box-2, so that we can re-use the styles.

The specific example of making some text italic is too trivial to worry about though. Best leave minutiae like that for the Semantic Nutters to argue about.

How do I use brew installed Python as the default Python?

Since High Sierra, you need to use:

sudo chown -R $(whoami) $(brew --prefix)/*

This is because /usr/local can no longer be chowned

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

OnClickListener in Android Studio

you will need to button initilzation inside method instead of trying to initlzing View's at class level do it as:

 Button button;  //<< declare here..

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.standingsButton); //<< initialize here
         // set OnClickListener for Button here
        button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
        }
      });
    }

Why can't I inherit static classes?

You can use composition instead... this will allow you to access class objects from the static type. But still cant implements interfaces or abstract classes

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

The correct answer that worked for me on CentOS is

/etc/init.d/mysql restart

which is an init script and not /etc/init.d/mysqld restart, which is binary

The is in fact comment of @MrTux on the question which worked for me. It took quite a bit of my time hence posting it as answer.

What is the difference between JVM, JDK, JRE & OpenJDK?

Another aspect worth mentioning:

JDK (java development kit)

You will need it for development purposes like the name suggests.

For example: a software company will have JDK install in their computer because they will need to develop new software which involves compiling and running their Java programs as well.

So we can say that JDK = JRE + JVM.

JRE (java run-time environment)

It's needed to run Java programs. You can't compile Java programs with it .

For example: a regular computer user who wants to run some online games then will need JRE in his system to run Java programs.

JVM (java virtual machine)

As you might know it run the bytecodes. It make Java platform independent because it executes the .class file which you get after you compile the Java program regardless of whether you compile it on Windows, Mac or Linux.

Open JDK

Well, like I said above. Now JDK is made by different company, one of them which happens to be an open source and free for public use is OpenJDK, while some others are Oracle Corporation's JRockit JDK or IBM JDK.

However they all might appear the same to general user.

Conclusion

If you are a Java programmer you will need JDK in your system and this package will include JRE and JVM as well but if you are normal user who like to play online games then you will only need JRE and this package will not have JDK in it.

In other words JDK is grandfather JRE is father and JVM is their son.

json_decode returns NULL after webservice call

I had the similar problem in a live site. In my local site it was working fine. For fixing the same I Just have added the below code

json_decode(stripslashes($_GET['arr']));

Android: Share plain text using intent (to all messaging apps)

100 % Working Code For Gmail Share

    Intent intent = new Intent (Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "Any subject if you want");
    intent.setPackage("com.google.android.gm");
    if (intent.resolveActivity(getPackageManager())!=null)
        startActivity(intent);
    else
        Toast.makeText(this,"Gmail App is not installed",Toast.LENGTH_SHORT).show();

Check if decimal value is null

you can use this code

if (DecimalVariable.Equals(null))  
{
   //something statements
}

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

How can I interrupt a running code in R with a keyboard command?

I know this is old, but I ran into the same issue. I'm on a Mac/Ubuntu and switch back and forth. What I have found is that just sending a simple interrupt signal to the main R process does exactly what you're looking for. I've ran scripts that went on for as long as 24 hours and the signal interrupt works very well. You should be able to run kill in terminal:

$ kill -2 pid

You can find the pid by running

$ps aux | grep exec/R

Not sure about Windows since I'm not ever on there, but I can't imagine there's not an option to do this as well in Command Prompt/Task Manager

Hope this helps!

Why did my Git repo enter a detached HEAD state?

It can happen if you have a tag named same as a branch.

Example: if "release/0.1" is tag name, then

git checkout release/0.1

produces detached HEAD at "release/0.1". If you expect release/0.1 to be a branch name, then you get confused.

Understanding __getitem__ method

The [] syntax for getting item by key or index is just syntax sugar.

When you evaluate a[i] Python calls a.__getitem__(i) (or type(a).__getitem__(a, i), but this distinction is about inheritance models and is not important here). Even if the class of a may not explicitly define this method, it is usually inherited from an ancestor class.

All the (Python 2.7) special method names and their semantics are listed here: https://docs.python.org/2.7/reference/datamodel.html#special-method-names

Difference in months between two dates

There are not a lot of clear answers on this because you are always assuming things.

This solution calculates between two dates the months between assuming you want to save the day of month for comparison, (meaning that the day of the month is considered in the calculation)

Example, if you have a date of 30 Jan 2012, 29 Feb 2012 will not be a month but 01 March 2013 will.

It's been tested pretty thoroughly, probably will clean it up later as we use it, but here:

private static int TotalMonthDifference(DateTime dtThis, DateTime dtOther)
{
    int intReturn = 0;
    bool sameMonth = false;

    if (dtOther.Date < dtThis.Date) //used for an error catch in program, returns -1
        intReturn--;

    int dayOfMonth = dtThis.Day; //captures the month of day for when it adds a month and doesn't have that many days
    int daysinMonth = 0; //used to caputre how many days are in the month

    while (dtOther.Date > dtThis.Date) //while Other date is still under the other
    {
        dtThis = dtThis.AddMonths(1); //as we loop, we just keep adding a month for testing
        daysinMonth = DateTime.DaysInMonth(dtThis.Year, dtThis.Month); //grabs the days in the current tested month

        if (dtThis.Day != dayOfMonth) //Example 30 Jan 2013 will go to 28 Feb when a month is added, so when it goes to march it will be 28th and not 30th
        {
            if (daysinMonth < dayOfMonth) // uses day in month max if can't set back to day of month
                dtThis.AddDays(daysinMonth - dtThis.Day);
            else
                dtThis.AddDays(dayOfMonth - dtThis.Day);
        }
        if (((dtOther.Year == dtThis.Year) && (dtOther.Month == dtThis.Month))) //If the loop puts it in the same month and year
        {
            if (dtOther.Day >= dayOfMonth) //check to see if it is the same day or later to add one to month
                intReturn++;
            sameMonth = true; //sets this to cancel out of the normal counting of month
        }
        if ((!sameMonth)&&(dtOther.Date > dtThis.Date))//so as long as it didn't reach the same month (or if i started in the same month, one month ahead, add a month)
            intReturn++;
    }
    return intReturn; //return month
}

Regular expression to detect semi-colon terminated C++ for & while loops

I don't know that regex would handle something like that very well. Try something like this

line = line.Trim();
if(line.StartsWith("for") && line.EndsWith(";")){
    //your code here
}

How to print out the method name and line number and conditionally disable NSLog?

To complement the answers above, it can be quite useful to use a replacement for NSLog in certain situations, especially when debugging. For example, getting rid of all the date and process name/id information on each line can make output more readable and faster to boot.

The following link provides quite a bit of useful ammo for making simple logging much nicer.

http://cocoaheads.byu.edu/wiki/a-different-nslog

Failed to allocate memory: 8

Referring to Android: failed to allocate memory and its first comment under accepted answer, changing "1024" to "1024MB" helped me. Pathetic, but works.

Is there any way to show a countdown on the lockscreen of iphone?

There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.

I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.

How to perform update operations on columns of type JSONB in Postgres 9.4

This is coming in 9.5 in the form of jsonb_set by Andrew Dunstan based on an existing extension jsonbx that does work with 9.4

ES6 export default with multiple functions referring to each other

One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.

export function foo() { console.log('foo') }, 
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }

In this case you are export all of the functions with names, so you could do

import * as fns from './foo';

to get an object with properties for each function instead of the import you'd use for your first example:

import fns from './foo';

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

Can I grep only the first n lines of a file?

You can use the following line:

head -n 10 /path/to/file | grep [...]

html vertical align the text inside input type button

You can use flexbox (check browser support, depending on your needs).

.testbutton {
  display: inline-flex;
  align-items: center; 
}

Adding a Method to an Existing Object Instance

What Jason Pratt posted is correct.

>>> class Test(object):
...   def a(self):
...     pass
... 
>>> def b(self):
...   pass
... 
>>> Test.b = b
>>> type(b)
<type 'function'>
>>> type(Test.a)
<type 'instancemethod'>
>>> type(Test.b)
<type 'instancemethod'>

As you can see, Python doesn't consider b() any different than a(). In Python all methods are just variables that happen to be functions.

PHP Accessing Parent Class Variable

Just echo it since it's inherited

echo $this->bb;

Convert string to date in Swift

  • Convert the ISO8601 string to date

    let isoDate = "2016-04-14T10:44:00+0000"
    
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let date = dateFormatter.date(from:isoDate)!
    
  • Get the date components for year, month, day and hour from the date

    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
    
  • Finally create a new Date object and strip minutes and seconds

    let finalDate = calendar.date(from:components)
    

Consider also the convenience formatter ISO8601DateFormatter introduced in iOS 10 / macOS 12:

let isoDate = "2016-04-14T10:44:00+0000"

let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!

How can I compare a date and a datetime in Python?

Here is another take, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:

datetime.datetime(d.year, d.month, d.day)

Suggestion:

from datetime import datetime

def ensure_datetime(d):
    """
    Takes a date or a datetime as input, outputs a datetime
    """
    if isinstance(d, datetime):
        return d
    return datetime.datetime(d.year, d.month, d.day)

def datetime_cmp(d1, d2):
    """
    Compares two timestamps.  Tolerates dates.
    """
    return cmp(ensure_datetime(d1), ensure_datetime(d2))

auto create database in Entity Framework Core

If you have created the migrations, you could execute them in the Startup.cs as follows.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
      using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
      {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.Migrate();
      }
      
      ...

This will create the database and the tables using your added migrations.

If you're not using Entity Framework Migrations, and instead just need your DbContext model created exactly as it is in your context class at first run, then you can use:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
      using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
      {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.EnsureCreated();
      }
      
      ...

Instead.

If you need to delete your database prior to making sure it's created, call:

            context.Database.EnsureDeleted();

Just before you call EnsureCreated()

Adapted from: http://docs.identityserver.io/en/latest/quickstarts/7_entity_framework.html?highlight=entity

How to start/stop/restart a thread in Java?

Sometimes if a Thread was started and it loaded a downside dynamic class which is processing with lots of Thread/currentThread sleep while ignoring interrupted Exception catch(es), one interrupt might not be enough to completely exit execution.

In that case, we can supply these loop-based interrupts:

while(th.isAlive()){
    log.trace("Still processing Internally; Sending Interrupt;");
    th.interrupt();
    try {
        Thread.currentThread().sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Can I replace groups in Java regex?

You can use matcher.start() and matcher.end() methods to get the group positions. So using this positions you can easily replace any text.

PackagesNotFoundError: The following packages are not available from current channels:

It may be that your condas channels need a wakeup call... with

conda update --all

For me it worked. More information: https://www.anaconda.com/keeping-anaconda-date/

Why is the Android emulator so slow? How can we speed up the Android emulator?

Good way to speed up Android Emulator and app testing is Install or Upgrade your Android Studio to Android Studio 2.0 version and then go to app open Settings/Preferences, the go to Build, Execution, Deployment ? Instant Run. Click on Enable Instant Run. And After That This will ensure you have the correct gradle plugin for your project to work with Instant Run. enter image description here

And Instant run will look like this New Run & Stop Actions in Android Studio for Instant Run

However Android Studio is right now in Preview you can try it now.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

I came here with the same Error, though one with a different origin.

It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.

An int type is expected, not a np.float64

Solution: Try to install numpy 1.11.0

sudo pip install -U numpy==1.11.0.

How to connect to remote Oracle DB with PL/SQL Developer?

I am facing to this problem so many times till I have 32bit PL/SQL Developer and 64bit Oracle DB or Oracle Client.

The solution is:

  1. install a 32bit client.
  2. set PLSQL DEV-Tools-Preferencies-Oracle Home to new 32bit client Home
  3. set PLSQL DEV-Tools-Preferencies-OCI to new 32 bit home /bin/oci.dll For example: c:\app\admin\product\11.2.0\client_1\BIN\oci.dll
  4. Save and restart PLSQL DEV.

Edit or create a TNSNAMES.ORA file in c:\app\admin\product\11.2.0\client_1\NETWORK\admin folder like mentioned above.

Try with TNSPING in console like

C:>tnsping ORCL

If still have problem, set the TNS_ADMIN Enviroment properties value pointing to the folder where the TNSNAMES.ORA located, like: c:\app\admin\product\11.2.0\client_1\network\admin

Upload failed You need to use a different version code for your APK because you already have one with version code 2

In my app/build.gradle file , version code was like this:-

build.gradle(app module) file

In place of versionCode flutterVersionCode.toInteger() , i replaced it with as versionCode 2

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

Go inside your phpMyAdmin directory inside XAMPP installation folder. There will be a file called config.inc.php. Inside that file, find this line:

$cfg['Servers'][$i]['password'] = '';

you must make sure that this field has your mysql root password (the one that you set).

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

What is middleware exactly?

Lets say your company makes 4 different products, your client has another 3 different products from another 3 different companies.

Someday the client thought, why don't we integrate all our systems into one huge system. Ten minutes later their IT department said that will take 2 years.

You (the wise developer) said, why don't we just integrate all the different systems and make them work together in a homogeneous environment? The client manager staring at you... You continued, we will use a Middleware, we will study the Inputs/Outputs of all different systems, the resources they use and then choose an appropriate Middleware framework.

Still explaining to the non tech manager
With Middleware framework in the middle, the first system will produce X stuff, the system Y and Z would consume those outputs and so on.

How to linebreak an svg text within javascript?

I suppese you alredy managed to solve it, but if someone is looking for similar solution then this worked for me:

 g.append('svg:text')
  .attr('x', 0)
  .attr('y', 30)
  .attr('class', 'id')
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 5)
  .text(function(d) { return d.name; })
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 20)
  .text(function(d) { return d.sname; })
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 20)
  .text(function(d) { return d.idcode; })

There are 3 lines separated with linebreak.

Android Studio: Unable to start the daemon process

I faced this issue in intellij idea and solved by doing this,

try to set "VM options" to -Xmx512m at Settings | Build, Execution, Deployment | Build Tools | Gradle | Gradle VM options

How to assign a NULL value to a pointer in python?

All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.

The python equivalent of NULL is called None (good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:

class Node:
    def __init__(self): #object initializer to set attributes (fields)
        self.val = 0
        self.right = None
        self.left = None

And then it works pretty much like you would expect:

node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()

Note that unlike in NULL in C, None is not a "pointer to nowhere": it is actually the only instance of class NoneType. Therefore, as None is a regular object, you can test for it just like any other object:

if node.left == None:
   print("The left node is None/Null.")

Although since None is a singleton instance, it is considered more idiomatic to use is and compare for reference equality:

if node.left is None:
   print("The left node is None/Null.")

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

pandas GroupBy columns with NaN (missing) values

I am not able to add a comment to M. Kiewisch since I do not have enough reputation points (only have 41 but need more than 50 to comment).

Anyway, just want to point out that M. Kiewisch solution does not work as is and may need more tweaking. Consider for example

>>> df = pd.DataFrame({'a': [1, 2, 3, 5], 'b': [4, np.NaN, 6, 4]})
>>> df
   a    b
0  1  4.0
1  2  NaN
2  3  6.0
3  5  4.0
>>> df.groupby(['b']).sum()
     a
b
4.0  6
6.0  3
>>> df.astype(str).groupby(['b']).sum()
      a
b
4.0  15
6.0   3
nan   2

which shows that for group b=4.0, the corresponding value is 15 instead of 6. Here it is just concatenating 1 and 5 as strings instead of adding it as numbers.

SSL Error: CERT_UNTRUSTED while using npm command

I had same problem and finally I understood that my node version is old. For example, you can install the current active LTS node version in Ubuntu by the following steps:

sudo apt-get update
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install nodejs -y

Installation instructions for more versions and systems can be found in the following link:

https://github.com/nodesource/distributions/blob/master/README.md

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Can I define a class name on paragraph using Markdown?

It should also be mentioned that <span> tags allow inside them -- block-level items negate MD natively inside them unless you configure them not to do so, but in-line styles natively allow MD within them. As such, I often do something akin to...

This is a superfluous paragraph thing.

<span class="class-red">And thus I delve into my topic, Lorem ipsum lollipop bubblegum.</span>

And thus with that I conclude.

I am not 100% sure if this is universal but seems to be the case in all MD editors I've used.

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

I'm new to tomcat, and this problem was driving me nuts today. It was sporadic. I asked a colleague to help, and the WAR expanded and it did was it was supposed to. 3 deploys later that day, it reverted back to the original version.

In my case, the MySite.WAR got expanded to both ROOT AND MySite. MySite was usually served up. But sometimes tomcat decided it liked the ROOT one better and all my changes disappeared.

The "solution" is to delete the ROOT website with every deploy of the war.

Bloomberg BDH function with ISIN

I had the same problem. Here's what I figured out:

=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")

A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.

How to "test" NoneType in python?

As pointed out by Aaron Hall's comment:

Since you can't subclass NoneType and since None is a singleton, isinstance should not be used to detect None - instead you should do as the accepted answer says, and use is None or is not None.


Original Answer:

The simplest way however, without the extra line in addition to cardamom's answer is probably:
isinstance(x, type(None))

So how can I question a variable that is a NoneType? I need to use if method

Using isinstance() does not require an is within the if-statement:

if isinstance(x, type(None)): 
    #do stuff

Additional information
You can also check for multiple types in one isinstance() statement as mentioned in the documentation. Just write the types as a tuple.

isinstance(x, (type(None), bytes))

What does 'low in coupling and high in cohesion' mean

An example might be helpful. Imagine a system which generates data and puts it into a data store, either a file on disk or a database.

High Cohesion can be achieved by separate the data store code from the data production code. (and in fact separating the disk storage from the database storage).

Low Coupling can be achieved by making sure that the data production doesn't have any unnecessary knowledge of the data store (e.g. doesn't ask the data store about filenames or db connections).

What is the height of Navigation Bar in iOS 7?

There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.

Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/

Download files in laravel using Response::download

This is html part

 <a href="{{route('download',$details->report_id)}}" type="button" class="btn btn-primary download" data-report_id="{{$details->report_id}}" >Download</a>

This is Route :

Route::get('/download/{id}', 'users\UserController@getDownload')->name('download')->middleware('auth');

This is function :

public function getDownload(Request $request,$id)
{
                $file= public_path(). "/pdf/";  //path of your directory
                $headers = array(
                    'Content-Type: application/pdf',
                );
                 return Response::download($file.$pdfName, 'filename.pdf', $headers);      
}

How do I convert strings between uppercase and lowercase in Java?

Yes. There are methods on the String itself for this.

Note that the result depends on the Locale the JVM is using. Beware, locales is an art in itself.

Generating random numbers with normal distribution in Excel

Rand() does generate a uniform distribution of random numbers between 0 and 1, but the norminv (or norm.inv) function is taking the uniform distributed Rand() as an input to generate the normally distributed sample set.

Xcode 7.2 no matching provisioning profiles found

Check your Keychain - look in Login and System keychains for expired certificates or error messages.

I found certs with "this certificate has an invalid user" error messages, and an expired Apple Worldwide Developer Relations Certificate.

Delete them and install the new AWDRC certificate from https://developer.apple.com/certificationauthority/AppleWWDRCA.cer

Then follow the accepted answer to get Xcode to use the new certificates.

How to parse a CSV file using PHP

Just discovered a handy way to get an index while parsing. My mind was blown.

$handle = fopen("test.csv", "r");
for ($i = 0; $row = fgetcsv($handle ); ++$i) {
    // Do something will $row array
}
fclose($handle);

Source: link

How to create number input field in Flutter?

For those who are looking for making TextField or TextFormField accept only numbers as input, try this code block :

for flutter 1.20 or newer versions

TextFormField(
              controller: _controller,
              keyboardType: TextInputType.number,
              inputFormatters: <TextInputFormatter>[
                FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
              ],
              decoration: InputDecoration(
                  labelText: "whatever you want",
                  hintText: "whatever you want",
                  icon: Icon(Icons.phone_iphone)))

for earlier versions of 1.20

TextFormField(
    controller: _controller,
    keyboardType: TextInputType.number,
    inputFormatters: <TextInputFormatter>[
        WhitelistingTextInputFormatter.digitsOnly
    ],
    decoration: InputDecoration(
        labelText:"whatever you want", 
        hintText: "whatever you want",
        icon: Icon(Icons.phone_iphone)
    )
)

How to manually update datatables table with new JSON data

SOLUTION: (Notice: this solution is for datatables version 1.10.4 (at the moment) not legacy version).

CLARIFICATION Per the API documentation (1.10.15), the API can be accessed three ways:

  1. The modern definition of DataTables (upper camel case):

    var datatable = $( selector ).DataTable();

  2. The legacy definition of DataTables (lower camel case):

    var datatable = $( selector ).dataTable().api();

  3. Using the new syntax.

    var datatable = new $.fn.dataTable.Api( selector );

Then load the data like so:

$.get('myUrl', function(newDataArray) {
    datatable.clear();
    datatable.rows.add(newDataArray);
    datatable.draw();
});

Use draw(false) to stay on the same page after the data update.

API references:

https://datatables.net/reference/api/clear()

https://datatables.net/reference/api/rows.add()

https://datatables.net/reference/api/draw()

No input file specified

Adding php5.ini doesn't work at all. But see the 'Disable FastCGI' section in this article on GoDaddy: http://support.godaddy.com/help/article/5121/changing-your-hosting-accounts-file-extensions

Add these lines to .htaccess files (webroot & website installation directory):

Options +ExecCGI
addhandler x-httpd-php5-cgi .php

It saves me a day! Cheers! Thanks DragonLord!

How can a query multiply 2 cell for each row MySQL?

I'm assuming this should work. This will actually put it in the column in your database

UPDATE yourTable yt SET yt.Total = (yt.Pieces * yt.Price)

If you want to retrieve the 2 values from the database and put your multiplication in the third column of the result only, then

SELECT yt.Pieces, yt.Price, (yt.Pieces * yt.Price) as 'Total' FROM yourTable yt

will be your friend

Create Map in Java

Java 9

public static void main(String[] args) {
    Map<Integer,String> map = Map.ofEntries(entry(1,"A"), entry(2,"B"), entry(3,"C"));
}

Select elements by attribute

simply:

$('input[name*="value"]')

more info: official docs

How to use LDFLAGS in makefile

In more complicated build scenarios, it is common to break compilation into stages, with compilation and assembly happening first (output to object files), and linking object files into a final executable or library afterward--this prevents having to recompile all object files when their source files haven't changed. That's why including the linking flag -lm isn't working when you put it in CFLAGS (CFLAGS is used in the compilation stage).

The convention for libraries to be linked is to place them in either LOADLIBES or LDLIBS (GNU make includes both, but your mileage may vary):

LDLIBS=-lm

This should allow you to continue using the built-in rules rather than having to write your own linking rule. For other makes, there should be a flag to output built-in rules (for GNU make, this is -p). If your version of make does not have a built-in rule for linking (or if it does not have a placeholder for -l directives), you'll need to write your own:

client.o: client.c
    $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ $<

client: client.o
    $(CC) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $@

How to find out what group a given user has?

Below is the script which is integrated into ansible and generating dashboard in CSV format.

sh collection.sh

#!/bin/bash

HOSTNAME=`hostname -s`

for i in `cat /etc/passwd| grep -vE "nologin|shutd|hal|sync|root|false"|awk -F':' '{print$1}' | sed 's/[[:space:]]/,/g'`; do groups $i; done|sed s/\:/\,/g|tr -d ' '|sed -e "s/^/$HOSTNAME,/"> /tmp/"$HOSTNAME"_inventory.txt

sudo cat /etc/sudoers| grep -v "^#"|awk '{print $1}'|grep -v Defaults|sed '/^$/d;s/[[:blank:]]//g'>/tmp/"$HOSTNAME"_sudo.txt

paste -d , /tmp/"$HOSTNAME"_inventory.txt /tmp/"$HOSTNAME"_sudo.txt|sed 's/,[[:blank:]]*$//g' >/tmp/"$HOSTNAME"_inventory_users.txt

My output stored in below text files.

cat /tmp/ANSIBLENODE_sudo.txt
cat /tmp/ANSIBLENODE_inventory.txt
cat /tmp/ANSIBLENODE_inventory_users.txt

Having trouble setting working directory

I just had this error message happen. When searching for why, I figured out that there's a related issue that can occur if you're not paying attention - the same error occurs if the directory you are trying to move into does not exist.

Ansible playbook shell output

I found using the minimal stdout_callback with ansible-playbook gave similar output to using ad-hoc ansible.

In your ansible.cfg (Note that I'm on OS X so modify the callback_plugins path to suit your install)

stdout_callback     = minimal
callback_plugins    = /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ansible/plugins/callback

So that a ansible-playbook task like yours

---
-
  hosts: example
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5

Gives output like this, like an ad-hoc command would

example | SUCCESS | rc=0 >>
%CPU USER     COMMAND
 0.2 root     sshd: root@pts/3
 0.1 root     /usr/sbin/CROND -n
 0.0 root     [xfs-reclaim/vda]
 0.0 root     [xfs_mru_cache]

I'm using ansible-playbook 2.2.1.0

"This project is incompatible with the current version of Visual Studio"

I checked if i could create a new solution and was unable because SSAS,SSIS and SSRS weren't there as options.

I downloaded SSDT from here and installed and it worked...

https://docs.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt?view=sql-server-2017

Const in JavaScript: when to use it and is it necessary?

There are two aspects to your questions: what are the technical aspects of using const instead of var and what are the human-related aspects of doing so.

The technical difference is significant. In compiled languages, a constant will be replaced at compile-time and its use will allow for other optimizations like dead code removal to further increase the runtime efficiency of the code. Recent (loosely used term) JavaScript engines actually compile JS code to get better performance, so using the const keyword would inform them that the optimizations described above are possible and should be done. This results in better performance.

The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error, var should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with const. If under different circumstances the information should change, use var to indicate that, even if the actual change doesn't appear in your code.

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

When we have a big/lengthy class say more than couple 100 lines of code we can't see everything on Monitor screen, hence we can't see overview (also called document items) of our class. Sometime we want to see overview of our class; its all methods, constants, properties etc at a glance. You can press Ctrl+6 in XCode to see overview of your class. You'll get a pop-up kind of Window aka Jump Bar.

By default, this jump bar doesn't have any buckets/sections. It's just one long list. (Though we can just start typing when jump Bar appears and it will search among jump bar items). Here comes the need of pragma mark

If you want to create sections in your Jump Bar then you can use pragma marks with relevant description. Now refer snapshot attached in question. There 'View lifeCycle' and 'A section dedicated ..' are sections created by pragma marks

Download all stock symbol list of a market

There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).

You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:

Company:  Vodafone
------------------
LSE symbol:    VOD
 in Google:    LON:VOD
 in Yahoo:     VOD.L
NASDAQ symbol: VOD
 in Google:    NASDAQ:VOD
 in Yahoo:     VOD

How to cast an object in Objective-C

((SelectionListViewController *)myEditController).list

More examples:

int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly

How do I override nested NPM dependency versions?

The only solution that worked for me (node 12.x, npm 6.x) was using npm-force-resolutions developed by @Rogerio Chaves.

First, install it by:

npm install npm-force-resolutions --save-dev

You can add --ignore-scripts if some broken transitive dependency scripts are blocking you from installing anything.

Then in package.json define what dependency should be overridden (you must set exact version number):

"resolutions": {
  "your-dependency-name": "1.23.4"
}

and in "scripts" section add new preinstall entry:

"preinstall": "npx npm-force-resolutions",

Now, npm install will apply changes and force your-dependency-name to be at version 1.23.4 for all dependencies.

Java: random long number in 0 <= x < n range

The methods using the r.nextDouble() should use:

long number = (long) (rand.nextDouble()*max);


long number = x+(((long)r.nextDouble())*(y-x));

How to declare a variable in a template in Angular

In case if you want to get the response of a function and set it into a variable, you can use it like the following in the template, using ng-container to avoid modifying the template.

<ng-container *ngIf="methodName(parameters) as respObject">
  {{respObject.name}}
</ng-container>

And the method in the component can be something like

methodName(parameters: any): any {
  return {name: 'Test name'};
}

How to change color in markdown cells ipython/jupyter notebook?

The text color can be changed using,

<span style='color:green'> message/text </span>

boundingRectWithSize for NSAttributedString returning wrong size

Ed McManus has certainly provided a key to getting this to work. I found a case that does not work

UIFont *font = ...
UIColor *color = ...
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                     font, NSFontAttributeName,
                                     color, NSForegroundColorAttributeName,
                                     nil];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString: someString attributes:attributesDictionary];

[string appendAttributedString: [[NSAttributedString alloc] initWithString: anotherString];

CGRect rect = [string boundingRectWithSize:constraint options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];

rect will not have the correct height. Notice that anotherString (which is appended to string) was initialized without an attribute dictionary. This is a legitimate initializer for anotherString but boundingRectWithSize: does not give an accurate size in this case.

How do I initialize an empty array in C#?

If you are going to use a collection that you don't know the size of in advance, there are better options than arrays.

Use a List<string> instead - it will allow you to add as many items as you need and if you need to return an array, call ToArray() on the variable.

var listOfStrings = new List<string>();

// do stuff...

string[] arrayOfStrings = listOfStrings.ToArray();

If you must create an empty array you can do this:

string[] emptyStringArray = new string[0]; 

Bootstrap select dropdown list placeholder

Try @title = "stuff". It worked for me.

Invoking Java main method with parameters from Eclipse

I'm not sure what your uses are, but I find it convenient that usually I use no more than several command line parameters, so each of those scenarios gets one run configuration, and I just pick the one I want from the Run History.

The feature you are suggesting seems a bit of an overkill, IMO.

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

If any Null value exists inside aggregate function you will face this issue. Instead of below code

 SELECT Count(closed)
  FROM   ticket
  WHERE  assigned_to = c.user_id
  AND closed IS NULL

use like

SELECT Count(ISNULL(closed, 0))
  FROM   ticket
  WHERE  assigned_to = c.user_id
  AND closed IS NULL

How to format a floating number to fixed width in Python

for x in numbers:
    print "{:10.4f}".format(x)

prints

   23.2300
    0.1233
    1.0000
    4.2230
 9887.2000

The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:

  • The empty string before the colon means "take the next provided argument to format()" – in this case the x as the only argument.
  • The 10.4f part after the colon is the format specification.
  • The f denotes fixed-point notation.
  • The 10 is the total width of the field being printed, lefted-padded by spaces.
  • The 4 is the number of digits after the decimal point.

Is it possible to program iPhone in C++

It may be a bit offtopic, but anyway. You can program c++ right on iOS devices. Check out CppCode ios app - http://cppcode.info. I believe it helps to learn c and c++ and objective-c later.

MySQL: Insert record if not exists in table

Worked :

INSERT INTO users (full_name, login, password) 
  SELECT 'Mahbub Tito','tito',SHA1('12345') FROM DUAL
WHERE NOT EXISTS 
  (SELECT login FROM users WHERE login='tito');

What does "O(1) access time" mean?

You're going to want to read up on Order of complexity.

http://en.wikipedia.org/wiki/Big_O_notation

In short, O(1) means that it takes a constant time, like 14 nanoseconds, or three minutes no matter the amount of data in the set.

O(n) means it takes an amount of time linear with the size of the set, so a set twice the size will take twice the time. You probably don't want to put a million objects into one of these.

Getting result of dynamic SQL into a variable for sql-server

 vMYQUERY := 'SELECT COUNT(*) FROM ALL_OBJECTS WHERE OWNER = UPPER(''MFI_IDBI2LIVE'') AND OBJECT_TYPE = ''TABLE'' 
    AND OBJECT_NAME  =''' || vTBL_CLIENT_MASTER || '''';
    PRINT_STRING(VMYQUERY);
    EXECUTE IMMEDIATE  vMYQUERY INTO VCOUNTTEMP ;

Types in MySQL: BigInt(20) vs Int(20)

Quote:

The "BIGINT(20)" specification isn't a digit limit. It just means that when the data is displayed, if it uses less than 20 digits it will be left-padded with zeros. 2^64 is the hard limit for the BIGINT type, and has 20 digits itself, hence BIGINT(20) just means everything less than 10^20 will be left-padded with spaces on display.

Where can I download IntelliJ IDEA Color Schemes?

The Solarized color theme (both light and dark versions) for IntelliJ IDEA is available here.

Solarized color theme for IntelliJ IDEA

Python Variable Declaration

Variables have scope, so yes it is appropriate to have variables that are specific to your function. You don't always have to be explicit about their definition; usually you can just use them. Only if you want to do something specific to the type of the variable, like append for a list, do you need to define them before you start using them. Typical example of this.

list = []
for i in stuff:
  list.append(i)

By the way, this is not really a good way to setup the list. It would be better to say:

list = [i for i in stuff] # list comprehension

...but I digress.

Your other question. The custom object should be a class itself.

class CustomObject(): # always capitalize the class name...this is not syntax, just style.
  pass
customObj = CustomObject()

What's the best way to determine which version of Oracle client I'm running?

You should put a semicolon at the end of select * from v$version;.

Like this you will get all info you need...

If you are looking just for Oracle for example you can do as:

SQL> select * from v$version where banner like 'Oracle%';

How can I create an observable with a delay

It's little late to answer ... but just in case may be someone return to this question looking for an answer

'delay' is property(function) of an Observable

fakeObservable = Observable.create(obs => {
  obs.next([1, 2, 3]);
  obs.complete();
}).delay(3000);

This worked for me ...

Why is Tkinter Entry's get function returning nothing?

You could also use a StringVar variable, even if it's not strictly necessary:

v = StringVar()

e = Entry(master, textvariable=v)
e.pack()

v.set("a default value")
s = v.get()

For more information, see this page on effbot.org.

Does a `+` in a URL scheme/host/path represent a space?

You can find a nice list of corresponding URL encoded characters on W3Schools.

  • + becomes %2B
  • space becomes %20

ORDER BY the IN value list

You can do it quite easily with (introduced in PostgreSQL 8.2) VALUES (), ().

Syntax will be like this:

select c.*
from comments c
join (
  values
    (1,1),
    (3,2),
    (2,3),
    (4,4)
) as x (id, ordering) on c.id = x.id
order by x.ordering

awk - concatenate two string variable and assign to a third

Concatenating strings in awk can be accomplished by the print command AWK manual page, and you can do complicated combination. Here I was trying to change the 16 char to A and used string concatenation:

echo    CTCTCTGAAATCACTGAGCAGGAGAAAGATT | awk -v w=15 -v BA=A '{OFS=""; print substr($0, 1, w), BA, substr($0,w+2)}'
Output: CTCTCTGAAATCACTAAGCAGGAGAAAGATT

I used the substr function to extract a portion of the input (STDIN). I passed some external parameters (here I am using hard-coded values) that are usually shell variable. In the context of shell programming, you can write -v w=$width -v BA=$my_charval. The key is the OFS which stands for Output Field Separate in awk. Print function take a list of values and write them to the STDOUT and glue them with the OFS. This is analogous to the perl join function.

It looks that in awk, string can be concatenated by printing variable next to each other:

echo xxx | awk -v a="aaa" -v b="bbb" '{ print a b $1 "string literal"}'
# will produce: aaabbbxxxstring literal

EPPlus - Read Excel Table

Below code will read excel data into a datatable, which is converted to list of datarows.

if (FileUpload1.HasFile)
{
    if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
    {
        Stream fs = FileUpload1.FileContent;
        ExcelPackage package = new ExcelPackage(fs);
        DataTable dt = new DataTable();
        dt= package.ToDataTable();
        List<DataRow> listOfRows = new List<DataRow>();
        listOfRows = dt.AsEnumerable().ToList();

    }
}
using OfficeOpenXml;
using System.Data;
using System.Linq;

 public static class ExcelPackageExtensions
    {
        public static DataTable ToDataTable(this ExcelPackage package)
        {
            ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
            DataTable table = new DataTable();
            foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
            {
                table.Columns.Add(firstRowCell.Text);
            }

            for (var rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
            {
                var row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];
                var newRow = table.NewRow();
                foreach (var cell in row)
                {
                    newRow[cell.Start.Column - 1] = cell.Text;
                }
                table.Rows.Add(newRow);
            }
            return table;
        }

    }

How to delete a record in Django models?

if you want to delete one instance then write the code

entry= Account.objects.get(id= 5)
entry.delete()

if you want to delete all instance then write the code

entries= Account.objects.all()
entries.delete()

How do I download a file from the internet to my linux server with Bash

I guess you could use curl and wget, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.

Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx, a text based browser.

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

To fix errors like:

It happened to me that the LocalContainerEntityManagerFactoryBean class did not have the setPackagesToScan method. Then I proceeded to use the @EntityScan annotation which doesn't work correctly.

Later I could find the method setPackagesToScan() but in another module, so the problem came from the dependency which did not have this method because it was an old version.

This method can be found in the spring-data-jpa or spring-orm dependency of updated versions:

From:

implementation("org.springframework", "spring-orm", "2.5.1") 

To:

implementation("org.springframework", "spring-orm", "5.2.9.RELEASE")

Or to:

implementation("org.springframework.data", "spring-data-jpa", "2.3.4.RELEASE")

In addition, it was not necessary to add other annotations other than that of @SprintBootApplication.

@SpringBootApplication
open class MoebiusApplication : SpringBootServletInitializer()

@Bean
open fun entityManagerFactory() : LocalContainerEntityManagerFactoryBean {
    val em = LocalContainerEntityManagerFactoryBean()
    em.dataSource = dataSource()
    em.setPackagesToScan("app.mobius.domain.entity")
    ... 
}

GL

Source

How to change the interval time on bootstrap carousel?

You can use the options when initializing the carousel, like this:

// interval is in milliseconds. 1000 = 1 second -> so 1000 * 10 = 10 seconds
$('.carousel').carousel({
  interval: 1000 * 10
});

or you can use the interval attribute directly on the HTML tag, like this:

<div class="carousel" data-interval="10000">

The advantage of the latter approach is that you do not have to write any JS for it - while the advantage of the former is that you can compute the interval and initialize it with a variable value at run time.

Insert current date in datetime format mySQL

NOW() is used to insert the current date and time in the MySQL table. All fields with datatypes DATETIME, DATE, TIME & TIMESTAMP work good with this function.

YYYY-MM-DD HH:mm:SS

Demonstration:

Following code shows the usage of NOW()

INSERT INTO auto_ins
(MySQL_Function, DateTime, Date, Time, Year, TimeStamp)
VALUES
(“NOW()”, NOW(), NOW(), NOW(), NOW(), NOW());

What is the point of "Initial Catalog" in a SQL Server connection string?

If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.

String variable interpolation Java

Note that there is no variable interpolation in Java. Variable interpolation is variable substitution with its value inside a string. An example in Ruby:

#!/usr/bin/ruby

age = 34
name = "William"

puts "#{name} is #{age} years old"

The Ruby interpreter automatically replaces variables with its values inside a string. The fact, that we are going to do interpolation is hinted by sigil characters. In Ruby, it is #{}. In Perl, it could be $, % or @. Java would only print such characters, it would not expand them.

Variable interpolation is not supported in Java. Instead of this, we have string formatting.

package com.zetcode;

public class StringFormatting 
{
    public static void main(String[] args) 
    {
        int age = 34;
        String name = "William";

        String output = String.format("%s is %d years old.", name, age);
    
        System.out.println(output);
    }
}

In Java, we build a new string using the String.format() method. The outcome is the same, but the methods are different.

See http://en.wikipedia.org/wiki/Variable_interpolation

Edit As of 2019, JEP 326 (Raw String Literals) was withdrawn and superseded by multiple JEPs eventually leading to JEP 378: Text Blocks delivered in Java 15.

A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.

However, still no string interpolation:

Non-Goals: … Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP. In the meantime, the new instance method String::formatted aids in situations where interpolation might be desired.

Can I hide/show asp:Menu items based on role?

To remove a MenuItem from an ASP.net NavigationMenu by Value:

public static void RemoveMenuItemByValue(MenuItemCollection items, String value)
{
   MenuItem itemToRemove = null;

   //Breadth first, look in the collection
   foreach (MenuItem item in items)
   {
      if (item.Value == value)
      {
          itemToRemove = item;
          break;
      }
   }

   if (itemToRemove != null)
   {
      items.Remove(itemToRemove);
      return;
   }


   //Search children
   foreach (MenuItem item in items)
   {
       RemoveMenuItemByValue(item.ChildItems, value);
   }
}

and helper extension:

public static RemoveMenuItemByValue(this NavigationMenu menu, String value)
{
   RemoveMenuItemByValue(menu.Items, value);
}

and sample usage:

navigationMenu.RemoveMenuItemByValue("UnitTests");

Note: Any code is released into the public domain. No attribution required.

Change width of select tag in Twitter Bootstrap

For me Pawan's css class combined with display: inline-block (so the selects don't stack) works best. And I wrap it in a media-query, so it stays Mobile Friendly:

@media (min-width: $screen-xs) {

    .selectwidthauto {
         width:auto !important;
         display: inline-block;
    }

}

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to read xls with explicit implementation poi classes for xlsx.

G:\Selenium Jar Files\TestData\Data.xls

Either use HSSFWorkbook and HSSFSheet classes or make your implementation more generic by using shared interfaces, like;

Change:

XSSFWorkbook workbook = new XSSFWorkbook(file);

To:

 org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);

And Change:

XSSFSheet sheet = workbook.getSheetAt(0);

To:

org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

How do I set the proxy to be used by the JVM

Combining Sorter's and javabrett/Leonel's answers:

java -Dhttp.proxyHost=10.10.10.10 -Dhttp.proxyPort=8080 -Dhttp.proxyUser=username -Dhttp.proxyPassword=password -jar myJar.jar

Python Matplotlib Y-Axis ticks on Right Side of Plot

Use ax.yaxis.tick_right()

for example:

from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()

enter image description here

Clearing NSUserDefaults

This code resets the defaults to the registration domain:

[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];

In other words, it removeObjectForKey for every single key you ever registered in that app.

Credits to Ken Thomases on this Apple Developer Forums thread.

MySQL Error 1093 - Can't specify target table for update in FROM clause

Try to save result of Select statement in separate variable and then use that for delete query.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

I'll leave the discussion of the difference between Build Tools, Platform Tools, and Tools to others. From a practical standpoint, you only need to know the answer to your second question:

Which version should be used?

Answer: Use the most recent version.

For those using Android Studio with Gradle, the buildToolsVersion has to be set in the build.gradle (Module: app) file.

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    ...
}

Where do I get the most recent version number of Build Tools?

Open the Android SDK Manager.

  • In Android Studio go to Tools > Android > SDK Manager > Appearance & Behavior > System Settings > Android SDK
  • Choose the SDK Tools tab.
  • Select Android SDK Build Tools from the list
  • Check Show Package Details.

The last item will show the most recent version.

enter image description here

Make sure it is installed and then write that number as the buildToolsVersion in build.gradle (Module: app).

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

Get size of a View in React Native

Here is the code to get the Dimensions of the complete view of the device.

var windowSize = Dimensions.get("window");

Use it like this:

width=windowSize.width,heigth=windowSize.width/0.565

How do I get the list of keys in a Dictionary?

You should be able to just look at .Keys:

    Dictionary<string, int> data = new Dictionary<string, int>();
    data.Add("abc", 123);
    data.Add("def", 456);
    foreach (string key in data.Keys)
    {
        Console.WriteLine(key);
    }

Fastest way to check if a string matches a regexp in ruby?

This is a simple benchmark:

require 'benchmark'

"test123" =~ /1/
=> 4
Benchmark.measure{ 1000000.times { "test123" =~ /1/ } }
=>   0.610000   0.000000   0.610000 (  0.578133)

"test123"[/1/]
=> "1"
Benchmark.measure{ 1000000.times { "test123"[/1/] } }
=>   0.718000   0.000000   0.718000 (  0.750010)

irb(main):019:0> "test123".match(/1/)
=> #<MatchData "1">
Benchmark.measure{ 1000000.times { "test123".match(/1/) } }
=>   1.703000   0.000000   1.703000 (  1.578146)

So =~ is faster but it depends what you want to have as a returned value. If you just want to check if the text contains a regex or not use =~

Count the items from a IEnumerable<T> without iterating?

Result of the IEnumerable.Count() function may be wrong. This is a very simple sample to test:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;

namespace Test
{
  class Program
  {
    static void Main(string[] args)
    {
      var test = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };
      var result = test.Split(7);
      int cnt = 0;

      foreach (IEnumerable<int> chunk in result)
      {
        cnt = chunk.Count();
        Console.WriteLine(cnt);
      }
      cnt = result.Count();
      Console.WriteLine(cnt);
      Console.ReadLine();
    }
  }

  static class LinqExt
  {
    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int chunkLength)
    {
      if (chunkLength <= 0)
        throw new ArgumentOutOfRangeException("chunkLength", "chunkLength must be greater than 0");

      IEnumerable<T> result = null;
      using (IEnumerator<T> enumerator = source.GetEnumerator())
      {
        while (enumerator.MoveNext())
        {
          result = GetChunk(enumerator, chunkLength);
          yield return result;
        }
      }
    }

    static IEnumerable<T> GetChunk<T>(IEnumerator<T> source, int chunkLength)
    {
      int x = chunkLength;
      do
        yield return source.Current;
      while (--x > 0 && source.MoveNext());
    }
  }
}

Result must be (7,7,3,3) but actual result is (7,7,3,17)

What does cmd /C mean?

/C Carries out the command specified by the string and then terminates.

You can get all the cmd command line switches by typing cmd /?.

java.net.SocketTimeoutException: Read timed out under Tomcat

I had the same problem while trying to read the data from the request body. In my case which occurs randomly only to the mobile-based client devices. So I have increased the connectionUploadTimeout to 1min as suggested by this link

Convert spark DataFrame column to python list

On my data I got these benchmarks:

>>> data.select(col).rdd.flatMap(lambda x: x).collect()

0.52 sec

>>> [row[col] for row in data.collect()]

0.271 sec

>>> list(data.select(col).toPandas()[col])

0.427 sec

The result is the same

How to read a file and write into a text file?

If you want to do it line by line:

Dim sFileText As String
Dim iInputFile As Integer, iOutputFile as integer

iInputFile = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iInputFile 
iOutputFile = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iOutputFile 
Do While Not EOF(iInputFile)
   Line Input #iInputFile , sFileText
   ' sFileTextis a single line of the original file
   ' you can append anything to it before writing to the other file
   Print #iOutputFile, sFileText 
Loop
Close #iInputFile 
Close #iOutputFile 

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

'It' requires a dll file called cvextern.dll . 'It' can be either your own cs file or some other third party dll which you are using in your project.

To call native dlls to your own cs file, copy the dll into your project's root\lib directory and add it as an existing item. (Add -Existing item) and use Dllimport with correct location.

For third party , copy the native library to the folder where the third party library resides and add it as an existing item.

After building make sure that the required dlls are appearing in Build folder. In some cases it may not appear or get replaced in Build folder. Delete the Build folder manually and build again.

How to implement the --verbose or -v option into a script?

What I need is a function which prints an object (obj), but only if global variable verbose is true, else it does nothing.

I want to be able to change the global parameter "verbose" at any time. Simplicity and readability to me are of paramount importance. So I would proceed as the following lines indicate:

ak@HP2000:~$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> verbose = True
>>> def vprint(obj):
...     if verbose:
...         print(obj)
...     return
... 
>>> vprint('Norm and I')
Norm and I
>>> verbose = False
>>> vprint('I and Norm')
>>> 

Global variable "verbose" can be set from the parameter list, too.

Dictionary with list of strings as value

I'd wrap the dictionary in another class:

public class MyListDictionary
{

    private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();

    public void Add(string key, string value)
    {
        if (this.internalDictionary.ContainsKey(key))
        {
            List<string> list = this.internalDictionary[key];
            if (list.Contains(value) == false)
            {
                list.Add(value);
            }
        }
        else
        {
            List<string> list = new List<string>();
            list.Add(value);
            this.internalDictionary.Add(key, list);
        }
    }

}

What is the best way to get all the divisors of a number?

For me this works fine and is also clean (Python 3)

def divisors(number):
    n = 1
    while(n<number):
        if(number%n==0):
            print(n)
        else:
            pass
        n += 1
    print(number)

Not very fast but returns divisors line by line as you wanted, also you can do list.append(n) and list.append(number) if you really want to

HTML -- two tables side by side

<div style="float: left;margin-right:10px">
  <table>
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>
<div style="float: left">
  <table>
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

Watching variables in SSIS during debug

Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?

Refused to apply inline style because it violates the following Content Security Policy directive

You can use in Content-security-policy add "img-src 'self' data:;" And Use outline CSS.Don't use Inline CSS.It's secure from attackers.

How to uninstall with msiexec using product id guid without .msi file present

Thanks all for the help - turns out it was a WiX issue.

When the Product ID GUID was left explicit & hardcoded as in the question, the resulting .msi had no ProductCode property but a Product ID property instead when inspected with orca.

Once I changed the GUID to '*' to auto-generate, the ProductCode showed up and all works fine with syntax confirmed by the other answers.

How can I store and retrieve images from a MySQL database using PHP?

Beware that serving images from DB is usually much, much much slower than serving them from disk.

You'll be starting a PHP process, opening a DB connection, having the DB read image data from the same disk and RAM for cache as filesystem would, transferring it over few sockets and buffers and then pushing out via PHP, which by default makes it non-cacheable and adds overhead of chunked HTTP encoding.

OTOH modern web servers can serve images with just few optimized kernel calls (memory-mapped file and that memory area passed to TCP stack), so that they don't even copy memory around and there's almost no overhead.

That's a difference between being able to serve 20 or 2000 images in parallel on one machine.

So don't do it unless you absolutely need transactional integrity (and actually even that can be done with just image metadata in DB and filesystem cleanup routines) and know how to improve PHP's handling of HTTP to be suitable for images.

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_