Programs & Examples On #Web sql

Web SQL Database is a SQL-based API allowing a web pages to store and retrieve structured data locally. It is based on, but not the same as SQLite.

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

In my case, uninstalling from Add&Remove Programs didn't work. Instead, the problem was due to a recently hotfix installed through automatic updates. The hotfix to VS 2008 (in my case) has the number KB952241, so I uninstalled it using Add/Remove Programs checking on the show updates option. After it was unistalled the problem was gone.

Create a day-of-week column in a Pandas dataframe using Python

Just in case if .dt doesn't work for you. Trying .DatetimeIndex might help. Hope the code and our test result here help you fix it. Regards,

import pandas as pd
import datetime

df = pd.DataFrame({'Date':['2015-01-01','2015-01-02','2015-01-03'],'Number':[1,2,3]})

df['Day'] = pd.DatetimeIndex(df['Date']).day_name() # week day name
df.head()

enter image description here

get the value of "onclick" with jQuery?

This works for me

 var link_click = $('#google').get(0).attributes.onclick.nodeValue;
 console.log(link_click);

Check if all values in list are greater than a certain number

There is a builtin function all:

all (x > limit for x in my_list)

Being limit the value greater than which all numbers must be.

Create an enum with string values

This works for me:

class MyClass {
    static MyEnum: { Value1; Value2; Value3; }
    = {
        Value1: "Value1",
        Value2: "Value2",
        Value3: "Value3"
    };
}

or

module MyModule {
    export var MyEnum: { Value1; Value2; Value3; }
    = {
        Value1: "Value1",
        Value2: "Value2",
        Value3: "Value3"
    };
}

8)

Update: Shortly after posting this I discovered another way, but forgot to post an update (however, someone already did mentioned it above):

enum MyEnum {
    value1 = <any>"value1 ", 
    value2 = <any>"value2 ", 
    value3 = <any>"value3 " 
}

For loop for HTMLCollection elements

Easy workaround that I always use

let list = document.getElementsByClassName("events");
let listArr = Array.from(list)

After this you can run any desired Array methods on the selection

listArr.map(item => console.log(item.id))
listArr.forEach(item => console.log(item.id))
listArr.reverse()

How do I make a redirect in PHP?

Use:

<?php header('Location: another-php-file.php'); exit(); ?>

Or if you've already opened PHP tags, use this:

header('Location: another-php-file.php'); exit();

You can also redirect to external pages, e.g.:

header('Location: https://www.google.com'); exit();

Make sure you include exit() or include die().

HTML5 form validation pattern alphanumeric with spaces?

Use this code to ensure the user doesn't just enter spaces but a valid name:

pattern="[a-zA-Z][a-zA-Z0-9\s]*"

how to align img inside the div to the right?

You can give the surrounding div a

text-align: right

this will leave white space to the left of the image. (= the image will occupy the whole line).

If you want content to be shown to the left hand side of the image, use

float: right

on the image. However, the surrounding div will then need overflow: auto to stretch to the needed height.

How do I copy an entire directory of files into an existing directory using Python?

The previous solution has some issue that src may overwrite dst without any notification or exception.

I add a predict_error method to predict errors before copy.copytree mainly base on Cyrille Pontvieux's version.

Using predict_error to predict all errors at first is best, unless you like to see exception raised one by another when execute copytree until fix all error.

def predict_error(src, dst):  
    if os.path.exists(dst):
        src_isdir = os.path.isdir(src)
        dst_isdir = os.path.isdir(dst)
        if src_isdir and dst_isdir:
            pass
        elif src_isdir and not dst_isdir:
            yield {dst:'src is dir but dst is file.'}
        elif not src_isdir and dst_isdir:
            yield {dst:'src is file but dst is dir.'}
        else:
            yield {dst:'already exists a file with same name in dst'}

    if os.path.isdir(src):
        for item in os.listdir(src):
            s = os.path.join(src, item)
            d = os.path.join(dst, item)
            for e in predict_error(s, d):
                yield e


def copytree(src, dst, symlinks=False, ignore=None, overwrite=False):
    '''
    would overwrite if src and dst are both file
    but would not use folder overwrite file, or viceverse
    '''
    if not overwrite:
        errors = list(predict_error(src, dst))
        if errors:
            raise Exception('copy would overwrite some file, error detail:%s' % errors)

    if not os.path.exists(dst):
        os.makedirs(dst)
        shutil.copystat(src, dst)
    lst = os.listdir(src)
    if ignore:
        excl = ignore(src, lst)
        lst = [x for x in lst if x not in excl]
    for item in lst:
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if symlinks and os.path.islink(s):
            if os.path.lexists(d):
                os.remove(d)
            os.symlink(os.readlink(s), d)
            try:
                st = os.lstat(s)
                mode = stat.S_IMODE(st.st_mode)
                os.lchmod(d, mode)
            except:
                pass  # lchmod not available
        elif os.path.isdir(s):
            copytree(s, d, symlinks, ignore)
        else:
            if not overwrite:
                if os.path.exists(d):
                    continue
            shutil.copy2(s, d)

Compile to a stand-alone executable (.exe) in Visual Studio

I don't think it is possible to do what the questioner asks which is to avoid dll hell by merging all the project files into one .exe.

The framework issue is a red herring. The problem that occurs is that when you have multiple projects depending on one library it is a PITA to keep the libraries in sync. Each time the library changes, all the .exes that depend on it and are not updated will die horribly.

Telling people to learn C as one response did is arrogant and ignorant.

List all of the possible goals in Maven 2?

The goal you indicate in the command line is linked to the lifecycle of Maven. For example, the build lifecycle (you also have the clean and site lifecycles which are different) is composed of the following phases:

  • validate: validate the project is correct and all necessary information is available.
  • compile: compile the source code of the project.
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run.
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally.
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

You can find the list of "core" plugins here, but there are plenty of others plugins, such as the codehaus ones, here.

jQuery - Appending a div to body, the body is the object?

jQuery methods returns the set they were applied on.

Use .appendTo:

var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');

Why should I prefer to use member initialization lists?

Just to add some additional info to demonstrate how much difference the member initialization list can mak. In the leetcode 303 Range Sum Query - Immutable, https://leetcode.com/problems/range-sum-query-immutable/, where you need to construct and initialize to zero a vector with certain size. Here is two different implementation and speed comparison.

Without member initialization list, to get AC it cost me about 212 ms.

class NumArray {
public:
vector<int> preSum;
NumArray(vector<int> nums) {
    preSum = vector<int>(nums.size()+1, 0);
    int ps = 0;
    for (int i = 0; i < nums.size(); i++)
    {
        ps += nums[i];
        preSum[i+1] = ps;
    }
}

int sumRange(int i, int j) {
    return preSum[j+1] - preSum[i];
}
};

Now using member initialization list, the time to get AC is about 108 ms. With this simple example, it is quite obvious that, member initialization list is way more efficient. All the measurement is from the running time from LC.

class NumArray {
public:
vector<int> preSum;
NumArray(vector<int> nums) : preSum(nums.size()+1, 0) { 
    int ps = 0;
    for (int i = 0; i < nums.size(); i++)
    {
        ps += nums[i];
        preSum[i+1] = ps;
    }
}

int sumRange(int i, int j) {
    return preSum[j+1] - preSum[i];
}
};

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

How to copy selected files from Android with adb pull

Pull multiple files using regex:

Create pullFiles.sh:

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION=".jpg"

for file in $(adb shell ls $DEVICE_DIR | grep $EXTENSION'$')
do
    file=$(echo -e $file | tr -d "\r\n"); # EOL fix
    adb pull $DEVICE_DIR/$file $HOST_DIR/$file;
done

Run it:

Make it executable: chmod +x pullFiles.sh

Run it: ./pullFiles.sh

Notes:

  • as is, won't work when filenames have spaces
  • includes a fix for end-of-line (EOL) on Android, which is a "\r\n"

PHP - Get key name of array value

If the name's dynamic, then you must have something like

$arr[$key]

which'd mean that $key contains the value of the key.

You can use array_keys() to get ALL the keys of an array, e.g.

$arr = array('a' => 'b', 'c' => 'd')
$x = array_keys($arr);

would give you

$x = array(0 => 'a', 1 => 'c');

Javascript Thousand Separator / string format

var number = 35002343;

console.log(number.toLocaleString());

for the reference you can check here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Get the current language in device

To add to Johan Pelgrim's answer

context.getResources().getConfiguration().locale
Locale.getDefault()

are equivalent because android.text.format.DateFormat class uses both interchangeably, e.g.

private static String zeroPad(int inValue, int inMinDigits) {
    return String.format(Locale.getDefault(), "%0" + inMinDigits + "d", inValue);
}

and

public static boolean is24HourFormat(Context context) {
    String value = Settings.System.getString(context.getContentResolver(),
            Settings.System.TIME_12_24);

    if (value == null) {
        Locale locale = context.getResources().getConfiguration().locale;

    // ... snip the rest ...
}

How to declare a type as nullable in TypeScript?

Just add a question mark ? to the optional field.

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

What is C# analog of C++ std::pair?

Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);

and access values through t.Item1 and t.Item2, you can simply do it like that:

(string message, int count) = ("Hello", 4);

or even:

(var message, var count) = ("Hello", 4);

Difference Between Select and SelectMany

One more example how SelectMany + Select can be used in order to accumulate sub array objects data.

Suppose we have users with they phones:

class Phone { 
    public string BasePart = "555-xxx-xxx"; 
}

class User { 
    public string Name = "Xxxxx";
    public List<Phone> Phones; 
}

Now we need to select all phones' BaseParts of all users:

var usersArray = new List<User>(); // array of arrays
List<string> allBaseParts = usersArray.SelectMany(ua => ua.Phones).Select(p => p.BasePart).ToList();

How to create an alert message in jsp page after submit process is complete

So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.

In test.jsp

Create a javascript

<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
} 
</script> 

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to

Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.

To do that i would highly recommendation to use session!

So what you want to do is in your servlet:

session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);

than in the test.jsp

<%
session.setMaxInactiveInterval(2);
%>

 <script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
    if (Msg != "null") {
 function alertName(){
 alert("Form has been submitted");
 } 
 }
 </script> 

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

So everytime you submit that form a session will be pass on! If session is not null the function will run!

How to dump only specific tables from MySQL?

Usage: mysqldump [OPTIONS] database [tables]

i.e.

mysqldump -u username -p db_name table1_name table2_name table3_name > dump.sql

Center an element with "absolute" position and undefined width in CSS?

This worked for me:

<div class="container><p>My text</p></div>

.container{
    position: absolute;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
}

Where is the documentation for the values() method of Enum?

Run this

    for (Method m : sex.class.getDeclaredMethods()) {
        System.out.println(m);
    }

you will see

public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()

These are all public methods that "sex" class has. They are not in the source code, javac.exe added them

Notes:

  1. never use sex as a class name, it's difficult to read your code, we use Sex in Java

  2. when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

How to execute .sql file using powershell?

Here is a function that I have in my PowerShell profile for loading SQL snapins:

function Load-SQL-Server-Snap-Ins
{
    try 
    {
        $sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

        if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
        {
            throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
        }

        $item = Get-ItemProperty $sqlpsreg
        $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

        $assemblyList = @(
            "Microsoft.SqlServer.Smo",
            "Microsoft.SqlServer.SmoExtended",
            "Microsoft.SqlServer.Dmf",
            "Microsoft.SqlServer.WmiEnum",
            "Microsoft.SqlServer.SqlWmiManagement",
            "Microsoft.SqlServer.ConnectionInfo ",
            "Microsoft.SqlServer.Management.RegisteredServers",
            "Microsoft.SqlServer.Management.Sdk.Sfc",
            "Microsoft.SqlServer.SqlEnum",
            "Microsoft.SqlServer.RegSvrEnum",
            "Microsoft.SqlServer.ServiceBrokerEnum",
            "Microsoft.SqlServer.ConnectionInfoExtended",
            "Microsoft.SqlServer.Management.Collector",
            "Microsoft.SqlServer.Management.CollectorEnum"
        )

        foreach ($assembly in $assemblyList)
        { 
            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly) 
            if ($assembly -eq $null)
                { Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
        }

        Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
        Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
        Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
        Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

        Push-Location

         if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null) 
        { 
            cd $sqlpsPath

            Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
            Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
            Update-TypeData -PrependPath SQLProvider.Types.ps1xml
            Update-FormatData -PrependPath SQLProvider.Format.ps1xml
        }
    } 

    catch 
    {
        Write-Host "`t`t$($MyInvocation.InvocationName): $_" 
    }

    finally
    {
        Pop-Location
    }
}

How should a model be structured in MVC?

Everything that is business logic belongs in a model, whether it is a database query, calculations, a REST call, etc.

You can have the data access in the model itself, the MVC pattern doesn't restrict you from doing that. You can sugar coat it with services, mappers and what not, but the actual definition of a model is a layer that handles business logic, nothing more, nothing less. It can be a class, a function, or a complete module with a gazillion objects if that's what you want.

It's always easier to have a separate object that actually executes the database queries instead of having them being executed in the model directly: this will especially come in handy when unit testing (because of the easiness of injecting a mock database dependency in your model):

class Database {
   protected $_conn;

   public function __construct($connection) {
       $this->_conn = $connection;
   }

   public function ExecuteObject($sql, $data) {
       // stuff
   }
}

abstract class Model {
   protected $_db;

   public function __construct(Database $db) {
       $this->_db = $db;
   }
}

class User extends Model {
   public function CheckUsername($username) {
       // ...
       $sql = "SELECT Username FROM" . $this->usersTableName . " WHERE ...";
       return $this->_db->ExecuteObject($sql, $data);
   }
}

$db = new Database($conn);
$model = new User($db);
$model->CheckUsername('foo');

Also, in PHP, you rarely need to catch/rethrow exceptions because the backtrace is preserved, especially in a case like your example. Just let the exception be thrown and catch it in the controller instead.

Converting LastLogon to DateTime format

Use the LastLogonDate property and you won't have to convert the date/time. lastLogonTimestamp should equal to LastLogonDate when converted. This way, you will get the last logon date and time across the domain without needing to convert the result.

Spring @ContextConfiguration how to put the right location for the xml

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"/Beans.xml"}) public class DemoTest{}

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

Javascript change color of text and background to input value

Things seems a little confused in the code in your question, so I am going to give you an example of what I think you are try to do.

First considerations are about mixing HTML, Javascript and CSS:

Why is using onClick() in HTML a bad practice?

Unobtrusive Javascript

Inline Styles vs Classes

I will be removing inline content and splitting these into their appropriate files.

Next, I am going to go with the "click" event and displose of the "change" event, as it is not clear that you want or need both.

Your function changeBackground sets both the backround color and the text color to the same value (your text will not be seen), so I am caching the color value as we don't need to look it up in the DOM twice.

CSS

#TheForm {
    margin-left: 396px;
}
#submitColor {
    margin-left: 48px;
    margin-top: 5px;
}

HTML

<form id="TheForm">
    <input id="color" type="text" />
    <br/>
    <input id="submitColor" value="Submit" type="button" />
</form>
<span id="coltext">This text should have the same color as you put in the text box</span>

Javascript

function changeBackground() {
    var color = document.getElementById("color").value; // cached

    // The working function for changing background color.
    document.bgColor = color;

    // The code I'd like to use for changing the text simultaneously - however it does not work.
    document.getElementById("coltext").style.color = color;
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Source: w3schools

Color Values

CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value that can be given to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).

Hex values are written as 3 double digit numbers, starting with a # sign.

Update: as pointed out by @Ian

Hex can be either 3 or 6 characters long

Source: W3C

Numerical color values

The format of an RGB value in hexadecimal notation is a ‘#’ immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.

Here is an alternative function that will check that your input is a valid CSS Hex Color, it will set the text color only or throw an alert if it is not valid.

For regex testing, I will use this pattern

/^#(?:[0-9a-f]{3}){1,2}$/i

but if you were regex matching and wanted to break the numbers into groups then you would require a different pattern

function changeBackground() {
    var color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i;

    if (rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Hex Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Here is a further modification that will allow colours by name along with by hex.

function changeBackground() {
    var names = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"],
        color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i,
        formattedName = color.charAt(0).toUpperCase() + color.slice(1).toLowerCase();

    if (names.indexOf(formattedName) !== -1 || rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

What is the easiest way to initialize a std::vector with hardcoded elements?

In C++11:

static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));

How to emit an event from parent to child?

In a parent component you can use @ViewChild() to access child component's method/variable.

@Component({
  selector: 'app-number-parent',
  templateUrl: './number-parent.component.html'
})
export class NumberParentComponent {
    @ViewChild(NumberComponent)
    private numberComponent: NumberComponent;
    increase() {
       this.numberComponent.increaseByOne();
    }
    decrease() {
       this.numberComponent.decreaseByOne();
    }
} 

Update:

Angular 8 onwards -

@ViewChild(NumberComponent, { static: false })

How to escape regular expression special characters using javascript?

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

how to get file path from sd card in android

There are different Names of SD-Cards.

This Code check every possible Name (I don't guarantee that these are all names but the most are included)

It prefers the main storage.

 private String SDPath() {
    String sdcardpath = "";

    //Datas
    if (new File("/data/sdext4/").exists() && new File("/data/sdext4/").canRead()){
        sdcardpath = "/data/sdext4/";
    }
    if (new File("/data/sdext3/").exists() && new File("/data/sdext3/").canRead()){
        sdcardpath = "/data/sdext3/";
    }
    if (new File("/data/sdext2/").exists() && new File("/data/sdext2/").canRead()){
        sdcardpath = "/data/sdext2/";
    }
    if (new File("/data/sdext1/").exists() && new File("/data/sdext1/").canRead()){
        sdcardpath = "/data/sdext1/";
    }
    if (new File("/data/sdext/").exists() && new File("/data/sdext/").canRead()){
        sdcardpath = "/data/sdext/";
    }

    //MNTS

    if (new File("mnt/sdcard/external_sd/").exists() && new File("mnt/sdcard/external_sd/").canRead()){
        sdcardpath = "mnt/sdcard/external_sd/";
    }
    if (new File("mnt/extsdcard/").exists() && new File("mnt/extsdcard/").canRead()){
        sdcardpath = "mnt/extsdcard/";
    }
    if (new File("mnt/external_sd/").exists() && new File("mnt/external_sd/").canRead()){
        sdcardpath = "mnt/external_sd/";
    }
    if (new File("mnt/emmc/").exists() && new File("mnt/emmc/").canRead()){
        sdcardpath = "mnt/emmc/";
    }
    if (new File("mnt/sdcard0/").exists() && new File("mnt/sdcard0/").canRead()){
        sdcardpath = "mnt/sdcard0/";
    }
    if (new File("mnt/sdcard1/").exists() && new File("mnt/sdcard1/").canRead()){
        sdcardpath = "mnt/sdcard1/";
    }
    if (new File("mnt/sdcard/").exists() && new File("mnt/sdcard/").canRead()){
        sdcardpath = "mnt/sdcard/";
    }

    //Storages
    if (new File("/storage/removable/sdcard1/").exists() && new File("/storage/removable/sdcard1/").canRead()){
        sdcardpath = "/storage/removable/sdcard1/";
    }
    if (new File("/storage/external_SD/").exists() && new File("/storage/external_SD/").canRead()){
        sdcardpath = "/storage/external_SD/";
    }
    if (new File("/storage/ext_sd/").exists() && new File("/storage/ext_sd/").canRead()){
        sdcardpath = "/storage/ext_sd/";
    }
    if (new File("/storage/sdcard1/").exists() && new File("/storage/sdcard1/").canRead()){
        sdcardpath = "/storage/sdcard1/";
    }
    if (new File("/storage/sdcard0/").exists() && new File("/storage/sdcard0/").canRead()){
        sdcardpath = "/storage/sdcard0/";
    }
    if (new File("/storage/sdcard/").exists() && new File("/storage/sdcard/").canRead()){
        sdcardpath = "/storage/sdcard/";
    }
    if (sdcardpath.contentEquals("")){
        sdcardpath = Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    Log.v("SDFinder","Path: " + sdcardpath);
    return sdcardpath;
}

Using SUMIFS with multiple AND OR conditions

You can use DSUM, which will be more flexible. Like if you want to change the name of Salesman or the Quote Month, you need not change the formula, but only some criteria cells. Please see the link below for details...Even the criteria can be formula to copied from other sheets

http://office.microsoft.com/en-us/excel-help/dsum-function-HP010342460.aspx?CTT=1

How to sort an array based on the length of each element?

We can use Array.sort method to sort this array.

ES5 solution

_x000D_
_x000D_
var array = ["ab", "abcdefgh", "abcd"];

array.sort(function(a, b){return b.length - a.length});

console.log(JSON.stringify(array, null, '\t'));
_x000D_
_x000D_
_x000D_

For ascending sort order: a.length - b.length

For descending sort order: b.length - a.length

ES6 solution

Attention: not all browsers can understand ES6 code!

In ES6 we can use an arrow function expressions.

_x000D_
_x000D_
let array = ["ab", "abcdefgh", "abcd"];

array.sort((a, b) => b.length - a.length);

console.log(JSON.stringify(array, null, '\t'));
_x000D_
_x000D_
_x000D_

Base64 Java encode and decode a string

The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries

Java 11 and up

import java.util.Base64;

public class Base64Encoding {

    public static void main(String[] args) {
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        String str = "77+9x6s=";

        // encode data using BASE64
        String encoded = enc.encodeToString(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data
        String decoded = new String(dec.decode(encoded));
        System.out.println("decoded value is \t" + decoded);
        System.out.println("original value is \t" + str);
    }
}

Java 6 - 10

import java.io.UnsupportedEncodingException;    
import javax.xml.bind.DatatypeConverter;

public class EncodeString64 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "77+9x6s=";
        // encode data using BASE64
        String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data 
        String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
        System.out.println("decoded value is \t" + decoded);

        System.out.println("original value is \t" + str);
    }
}

The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

Update TextView Every Second

If you want to show time on textview then better use Chronometer or TextClock

Using Chronometer:This was added in API 1. It has lot of option to customize it.

Your xml

<Chronometer
    android:id="@+id/chronometer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp" />

Your activity

Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();

Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.

Your xml

<TextClock
    android:id="@+id/textClock"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:format12Hour="hh:mm:ss a"
    android:gravity="center_horizontal"
    android:textColor="#d41709"
    android:textSize="44sp"
    android:textStyle="bold" />

Thats it, you are done.

You can use any of these two widgets. This will make your life easy.

VMware Workstation and Device/Credential Guard are not compatible

Well Boys and Girls after reading through the release notes for build 17093 in the wee small hours of the night, I have found the change point that affects my VMware Workstation VM's causing them not to work, it is the Core Isolation settings under Device Security under windows security (new name for windows defender page) in settings.

By default it is turned on, however when I turned it off and restarted my pc all my VMware VM's resumed working correctly. Perhaps a by device option could be incorporated in the next build to allow us to test individual devices / Apps responses to allow the core isolation to be on or off per device or App as required .

performSelector may cause a leak because its selector is unknown

@c-road provides the right link with problem description here. Below you can see my example, when performSelector causes a memory leak.

@interface Dummy : NSObject <NSCopying>
@end

@implementation Dummy

- (id)copyWithZone:(NSZone *)zone {
  return [[Dummy alloc] init];
}

- (id)clone {
  return [[Dummy alloc] init];
}

@end

void CopyDummy(Dummy *dummy) {
  __unused Dummy *dummyClone = [dummy copy];
}

void CloneDummy(Dummy *dummy) {
  __unused Dummy *dummyClone = [dummy clone];
}

void CopyDummyWithLeak(Dummy *dummy, SEL copySelector) {
  __unused Dummy *dummyClone = [dummy performSelector:copySelector];
}

void CloneDummyWithoutLeak(Dummy *dummy, SEL cloneSelector) {
  __unused Dummy *dummyClone = [dummy performSelector:cloneSelector];
}

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    Dummy *dummy = [[Dummy alloc] init];
    for (;;) { @autoreleasepool {
      //CopyDummy(dummy);
      //CloneDummy(dummy);
      //CloneDummyWithoutLeak(dummy, @selector(clone));
      CopyDummyWithLeak(dummy, @selector(copy));
      [NSThread sleepForTimeInterval:1];
    }} 
  }
  return 0;
}

The only method, which causes memory leak in my example is CopyDummyWithLeak. The reason is that ARC doesn't know, that copySelector returns retained object.

If you'll run Memory Leak Tool you can see the following picture: enter image description here ...and there are no memory leaks in any other case: enter image description here

Specify an SSH key for git push for a given domain

One Unix based systems (Linux, BSD, Mac OS X), the default identity is stored in the directory $HOME/.ssh, in 2 files: private key: $HOME/.ssh/id_rsa public key: $HOME/.ssh/id_rsa.pub When you use ssh without option -i, it uses the default private key to authenticate with remote system.

If you have another private key you want to use, for example $HOME/.ssh/deploy_key, you have to use ssh -i ~/.ssh/deploy_key ...

It is annoying. You can add the following lines in to your $HOME/.bash_profile : ssh-add ~/.ssh/deploy_key ssh-add ~/.ssh/id_rsa

So each time you use ssh or git or scp (basically ssh too), you don't have to use option -i anymore.

You can add as many keys as you like in the file $HOME/.bash_profile.

jQuery to loop through elements with the same class

Try this example

Html

<div class="testimonial" data-index="1">
    Testimonial 1
</div>
<div class="testimonial" data-index="2">
    Testimonial 2
</div>
<div class="testimonial" data-index="3">
    Testimonial 3
</div>
<div class="testimonial" data-index="4">
    Testimonial 4
</div>
<div class="testimonial" data-index="5">
    Testimonial 5
</div>

When we want to access those divs which has data-index greater than 2 then we need this jquery.

$('div[class="testimonial"]').each(function(index,item){
    if(parseInt($(item).data('index'))>2){
        $(item).html('Testimonial '+(index+1)+' by each loop');
    }
});

Working example fiddle

Django - "no module named django.core.management"

My case I used pyCharm 5 on mac. I also had this problem and after running this command my problem was solved

sudo pip install django --upgrade 

Intercept page exit event

Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:

window.onbeforeunload=function(e){
  // only take action (iterate) if my SCHEDULED_REQUEST object contains data        
  for (var key in SCHEDULED_REQUEST){   
    postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
    for (var i=0;i<1000;i++){
      // do something unnoticable but time consuming like writing a lot to console
      console.log('buying some time to finish saving data'); 
    };
    break;
  };
}; // no return string --> user will leave as normal but data is send to server

Edit: See also Synchronous_AJAX and how to do that with jquery

File path to resource in our war/WEB-INF folder?

Now with Java EE 7 you can find the resource more easily with

InputStream resource = getServletContext().getResourceAsStream("/WEB-INF/my.json");

https://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#getServletContext--

How to search through all Git and Mercurial commits in the repository for a certain string?

In addition to richq answer of using git log -g --grep=<regexp> or git grep -e <regexp> $(git log -g --pretty=format:%h): take a look at the following blog posts by Junio C Hamano, current git maintainer


Summary

Both git grep and git log --grep are line oriented, in that they look for lines that match specified pattern.

You can use git log --grep=<foo> --grep=<bar> (or git log --author=<foo> --grep=<bar> that internally translates to two --grep) to find commits that match either of patterns (implicit OR semantic).

Because of being line-oriented, the useful AND semantic is to use git log --all-match --grep=<foo> --grep=<bar> to find commit that has both line matching first and line matching second somewhere.

With git grep you can combine multiple patterns (all which must use the -e <regexp> form) with --or (which is the default), --and, --not, ( and ). For grep --all-match means that file must have lines that match each of alternatives.

How to center the elements in ConstraintLayout

The solution with guideline works only for this particular case with single line EditText. To make it work for multiline EditText you should use "packed" chain.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/client_id_input_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/authenticate"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/login_client_id"
            android:inputType="textEmailAddress" />

    </android.support.design.widget.TextInputLayout>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/authenticate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/login_auth"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="@id/client_id_input_layout"
        app:layout_constraintRight_toRightOf="@id/client_id_input_layout"
        app:layout_constraintTop_toBottomOf="@id/client_id_input_layout" />

</android.support.constraint.ConstraintLayout>

Here's how it looks:

View on Nexus 5

You can read more about using chains in following posts:

How to find substring inside a string (or how to grep a variable)?

You can use "index" if you only want to find a single character, e.g.:

LIST="server1 server2 server3 server4 server5"
SOURCE="3"
if expr index "$LIST" "$SOURCE"; then
    echo "match"
    exit -1
else
    echo "no match"
fi

Output is:

23
match

How to implement onBackPressed() in Fragments?

New and better approach: Following piece of code in a Fragment will help you to capture the back-press event.

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);

    OnBackPressedCallback callback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            Toast.makeText(mContext, "back pressed", Toast.LENGTH_SHORT).show();
            
            // And when you want to go back based on your condition
            if (yourCondition) {
                this.setEnabled(false);
                requireActivity().onBackPressed();
            }
        }
    };

    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}

Python Timezone conversion

import datetime
import pytz

def convert_datetime_timezone(dt, tz1, tz2):
    tz1 = pytz.timezone(tz1)
    tz2 = pytz.timezone(tz2)

    dt = datetime.datetime.strptime(dt,"%Y-%m-%d %H:%M:%S")
    dt = tz1.localize(dt)
    dt = dt.astimezone(tz2)
    dt = dt.strftime("%Y-%m-%d %H:%M:%S")

    return dt

-

  • dt: date time string
  • tz1: initial time zone
  • tz2: target time zone

-

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "PST8PDT")
'2017-05-13 05:56:32'

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "UTC")
'2017-05-13 12:56:32'

-

> pytz.all_timezones[0:10]
['Africa/Abidjan',
 'Africa/Accra',
 'Africa/Addis_Ababa',
 'Africa/Algiers',
 'Africa/Asmara',
 'Africa/Asmera',
 'Africa/Bamako',
 'Africa/Bangui',
 'Africa/Banjul',
 'Africa/Bissau']

How do I `jsonify` a list in Flask?

You can't but you can do it anyway like this. I needed this for jQuery-File-Upload

import json
# get this object
from flask import Response

#example data:

    js = [ { "name" : filename, "size" : st.st_size , 
        "url" : url_for('show', filename=filename)} ]
#then do this
    return Response(json.dumps(js),  mimetype='application/json')

Delete worksheet in Excel using VBA

Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete

if checkbox is checked, do this

It may happen that "this.checked" is always "on". Therefore, I recommend:

$('#checkbox').change(function() {
  if ($(this).is(':checked')) {
    console.log('Checked');
  } else {
    console.log('Unchecked');
  }
});

No notification sound when sending notification from firebase in android

The onMessageReceived method is fired only when app is in foreground or the notification payload only contains the data type.

From the Firebase docs

For downstream messaging, FCM provides two types of payload: notification and data.

For notification type, FCM automatically displays the message to end-user devices on behalf of the client app. Notifications have a predefined set of user-visible keys.
For data type, client app is responsible for processing data messages. Data messages have only custom key-value pairs.

Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.

Further down the docs

App behaviour when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.
When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
When in the foreground, your app receives a message object with both payloads available.

If you are using the firebase console to send notifications, the payload will always contain the notification type. You have to use the Firebase API to send the notification with only the data type in the notification payload. That way your app is always notified when a new notification is received and the app can handle the notification payload.

If you want to play notification sound when app is in background using the conventional method, you need to add the sound parameter to the notification payload.

Can you create nested WITH clauses for Common Table Expressions?

I was trying to measure the time between events with the exception of what one entry that has multiple processes between the start and end. I needed this in the context of other single line processes.

I used a select with an inner join as my select statement within the Nth cte. The second cte I needed to extract the start date on X and end date on Y and used 1 as an id value to left join to put them on a single line.

Works for me, hope this helps.

cte_extract
as 
(
    select ps.Process as ProcessEvent
        , ps.ProcessStartDate 
        , ps.ProcessEndDate 
        -- select strt.*
    from dbo.tbl_some_table ps 
    inner join (select max(ProcessStatusId) ProcessStatusId 
                    from dbo.tbl_some_table 
                where Process = 'some_extract_tbl' 
                and convert(varchar(10), ProcessStartDate, 112) < '29991231'
                ) strt on strt.ProcessStatusId = ps.ProcessStatusID
), 
cte_rls
as 
(
    select 'Sample' as ProcessEvent, 
     x.ProcessStartDate, y.ProcessEndDate  from (
    select 1 as Id, ps.Process as ProcessEvent
        , ps.ProcessStartDate 
        , ps.ProcessEndDate
        -- select strt.*
    from dbo.tbl_some_table ps 
    inner join (select max(ProcessStatusId) ProcessStatusId 
                    from dbo.tbl_some_table 
                where Process = 'XX Prcss' 
                and convert(varchar(10), ProcessStartDate, 112) < '29991231'
                ) strt on strt.ProcessStatusId = ps.ProcessStatusID
    ) x
    left join (
        select 1 as Id, ps.Process as ProcessEvent
            , ps.ProcessStartDate 
            , ps.ProcessEndDate
            -- select strt.*
        from dbo.tbl_some_table ps 
        inner join (select max(ProcessStatusId) ProcessStatusId
                    from dbo.tbl_some_table 
                    where Process = 'YY Prcss Cmpltd' 
                    and convert(varchar(10), ProcessEndDate, 112) < '29991231'
                    ) enddt on enddt.ProcessStatusId = ps.ProcessStatusID
            ) y on y.Id = x.Id 
),

.... other ctes

How do I get rid of the b-prefix in a string in python?

On python 3.6 with django 2.0, decode on a byte literal does not works as expected. Yeah i get the right result when i print it, but the b'value' is still there even if you print it right.

This is what im encoding

uid': urlsafe_base64_encode(force_bytes(user.pk)),

This is what im decoding:

uid = force_text(urlsafe_base64_decode(uidb64))

This is what django 2.0 says :

urlsafe_base64_encode(s)[source]

Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs.

urlsafe_base64_decode(s)[source]

Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped.


This is my account_activation_email_test.html file

{% autoescape off %}
Hi {{ user.username }},

Please click on the link below to confirm your registration:

http://{{ domain }}{% url 'accounts:activate' uidb64=uid token=token %}
{% endautoescape %}

This is my console response:

Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Activate Your MySite Account From: webmaster@localhost To: [email protected] Date: Fri, 20 Apr 2018 06:26:46 -0000 Message-ID: <152420560682.16725.4597194169307598579@Dash-U>

Hi testuser,

Please click on the link below to confirm your registration:

http://127.0.0.1:8000/activate/b'MjU'/4vi-fasdtRf2db2989413ba/

as you can see uid = b'MjU'

expected uid = MjU


test in console:

$ python
Python 3.6.4 (default, Apr  7 2018, 00:45:33) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
>>> from django.utils.encoding import force_bytes, force_text
>>> var1=urlsafe_base64_encode(force_bytes(3))
>>> print(var1)
b'Mw'
>>> print(var1.decode())
Mw
>>> 

After investigating it seems like its related to python 3. My workaround was quite simple:

'uid': user.pk,

i receive it as uidb64 on my activate function:

user = User.objects.get(pk=uidb64)

and voila:

Content-Transfer-Encoding: 7bit
Subject: Activate Your MySite Account
From: webmaster@localhost
To: [email protected]
Date: Fri, 20 Apr 2018 20:44:46 -0000
Message-ID: <152425708646.11228.13738465662759110946@Dash-U>


Hi testuser,

Please click on the link below to confirm your registration:

http://127.0.0.1:8000/activate/45/4vi-3895fbb6b74016ad1882/

now it works fine. :)

How to display pdf in php

Simple way to display pdf files from database and we can download it.
$resume is pdf file name which comes from database.
../resume/filename is path of folder where your file is stored.

<a href="../resumes/<?php echo $resume; ?>"/><?php echo $resume; ?></a>

How do I convert an interval into a number of hours with postgres?

         select date 'now()' - date '1955-12-15';

Here is the simple query which calculates total no of days.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

MySQL (and subsequently SQLite) also support the REPLACE INTO syntax:

REPLACE INTO my_table (pk_id, col1) VALUES (5, '123');

This automatically identifies the primary key and finds a matching row to update, inserting a new one if none is found.

Why cannot cast Integer to String in java?

Why this is not possible:

Because String and Integer are not in the same Object hierarchy.

      Object
     /      \
    /        \
String     Integer

The casting which you are trying, works only if they are in the same hierarchy, e.g.

      Object
     /
    /
   A
  /
 /
B

In this case, (A) objB or (Object) objB or (Object) objA will work.

Hence as others have mentioned already, to convert an integer to string use:

String.valueOf(integer), or Integer.toString(integer) for primitive,

or

Integer.toString() for the object.

Ruby on Rails: Where to define global constants?

According your condition, you can also define some environmental variables, and fetch it via ENV['some-var'] in ruby code, this solution may not fit for you, but I hope it may help others.

Example: you can create different files .development_env, .production_env, .test_env and load it according your application environments, check this gen dotenv-rails which automate this for your.

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

Is there a performance difference between a for loop and a for-each loop?

Even with something like an ArrayList or Vector, where "get" is a simple array lookup, the second loop still has additional overhead that the first one doesn't. I would expect it to be a tiny bit slower than the first.

Use String.split() with multiple delimiters

I'd use Apache Commons:

import org.apache.commons.lang3.StringUtils;

private void getId(String pdfName){
    String[] tokens = StringUtils.split(pdfName, "-.");
}

It'll split on any of the specified separators, as opposed to StringUtils.splitByWholeSeparator(str, separator) which uses the complete string as a separator

How to enter quotes in a Java string?

\ = \\

" = \"

new line = \r\n OR \n\r OR \n (depends on OS) bun usualy \n enough.

taabulator = \t

Merge two json/javascript arrays in to one array

You can use the new js spread operator if using es6:

_x000D_
_x000D_
var json1 = [{id:1, name: 'xxx'}]_x000D_
var json2 = [{id:2, name: 'xyz'}]_x000D_
var finalObj = [...json1, ...json2]_x000D_
_x000D_
console.log(finalObj)
_x000D_
_x000D_
_x000D_

Android: Tabs at the BOTTOM

This may not be exactly what you're looking for (it's not an "easy" solution to send your Tabs to the bottom of the screen) but is nevertheless an interesting alternative solution I would like to flag to you :

ScrollableTabHost is designed to behave like TabHost, but with an additional scrollview to fit more items ...

maybe digging into this open-source project you'll find an answer to your question. If I see anything easier I'll come back to you.

How to find the port for MS SQL Server 2008?

USE master
GO
xp_readerrorlog 0, 1, N'Server is listening on', 'any', NULL, NULL, N'asc' 
GO

[Identify Port used by Named Instance of SQL Server Database Engine by Reading SQL Server Error Logs]

How to make a cross-module variable?

Global variables are usually a bad idea, but you can do this by assigning to __builtins__:

__builtins__.foo = 'something'
print foo

Also, modules themselves are variables that you can access from any module. So if you define a module called my_globals.py:

# my_globals.py
foo = 'something'

Then you can use that from anywhere as well:

import my_globals
print my_globals.foo

Using modules rather than modifying __builtins__ is generally a cleaner way to do globals of this sort.

Get first and last day of month using threeten, LocalDate

YearMonth

For completeness, and more elegant in my opinion, see this use of YearMonth class.

YearMonth month = YearMonth.from(date);
LocalDate start = month.atDay(1);
LocalDate end   = month.atEndOfMonth();

For the first & last day of the current month, this becomes:

LocalDate start = YearMonth.now().atDay(1);
LocalDate end   = YearMonth.now().atEndOfMonth();

C# getting the path of %AppData%

For ASP.NET, the Load User Profile setting needs to be set on the app pool but that's not enough. There is a hidden setting named setProfileEnvironment in \Windows\System32\inetsrv\Config\applicationHost.config, which for some reason is turned off by default, instead of on as described in the documentation. You can either change the default or set it on your app pool. All the methods on the Environment class will then return proper values.

How can I run a windows batch file but hide the command window?

1,Download the bat to exe converter and install it 2,Run the bat to exe application 3,Download .pco images if you want to make good looking exe 4,specify the bat file location(c:\my.bat) 5,Specify the location for saving the exe(ex:c:/my.exe) 6,Select Version Information Tab 7,Choose the icon file (downloaded .pco image) 8,if you want fill the information like version,comapny name etc 9,change the tab to option 10,Select the invisible application(This will hide the command prompt while running the application) 11,Choose 32 bit(if you select 64 bit exe will work only in 32 bit OS) 12,Compile 13,Copy the exe to the location where bat file executed properly 14,Run the exe

Simple 3x3 matrix inverse code (C++)

I have just created a QMatrix class. It uses the built in vector > container. QMatrix.h It uses the Jordan-Gauss method to compute the inverse of a square matrix.

You can use it as follows:

#include "QMatrix.h"
#include <iostream>

int main(){
QMatrix<double> A(3,3,true);
QMatrix<double> Result = A.inverse()*A; //should give the idendity matrix

std::cout<<A.inverse()<<std::endl;
std::cout<<Result<<std::endl; // for checking
return 0;
}

The inverse function is implemented as follows:

Given a class with the following fields:

template<class T> class QMatrix{
public:
int rows, cols;
std::vector<std::vector<T> > A;

the inverse() function:

template<class T> 
QMatrix<T> QMatrix<T>:: inverse(){
Identity<T> Id(rows); //the Identity Matrix as a subclass of QMatrix.
QMatrix<T> Result = *this; // making a copy and transforming it to the Identity matrix
T epsilon = 0.000001;
for(int i=0;i<rows;++i){
    //check if Result(i,i)==0, if true, switch the row with another

    for(int j=i;j<rows;++j){
        if(std::abs(Result(j,j))<epsilon) { //uses Overloading()(int int) to extract element from Result Matrix
            Result.replace_rows(i,j+1); //switches rows i with j+1
        }
        else break;
    }
    // main part, making a triangular matrix
    Id(i)=Id(i)*(1.0/Result(i,i));
    Result(i)=Result(i)*(1.0/Result(i,i));  // Using overloading ()(int) to get a row form the matrix
    for(int j=i+1;j<rows;++j){
        T temp = Result(j,i);
        Result(j) = Result(j) - Result(i)*temp;
        Id(j) = Id(j) - Id(i)*temp; //doing the same operations to the identity matrix
        Result(j,i)=0; //not necessary, but looks nicer than 10^-15
    }
}

// solving a triangular matrix 
for(int i=rows-1;i>0;--i){
    for(int j=i-1;j>=0;--j){
        T temp = Result(j,i);
        Id(j) = Id(j) - temp*Id(i);
        Result(j)=Result(j)-temp*Result(i);
    }
}

return Id;
}

Lambda expression to convert array/List of String to array/List of Integers

EDIT: As pointed out in the comments, this is a much simpler version: Arrays.stream(stringArray).mapToInt(Integer::parseInt).toArray() This way we can skip the whole conversion to and from a list.


I found another one line solution, but it's still pretty slow (takes about 100 times longer than a for cycle - tested on an array of 6000 0's)

String[] stringArray = ...
int[] out= Arrays.asList(stringArray).stream().map(Integer::parseInt).mapToInt(i->i).toArray();

What this does:

  1. Arrays.asList() converts the array to a List
  2. .stream converts it to a Stream (needed to perform a map)
  3. .map(Integer::parseInt) converts all the elements in the stream to Integers
  4. .mapToInt(i->i) converts all the Integers to ints (you don't have to do this if you only want Integers)
  5. .toArray() converts the Stream back to an array

How does a hash table work?

This turns out to be a pretty deep area of theory, but the basic outline is simple.

Essentially, a hash function is just a function that takes things from one space (say strings of arbitrary length) and maps them to a space useful for indexing (unsigned integers, say).

If you only have a small space of things to hash, you might get away with just interpreting those things as integers, and you're done (e.g. 4 byte strings)

Usually, though, you've got a much larger space. If the space of things you allow as keys is bigger than the space of things you are using to index (your uint32's or whatever) then you can't possibly have a unique value for each one. When two or more things hash to the same result, you'll have to handle the redundancy in an appropriate way (this is usually referred to as a collision, and how you handle it or don't will depend a bit on what you are using the hash for).

This implies you want it to be unlikely to have the same result, and you probably also would really like the hash function to be fast.

Balancing these two properties (and a few others) has kept many people busy!

In practice you usually should be able to find a function that is known to work well for your application and use that.

Now to make this work as a hashtable: Imagine you didn't care about memory usage. Then you can create an array as long as your indexing set (all uint32's, for example). As you add something to the table, you hash it's key and look at the array at that index. If there is nothing there, you put your value there. If there is already something there, you add this new entry to a list of things at that address, along with enough information (your original key, or something clever) to find which entry actually belongs to which key.

So as you go a long, every entry in your hashtable (the array) is either empty, or contains one entry, or a list of entries. Retrieving is a simple as indexing into the array, and either returning the value, or walking the list of values and returning the right one.

Of course in practice you typically can't do this, it wastes too much memory. So you do everything based on a sparse array (where the only entries are the ones you actually use, everything else is implicitly null).

There are lots of schemes and tricks to make this work better, but that's the basics.

How to parse a CSV file in Bash?

If you want to read CSV file with some lines, so this the solution.

while IFS=, read -ra line
do 
    test $i -eq 1 && ((i=i+1)) && continue
    for col_val in ${line[@]}
    do
        echo -n "$col_val|"                 
    done
    echo        
done < "$csvFile"

How do I validate a date in rails?

If you want Rails 3 or Ruby 1.9 compatibility try the date_validator gem.

How to test abstract class in Java with JUnit?

If you have no concrete implementations of the class and the methods aren't static whats the point of testing them? If you have a concrete class then you'll be testing those methods as part of the concrete class's public API.

I know what you are thinking "I don't want to test these methods over and over thats the reason I created the abstract class", but my counter argument to that is that the point of unit tests is to allow developers to make changes, run the tests, and analyze the results. Part of those changes could include overriding your abstract class's methods, both protected and public, which could result in fundamental behavioral changes. Depending on the nature of those changes it could affect how your application runs in unexpected, possibly negative ways. If you have a good unit testing suite problems arising from these types changes should be apparent at development time.

How to load/reference a file as a File instance from the classpath

This also works, and doesn't require a /path/to/file URI conversion. If the file is on the classpath, this will find it.

File currFile = new File(getClass().getClassLoader().getResource("the_file.txt").getFile());

What is "Linting"?

Linting is the process of running a program that will analyse code for potential errors.

See lint on wikipedia:

lint was the name originally given to a particular program that flagged some suspicious and non-portable constructs (likely to be bugs) in C language source code. The term is now applied generically to tools that flag suspicious usage in software written in any computer language.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

I ran into the same issue and the above answers didn't help. I need to debug and find it.

 <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.6.0-cdh5.13.1</version>
        <exclusions>
            <exclusion>
                <artifactId>jsp-api</artifactId>
                <groupId>javax.servlet.jsp</groupId>
            </exclusion>
        </exclusions>
    </dependency>

After excluding the jsp-api, it worked for me.

What is the most effective way for float and double comparison?

I write this for java, but maybe you find it useful. It uses longs instead of doubles, but takes care of NaNs, subnormals, etc.

public static boolean equal(double a, double b) {
    final long fm = 0xFFFFFFFFFFFFFL;       // fraction mask
    final long sm = 0x8000000000000000L;    // sign mask
    final long cm = 0x8000000000000L;       // most significant decimal bit mask
    long c = Double.doubleToLongBits(a), d = Double.doubleToLongBits(b);        
    int ea = (int) (c >> 52 & 2047), eb = (int) (d >> 52 & 2047);
    if (ea == 2047 && (c & fm) != 0 || eb == 2047 && (d & fm) != 0) return false;   // NaN 
    if (c == d) return true;                            // identical - fast check
    if (ea == 0 && eb == 0) return true;                // ±0 or subnormals
    if ((c & sm) != (d & sm)) return false;             // different signs
    if (abs(ea - eb) > 1) return false;                 // b > 2*a or a > 2*b
    d <<= 12; c <<= 12;
    if (ea < eb) c = c >> 1 | sm;
    else if (ea > eb) d = d >> 1 | sm;
    c -= d;
    return c < 65536 && c > -65536;     // don't use abs(), because:
    // There is a posibility c=0x8000000000000000 which cannot be converted to positive
}
public static boolean zero(double a) { return (Double.doubleToLongBits(a) >> 52 & 2047) < 3; }

Keep in mind that after a number of floating-point operations, number can be very different from what we expect. There is no code to fix that.

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

Regarding client timeouts and the use of XACT_ABORT to handle them, in my opinion there is at least one very good reason to have timeouts in client APIs like SqlClient, and that is to guard the client application code from deadlocks occurring in SQL server code. In this case the client code has no fault, but has to protect it self from blocking forever waiting for the command to complete on the server. So conversely, if client timeouts have to exist to protect client code, so does XACT_ABORT ON has to protect server code from client aborts, in case the server code takes longer to execute than the client is willing to wait for.

How to call a method after bean initialization is complete?

To further clear any confusion about the two approach i.e use of

  1. @PostConstruct and
  2. init-method="init"

From personal experience, I realized that using (1) only works in a servlet container, while (2) works in any environment, even in desktop applications. So, if you would be using Spring in a standalone application, you would have to use (2) to carry out that "call this method after initialization.

swift 3.0 Data to String?

I found the way to do it. You need to convert Data to NSData:

let characterSet = CharacterSet(charactersIn: "<>")
let nsdataStr = NSData.init(data: deviceToken)
let deviceStr = nsdataStr.description.trimmingCharacters(in: characterSet).replacingOccurrences(of: " ", with: "")
print(deviceStr)

How do we check if a pointer is NULL pointer?

Apparently the thread you refer is about C++.

In C your snippet will always work. I like the simpler if (p) { /* ... */ }.

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

I got this problem too. I have solved this issue already. If u are using Wamp then perform the following steps.

  1. Go to wamp64/www/bin/php/php* (where * is the php version you are using)
  2. Edit file php and uncomment this line by removing the semicolon:
;extension=pdo_pgsql to extension=pdo_pgsql
  1. Save and restart your Wamp server

If it does not work, please check your .env and config/database again.

Get current value selected in dropdown using jQuery

This is what you need :)

$('._someDropDown').live('change', function(e) {
    console.log(e.target.options[e.target.selectedIndex].text);
});

For new jQuery use on

$(document).on('change', '._someDropDown', function(e) {
    console.log(this.options[e.target.selectedIndex].text);
});

jQuery UI autocomplete with JSON

You need to transform the object you are getting back into an array in the format that jQueryUI expects.

You can use $.map to transform the dealers object into that array.

$('#dealerName').autocomplete({
    source: function (request, response) {
        $.getJSON("/example/location/example.json?term=" + request.term, function (data) {
            response($.map(data.dealers, function (value, key) {
                return {
                    label: value,
                    value: key
                };
            }));
        });
    },
    minLength: 2,
    delay: 100
});

Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label and value properties that $.map's callback function return.

Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:

  • Is an array of objects that have a label property, a value property, or both, or
  • Is a simple array of strings

In other words, if you can format the data like this:

[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]

or this:

["dealer 5", "dealer 6"]

Then your JavaScript becomes much simpler:

$('#dealerName').autocomplete({
    source: "/example/location/example.json"
});

How do I get information about an index and table owner in Oracle?

Below are two simple query using which you can check index created on a table in Oracle.

select index_name
  from dba_indexes
 where table_name='&TABLE_NAME'
   and owner='&TABLE_OWNER';
select index_name 
  from user_indexes 
 where table_name='&TABLE_NAME';

Please check for more details and index size below. Index on a table and its size in Oracle

How to convert nanoseconds to seconds using the TimeUnit enum?

You should write :

    long startTime = System.nanoTime();        
    long estimatedTime = System.nanoTime() - startTime;

Assigning the endTime in a variable might cause a few nanoseconds. In this approach you will get the exact elapsed time.

And then:

TimeUnit.SECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS)

Setting selection to Nothing when programming Excel

Tried all your suggestions, no luck , but here's an idea that worked for me select a cell out of your selection range (say AAA1000000) and then select the A1 again

Range("AAA1000000").Activate

Range("A1").Activate

Guy

Convert generic List/Enumerable to DataTable?

To Convert Generic list into DataTable

using Newtonsoft.Json;

public DataTable GenericToDataTable(IList<T> list)
{
    var json = JsonConvert.SerializeObject(list);
    DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
    return dt;
}

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

Angular 2 filter/search list

Slight modification to @Mosche answer, for handling if there exist no filter element.

TS:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'filterFromList'
})
export class FilterPipe implements PipeTransform {
    public transform(value, keys: string, term: string) {

        if (!term) {
            return value
        }
        let res = (value || []).filter((item) => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));
        return res.length ? res : [-1];

    }
}

Now, in your HTML you can check via '-1' value, for no results.

HTML:

<div *ngFor="let item of list | filterFromList: 'attribute': inputVariableModel">
            <mat-list-item *ngIf="item !== -1">
                <h4 mat-line class="inline-block">
                 {{item}}
                </h4>
            </mat-list-item>
            <mat-list-item *ngIf="item === -1">
                No Matches
            </mat-list-item>
        </div>

PHP: HTML: send HTML select option attribute in POST

just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:

<form name='add'>
Age: <select name='age'>
     <option value='1_sre'>23</option>
     <option value='2_sam>24</option>
     <option value='5_john>25</option>
     </select>
<input type='submit' name='submit'/>
</form>

Convert row names into first column

You can both remove row names and convert them to a column by reference (without reallocating memory using ->) using setDT and its keep.rownames = TRUE argument from the data.table package

library(data.table)
setDT(df, keep.rownames = TRUE)[]
#    rn     VALUE  ABS_CALL DETECTION     P.VALUE
# 1:  1 1007_s_at  957.7292         P 0.004862793
# 2:  2   1053_at  320.6327         P 0.031335632
# 3:  3    117_at  429.8423         P 0.017000453
# 4:  4    121_at 2395.7364         P 0.011447358
# 5:  5 1255_g_at  116.4936         A 0.397993682
# 6:  6   1294_at  739.9271         A 0.066864977

As mentioned by @snoram, you can give the new column any name you want, e.g. setDT(df, keep.rownames = "newname") would add "newname" as the rows column.

How generate unique Integers based on GUIDs

A GUID is a 128 bit integer (its just in hex rather than base 10). With .NET 4 use http://msdn.microsoft.com/en-us/library/dd268285%28v=VS.100%29.aspx like so:

// Turn a GUID into a string and strip out the '-' characters.
BigInteger huge = BigInteger.Parse(modifiedGuidString, NumberStyles.AllowHexSpecifier)

If you don't have .NET 4 you can look at IntX or Solver Foundation.

Using FileSystemWatcher to monitor a directory

The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

How to dynamically build a JSON object with Python?

You can create the Python dictionary and serialize it to JSON in one line and it's not even ugly.

my_json_string = json.dumps({'key1': val1, 'key2': val2})

Change tab bar item selected color in a storyboard

You can also set selected image bar tint color by key path:

enter image description here

Hope this will help you!! Thanks

Need to find a max of three numbers in java

Two things: Change the variables x, y, z as int and call the method as Math.max(Math.max(x,y),z) as it accepts two parameters only.

In Summary, change below:

    String x = keyboard.nextLine();
    String y = keyboard.nextLine();
    String z = keyboard.nextLine();
    int max = Math.max(x,y,z);

to

    int x = keyboard.nextInt();
    int y = keyboard.nextInt();
    int z = keyboard.nextInt();
    int max =  Math.max(Math.max(x,y),z);

Delete all the queues from RabbitMQ?

There's a way to remove all queues and exchanges without scripts and full reset. You can just delete and re-create a virtual host from admin interface. This will work even for vhost /.

The only thing you'll need to restore is permissions for the newly created vhost.

Changing datagridview cell color based on condition

Without looping it can be achived like below.

private void dgEvents_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {

        FormatRow(dgEvents.Rows[e.RowIndex]);

    }

private void FormatRow(DataGridViewRow myrow)
    {
        try
        {
            if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Error")
            {
                myrow.DefaultCellStyle.BackColor = Color.Red;
            }
            else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Warning")
            {
                myrow.DefaultCellStyle.BackColor = Color.Yellow;
            }
            else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Information")
            {
                myrow.DefaultCellStyle.BackColor = Color.LightGreen;
            }
        }
        catch (Exception exception)
        {
            onLogs?.Invoke(exception.Message, EventArgs.Empty);
        }
    }

Angular 2 Routing run in new tab

In my use case, I wanted to asynchronously retrieve a url, and then follow that url to an external resource in a new window. A directive seemed overkill because I don't need reusability, so I simply did:

<button (click)="navigateToResource()">Navigate</button>

And in my component.ts

navigateToResource(): void {
  this.service.getUrl((result: any) => window.open(result.url));
}


Note:

Routing to a link indirectly like this will likely trigger the browser's popup blocker.

Support for the experimental syntax 'classProperties' isn't currently enabled

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ],
    "plugins": [
        [
          "@babel/plugin-proposal-class-properties"
        ]
    ]
}

replace your .babelrc file with above code. it fixed the issue for me.

I can't access http://localhost/phpmyadmin/

Or it could be that Skype is running on the same port (it does by default).

Disable Skype or configure Skype to use another port

How to schedule a function to run every hour on Flask?

I've tried using flask instead of a simple apscheduler what you need to install is

pip3 install flask_apscheduler

Below is the sample of my code:

from flask import Flask
from flask_apscheduler import APScheduler

app = Flask(__name__)
scheduler = APScheduler()

def scheduleTask():
    print("This test runs every 3 seconds")

if __name__ == '__main__':
    scheduler.add_job(id = 'Scheduled Task', func=scheduleTask, trigger="interval", seconds=3)
    scheduler.start()
    app.run(host="0.0.0.0")

Compare integer in bash, unary operator expected

I need to add my 5 cents. I see everybody use [ or [[, but it worth to mention that they are not part of if syntax.

For arithmetic comparisons, use ((...)) instead.

((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.

See: ArithmeticExpression

Split / Explode a column of dictionaries into separate columns with pandas

I strongly recommend the method extract the column 'Pollutants':

df_pollutants = pd.DataFrame(df['Pollutants'].values.tolist(), index=df.index)

it's much faster than

df_pollutants = df['Pollutants'].apply(pd.Series)

when the size of df is giant.

When to use MongoDB or other document oriented database systems?

In NoSQL: If Only It Was That Easy, the author writes about MongoDB:

MongoDB is not a key/value store, it’s quite a bit more. It’s definitely not a RDBMS either. I haven’t used MongoDB in production, but I have used it a little building a test app and it is a very cool piece of kit. It seems to be very performant and either has, or will have soon, fault tolerance and auto-sharding (aka it will scale). I think Mongo might be the closest thing to a RDBMS replacement that I’ve seen so far. It won’t work for all data sets and access patterns, but it’s built for your typical CRUD stuff. Storing what is essentially a huge hash, and being able to select on any of those keys, is what most people use a relational database for. If your DB is 3NF and you don’t do any joins (you’re just selecting a bunch of tables and putting all the objects together, AKA what most people do in a web app), MongoDB would probably kick ass for you.

Then, in the conclusion:

The real thing to point out is that if you are being held back from making something super awesome because you can’t choose a database, you are doing it wrong. If you know mysql, just use it. Optimize when you actually need to. Use it like a k/v store, use it like a rdbms, but for god sake, build your killer app! None of this will matter to most apps. Facebook still uses MySQL, a lot. Wikipedia uses MySQL, a lot. FriendFeed uses MySQL, a lot. NoSQL is a great tool, but it’s certainly not going to be your competitive edge, it’s not going to make your app hot, and most of all, your users won’t care about any of this.

What am I going to build my next app on? Probably Postgres. Will I use NoSQL? Maybe. I might also use Hadoop and Hive. I might keep everything in flat files. Maybe I’ll start hacking on Maglev. I’ll use whatever is best for the job. If I need reporting, I won’t be using any NoSQL. If I need caching, I’ll probably use Tokyo Tyrant. If I need ACIDity, I won’t use NoSQL. If I need a ton of counters, I’ll use Redis. If I need transactions, I’ll use Postgres. If I have a ton of a single type of documents, I’ll probably use Mongo. If I need to write 1 billion objects a day, I’d probably use Voldemort. If I need full text search, I’d probably use Solr. If I need full text search of volatile data, I’d probably use Sphinx.

I like this article, I find it very informative, it gives a good overview of the NoSQL landscape and hype. But, and that's the most important part, it really helps to ask yourself the right questions when it comes to choose between RDBMS and NoSQL. Worth the read IMHO.

Alternate link to article

How do I automatically play a Youtube video (IFrame API) muted?

The accepted answer works pretty good. I wanted more control so I added a couple of functions more to the script:

function unmuteVideo() {
    player.unMute();
    return false;
  }
  function muteVideo() {
    player.mute();
    return false;
  }
  function setVolumeVideo(volume) {
    player.setVolume(volume);
    return false;
  }

And here is the HTML:

<br>
<button type="button" onclick="unmuteVideo();">Unmute Video</button>
<button type="button" onclick="muteVideo();">Mute Video</button>
<br>
<br>
<button type="button" onclick="setVolumeVideo(100);">Volume 100%</button>
<button type="button" onclick="setVolumeVideo(75);">Volume 75%</button>
<button type="button" onclick="setVolumeVideo(50);">Volume 50%</button>
<button type="button" onclick="setVolumeVideo(25);">Volume 25%</button>

Now you have more control of the sound... Check the reference URL for more:

YouTube IFrame Player API

"Cannot start compilation: the output path is not specified for module..."

After this

Two things to do:

Project Settings > Project compiler output > Set it as "Project path(You actual project's path)”+”\out”.

Project Settings > Module > Path > Choose "Inherit project compile path""

If button ran is not active

You must reload IDEA

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

I guess it depends on what you want. For simple objects, I guess you could use the second methods. When your objects grow larger and you're planning on using similar objects, I guess the first method would be better. That way you can also extend it using prototypes.

Example:

function Circle(radius) {
    this.radius = radius;
}
Circle.prototype.getCircumference = function() {
    return Math.PI * 2 * this.radius;
};
Circle.prototype.getArea = function() {
    return Math.PI * this.radius * this.radius;
}

I am not a big fan of the third method, but it's really useful for dynamically editing properties, for example var foo='bar'; var bar = someObject[foo];.

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

iOS 7 - Status bar overlaps the view

I have posted my answer to another post with the same question with this one.

From Apple iOS7 transition Guide, https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/TransitionGuide/AppearanceCustomization.html#//apple_ref/doc/uid/TP40013174-CH15-SW1

Specifically automaticallyAdjustsScrollViewInsets=YES and set self.edgesForExtendedLayout = UIRectEdgeNone works for me when I don't want to the overlap and I have a tableviewcontroller.

ffprobe or avprobe not found. Please install one

There is some confusion when using pip install in Windows. The instructions talk about a specific folder which has youtube-dl.exe. There is no such folder if you use pip install.

The solution is to:

  • Download one of the builds from https://ffmpeg.zeranoe.com/
  • Extract the zip contents
  • Place the contents of the bin folder (there are three exe files) in any folder which is a path in Windows. I personally use Ananconda, so I placed them in /Anaconda/Scripts, but you could place it in any folder and add that folder to the path.

Make a directory and copy a file

You can use the shell for this purpose.

Set shl = CreateObject("WScript.Shell") 
shl.Run "cmd mkdir YourDir" & copy "

Does Index of Array Exist

// I'd modify this slightly to be more resilient to a bad parameter
// it will handle your case and better handle other cases given to it:

int index = 25;

if (index >= 0 && index < array.Length)
{
    // Array element found
}

Why does cURL return error "(23) Failed writing body"?

For me, it was permission issue. Docker run is called with a user profile but root is the user inside the container. The solution was to make curl write to /tmp since that has write permission for all users , not just root.

I used the -o option.

-o /tmp/file_to_download

How to make a copy of an object in C#

You can use MemberwiseClone

obj myobj2 = (obj)myobj.MemberwiseClone();

The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj are of value types.

If you own the source code, you can also implement ICloneable

How do I compare two strings in python?

I am going to provide several solutions and you can choose the one that meets your needs:

1) If you are concerned with just the characters, i.e, same characters and having equal frequencies of each in both the strings, then use:

''.join(sorted(string1)).strip() == ''.join(sorted(string2)).strip()

2) If you are also concerned with the number of spaces (white space characters) in both strings, then simply use the following snippet:

sorted(string1) == sorted(string2)

3) If you are considering words but not their ordering and checking if both the strings have equal frequencies of words, regardless of their order/occurrence, then can use:

sorted(string1.split()) == sorted(string2.split())

4) Extending the above, if you are not concerned with the frequency count, but just need to make sure that both the strings contain the same set of words, then you can use the following:

set(string1.split()) == set(string2.split())

Any free WPF themes?

There are some Microsoft Themes in the WPF page on CodePlex:

CodePlex - Windows Presentation Foundation

Bootstrap with jQuery Validation Plugin

For full compatibility with Bootstrap 3 I added support for input-group, radio and checkbox, that was missing in the other solutions.

Update 10/20/2017: Inspected suggestions of the other answers and added additional support for special markup of radio-inline, better error placement for a group of radios or checkboxes and added support for a custom .novalidation class to prevent validation of controls. Hope this helps and thanks for the suggestions.

After including the validation plugin add the following call:

$.validator.setDefaults({
    errorElement: "span",
    errorClass: "help-block",
    highlight: function (element, errorClass, validClass) {
        // Only validation controls
        if (!$(element).hasClass('novalidation')) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        }
    },
    unhighlight: function (element, errorClass, validClass) {
        // Only validation controls
        if (!$(element).hasClass('novalidation')) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        }
    },
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        }
        else if (element.prop('type') === 'radio' && element.parent('.radio-inline').length) {
            error.insertAfter(element.parent().parent());
        }
        else if (element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
            error.appendTo(element.parent().parent());
        }
        else {
            error.insertAfter(element);
        }
    }
});

This works for all Bootstrap 3 form classes. If you use a horizontal form you have to use the following markup. This ensures that the help-block text respects the validation states ("has-error", ...) of the form-group.

<div class="form-group">
    <div class="col-lg-12">
        <div class="checkbox">
            <label id="LabelConfirm" for="CheckBoxConfirm">
                <input type="checkbox" name="CheckBoxConfirm" id="CheckBoxConfirm" required="required" />
                I have read all the information 
            </label>
        </div>
    </div>
</div>

Convert pyQt UI to python

Update for anyone using PyQt5 with python 3.x:

  1. Open terminal (eg. Powershell, cmd etc.)
  2. cd into the folder with your .ui file.
  3. Type: "C:\python\Lib\site-packages\PyQt5\pyuic5.bat" -x Trial.ui -o trial_gui.py for cases where PyQt5 is not a path variable. The path in quotes " " represents where the pyuic5.bat file is.

This should work!

How to easily map c++ enums to strings

I'd be tempted to have a map m - and embedd this into the enum.

setup with m[MyEnum.VAL1] = "Value 1";

and all is done.

Get method arguments using Spring AOP?

you can get method parameter and its value and if annotated with a annotation with following code:

Map<String, Object> annotatedParameterValue = getAnnotatedParameterValue(MethodSignature.class.cast(jp.getSignature()).getMethod(), jp.getArgs()); ....

private Map<String, Object> getAnnotatedParameterValue(Method method, Object[] args) {
        Map<String, Object> annotatedParameters = new HashMap<>();
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        Parameter[] parameters = method.getParameters();

        int i = 0;
        for (Annotation[] annotations : parameterAnnotations) {
            Object arg = args[i];
            String name = parameters[i++].getDeclaringExecutable().getName();
            for (Annotation annotation : annotations) {
                if (annotation instanceof AuditExpose) {
                    annotatedParameters.put(name, arg);
                }
            }
        }
        return annotatedParameters;
    }

Where is git.exe located?

Appears to have moved again in the latest version of GH for windows to:

%USERPROFILE%\AppData\Local\GitHubDesktop\app-[gfw-version]\resources\app\git\cmd\git.exe

Given it now has the version in the folder structure i think it will move every time it auto-updates. This makes it impossible to put into path. I think the best option is to install git separately.

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

I explain this to users by comparing Perforce changelists to a stack (from data structures).

Backing out removes one item from anywhere in the stack.

Rolling back removes n items from the top of the stack.

C# List of objects, how do I get the sum of a property

Here is example code you could run to make such test:

var f = 10000000;
var p = new int[f];

for(int i = 0; i < f; ++i)
{
    p[i] = i % 2;
}

var time = DateTime.Now;
p.Sum();
Console.WriteLine(DateTime.Now - time);

int x = 0;
time = DateTime.Now;
foreach(var item in p){
   x += item;
}
Console.WriteLine(DateTime.Now - time);

x = 0;
time = DateTime.Now;
for(int i = 0, j = f; i < j; ++i){
   x += p[i];
}
Console.WriteLine(DateTime.Now - time);

The same example for complex object is:

void Main()
{
    var f = 10000000;
    var p = new Test[f];

    for(int i = 0; i < f; ++i)
    {
        p[i] = new Test();
        p[i].Property = i % 2;
    }

    var time = DateTime.Now;
    p.Sum(k => k.Property);
    Console.WriteLine(DateTime.Now - time);

    int x = 0;
    time = DateTime.Now;
    foreach(var item in p){
        x += item.Property;
    }
    Console.WriteLine(DateTime.Now - time);

    x = 0;
    time = DateTime.Now;
    for(int i = 0, j = f; i < j; ++i){
        x += p[i].Property;
    }
    Console.WriteLine(DateTime.Now - time);
}

class Test
{
    public int Property { get; set; }
}

My results with compiler optimizations off are:

00:00:00.0570370 : Sum()
00:00:00.0250180 : Foreach()
00:00:00.0430272 : For(...)

and for second test are:

00:00:00.1450955 : Sum()
00:00:00.0650430 : Foreach()
00:00:00.0690510 : For()

it looks like LINQ is generally slower than foreach(...) but what is weird for me is that foreach(...) appears to be faster than for loop.

How to change indentation in Visual Studio Code?

Setting the indentation in preferences isn't allways the solution. Most of the time the indentation is right except you happen to copy some code code from other sources or your collegue make something for you and has different settings. Then you want to just quickly convert the indentation from 2 to 4 or the other way round.

That's what this vscode extension is doing for you

enter image description here

difference between css height : 100% vs height : auto

height:100% works if the parent container has a specified height property else, it won't work

How to change date format in JavaScript

Try -

var monthNames = [ "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December" ];

var newDate = new Date(form.startDate.value);
var formattedDate = monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear();

Change default icon

The Icon property for a project specifies the icon file (.ico) that will be displayed for the compiled application in Windows Explorer and in the Windows taskbar.

The Icon property can be accessed in the Application pane of the Project Designer; it contains a list of icons that have been added to a project either as resources or as content files.

To specify an application icon

  1. With a project selected in Solution Explorer, on the Project menu click Properties.
  2. Select the Application pane.
  3. Select an icon (.ico) file from the Icon drop-down list.

To specify an application icon and add it to your project

  1. With a project selected in Solution Explorer, on the Project menu, click Properties.
  2. Select the Application pane.
  3. Select Browse from the Icon drop-down list and browse to the location of the icon file that you want.

The icon file is added to your project as a content file and can be seen on top left corner.

And if you want to show separate icons for every form you have to go to each form's properties, select icon attribute and browse for an icon you want.

Here's MSDN link for the same purpose...

Hope this helps.

c++ boost split string

My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:

-----------test2-------test3

What happened is the machine actually printed this:

test-------test2-------test3\r-------

That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).

JavaScript get element by name

All Answers here seem to be outdated. Please use this now:

document.querySelector("[name='acc']");
document.querySelector("[name='pass']")

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

-xms is the start memory (at the VM start), -xmx is the maximum memory for the VM

  • eclipse.ini : the memory for the VM running eclipse
  • jre setting : the memory for java programs run from eclipse
  • catalina.sh : the memory for your tomcat server

Unable to find a @SpringBootConfiguration when doing a JpaTest

In addition to what Thomas Kåsene said, you can also add

@SpringBootTest(classes=com.package.path.class)

to the test annotation to specify where it should look for the other class if you didn't want to refactor your file hierarchy. This is what the error message hints at by saying:

Unable to find a @SpringBootConfiguration, you need to use 
@ContextConfiguration or @SpringBootTest(classes=...) ...

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

I create simple method for that

popBackStack(getSupportFragmentManager());

Than place it in my ActivityUtils class

public static void popBackStack(FragmentManager manager){
        FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
        manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

It's work great, have fun!

Apache Spark: The number of cores vs. the number of executors

To hopefully make all of this a little more concrete, here’s a worked example of configuring a Spark app to use as much of the cluster as possible: Imagine a cluster with six nodes running NodeManagers, each equipped with 16 cores and 64GB of memory. The NodeManager capacities, yarn.nodemanager.resource.memory-mb and yarn.nodemanager.resource.cpu-vcores, should probably be set to 63 * 1024 = 64512 (megabytes) and 15 respectively. We avoid allocating 100% of the resources to YARN containers because the node needs some resources to run the OS and Hadoop daemons. In this case, we leave a gigabyte and a core for these system processes. Cloudera Manager helps by accounting for these and configuring these YARN properties automatically.

The likely first impulse would be to use --num-executors 6 --executor-cores 15 --executor-memory 63G. However, this is the wrong approach because:

63GB + the executor memory overhead won’t fit within the 63GB capacity of the NodeManagers. The application master will take up a core on one of the nodes, meaning that there won’t be room for a 15-core executor on that node. 15 cores per executor can lead to bad HDFS I/O throughput.

A better option would be to use --num-executors 17 --executor-cores 5 --executor-memory 19G. Why?

This config results in three executors on all nodes except for the one with the AM, which will have two executors. --executor-memory was derived as (63/3 executors per node) = 21. 21 * 0.07 = 1.47. 21 – 1.47 ~ 19.

The explanation was given in an article in Cloudera's blog, How-to: Tune Your Apache Spark Jobs (Part 2).

show more/Less text with just HTML and JavaScript

Hope this Code you are looking for HTML:

            <div class="showmore">
                <div class="shorten_txt">
                    <h4> #@item.Title</h4>
                    <p>Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text </p>
                </div>
            </div>

SCRIPT:

    var showChar = 100;
    var ellipsestext = "[...]";
    $('.showmore').each(function () {
        $(this).find('.shorten_txt p').addClass('more_p').hide();
        $(this).find('.shorten_txt p:first').removeClass('more_p').show();
        $(this).find('.shorten_txt ul').addClass('more_p').hide();
        //you can do this above with every other element
        var teaser = $(this).find('.shorten_txt p:first').html();
        var con_length = parseInt(teaser.length);
        var c = teaser.substr(0, showChar);
        var h = teaser.substr(showChar, con_length - showChar);
        var html = '<span class="teaser_txt">' + c + '<span class="moreelipses">' + ellipsestext +
        '</span></span><span class="morecontent_txt">' + h
        + '</span>';
        if (con_length > showChar) {
            $(this).find(".shorten_txt p:first").html(html);
            $(this).find(".shorten_txt p:first span.morecontent_txt").toggle();
        }
    });
    $(".showmore").click(function () {
        if ($(this).hasClass("less")) {
            $(this).removeClass("less");
        } else {
            $(this).addClass("less");
        }
        $(this).find('.shorten_txt p:first span.moreelipses').toggle();
        $(this).find('.shorten_txt p:first span.morecontent_txt').toggle();
        $(this).find('.shorten_txt .more_p').toggle();
        return false;
    });

How to prevent favicon.ico requests?

You can use .htaccess or server directives to deny access to favicon.ico, but the server will send an access denied reply to the browser and this still slows page access.

You can stop the browser requesting favicon.ico when a user returns to your site, by getting it to stay in the browser cache.

First, provide a small favicon.ico image, could be blank, but as small as possible. I made a black and white one under 200 bytes. Then, using .htaccess or server directives, set the file Expires header a month or two in the future. When the same user comes back to your site it will be loaded from the browser cache and no request will go to your site. No more 404's in the server logs too.

If you have control over a complete Apache server or maybe a virtual server you can do this:-

If the server document root is say /var/www/html then add this to /etc/httpd/conf/httpd.conf:-

Alias /favicon.ico "/var/www/html/favicon.ico"
<Directory "/var/www/html">
    <Files favicon.ico>
       ExpiresActive On
       ExpiresDefault "access plus 1 month"
    </Files>
</Directory>

Then a single favicon.ico will work for all the virtual hosted sites since you are aliasing it. It will be drawn from the browser cache for a month after the users visit.

For .htaccess this is reported to work (not checked by me):-

AddType image/x-icon .ico
ExpiresActive On
ExpiresByType image/x-icon "access plus 1 month"

How to unescape HTML character entities in Java?

The most reliable way is with

String cleanedString = StringEscapeUtils.unescapeHtml4(originalString);

from org.apache.commons.lang3.StringEscapeUtils.

And to escape the whitespaces

cleanedString = cleanedString.trim();

This will ensure that whitespaces due to copy and paste in web forms to not get persisted in DB.

How to get all checked checkboxes

For a simple two- (or one) liner this code can be:

checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);

Here the Array.prototype.slice.call() part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value) on the end of line 2. The => is javascript's arrow function notation.

Getting the name / key of a JToken with JSON.net

The default iterator for the JObject is as a dictionary iterating over key/value pairs.

JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
    Console.WriteLine (pair.Key);
}

Find unique rows in numpy.array

Lets get the entire numpy matrix as a list, then drop duplicates from this list, and finally return our unique list back into a numpy matrix:

matrix_as_list=data.tolist() 
matrix_as_list:
[[1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0]]

uniq_list=list()
uniq_list.append(matrix_as_list[0])

[uniq_list.append(item) for item in matrix_as_list if item not in uniq_list]

unique_matrix=np.array(uniq_list)
unique_matrix:
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 1, 1, 0]])

In c++ what does a tilde "~" before a function name signify?

This is a destructor. It's called when the object is destroyed (out of life scope or deleted).

To be clear, you have to use ~NameOfTheClass like for the constructor, other names are invalid.

"Sources directory is already netbeans project" error when opening a project from existing sources

If it helps anyone else, I had the same problem and the solution was to reinstall NetBeans.

I had tried all sorts of fixes: Deleting the NetBeansProjects folders, checking/unchecking "Put Netbeans metadata in a separate directory", killing/restarting NetBeans, restarting the system, etc. Nothing cleared the message...except the reinstall.

Gradle failed to resolve library in Android Studio

To be able to use a lib project you need to include it in your application's settings.gradle add:

include '..:ExpandableButtonMenu:library'

and then in your build.gradle add:

compile project(':..:ExpandableButtonMenu:library') 

place ExpandableButtonMenu project along side your own (same folder)

see this How to build an android library with Android Studio and gradle? for more details.

Regular expression for exact match of a string

if you have a the input password in a variable and you want to match exactly 123456 then anchors will help you:

/^123456$/

in perl the test for matching the password would be something like

print "MATCH_OK" if ($input_pass=~/^123456$/);

EDIT:

bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way

as a second thought, you may want to consider a safer authentication mechanism :)

How to convert an image to base64 encoding?

I think that it should be:

$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

Generate SHA hash in C++ using OpenSSL library

Here is OpenSSL example of calculating sha-1 digest using BIO:

#include <openssl/bio.h>
#include <openssl/evp.h>

std::string sha1(const std::string &input)
{
    BIO * p_bio_md  = nullptr;
    BIO * p_bio_mem = nullptr;

    try
    {
        // make chain: p_bio_md <-> p_bio_mem
        p_bio_md = BIO_new(BIO_f_md());
        if (!p_bio_md) throw std::bad_alloc();
        BIO_set_md(p_bio_md, EVP_sha1());

        p_bio_mem = BIO_new_mem_buf((void*)input.c_str(), input.length());
        if (!p_bio_mem) throw std::bad_alloc();
        BIO_push(p_bio_md, p_bio_mem);

        // read through p_bio_md
        // read sequence: buf <<-- p_bio_md <<-- p_bio_mem
        std::vector<char> buf(input.size());
        for (;;)
        {
            auto nread = BIO_read(p_bio_md, buf.data(), buf.size());
            if (nread  < 0) { throw std::runtime_error("BIO_read failed"); }
            if (nread == 0) { break; } // eof
        }

        // get result
        char md_buf[EVP_MAX_MD_SIZE];
        auto md_len = BIO_gets(p_bio_md, md_buf, sizeof(md_buf));
        if (md_len <= 0) { throw std::runtime_error("BIO_gets failed"); }

        std::string result(md_buf, md_len);

        // clean
        BIO_free_all(p_bio_md);

        return result;
    }
    catch (...)
    {
        if (p_bio_md) { BIO_free_all(p_bio_md); }
        throw;
    }
}

Though it's longer than just calling SHA1 function from OpenSSL, but it's more universal and can be reworked for using with file streams (thus processing data of any length).

How to use JNDI DataSource provided by Tomcat in Spring?

In your spring class, You can inject a bean annotated like as

@Autowired
@Qualifier("dbDataSource")
private DataSource dataSource;

and You add this in your context.xml

<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/>
</beans:bean>

You can declare the JNDI resource in tomcat's server.xml using

<Resource name="jdbc/TestDB" 
  global="jdbc/TestDB" 
  auth="Container" 
  type="javax.sql.DataSource" 
  driverClassName="com.mysql.jdbc.Driver" 
  url="jdbc:mysql://localhost:3306/TestDB" 
  username="pankaj" 
  password="pankaj123" 

  maxActive="100" 
  maxIdle="20" 
  minIdle="5" 
  maxWait="10000"/>

back to context.xml de spring add this

<ResourceLink name="jdbc/MyLocalDB"
                global="jdbc/TestDB"
                auth="Container"
                type="javax.sql.DataSource" />

if, like this exmple you are injecting connection to database, make sure that MySQL jar is present in the tomcat lib directory, otherwise tomcat will not be able to create the MySQL database connection pool.

HTML CSS How to stop a table cell from expanding

No javascript, just CSS. Works fine!

   .no-break-out {
      /* These are technically the same, but use both */
      overflow-wrap: break-word;
      word-wrap: break-word;

      -ms-word-break: break-all;
      /* This is the dangerous one in WebKit, as it breaks things wherever */
      word-break: break-all;
      /* Instead use this non-standard one: */
      word-break: break-word;

      /* Adds a hyphen where the word breaks, if supported (No Blink) */
      -ms-hyphens: auto;
      -moz-hyphens: auto;
      -webkit-hyphens: auto;
      hyphens: auto;

    }

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I want to correct little bit the above code

    public class MainActivity extends ActionBarActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this,  mDrawerLayout, mToolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close
        );
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

and all the other things will remain same...

For those who are having problem Drawerlayout overlaying toolbar

add android:layout_marginTop="?attr/actionBarSize" to root layout of drawer content

Run bash script as daemon

Another cool trick is to run functions or subshells in background, not always feasible though

name(){
  echo "Do something"
  sleep 1
}

# put a function in the background
name &
#Example taken from here
#https://bash.cyberciti.biz/guide/Putting_functions_in_background

Running a subshell in the background

(echo "started"; sleep 15; echo "stopped") &

Programmatically create a UIView with color gradient

Objective-C:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
CAGradientLayer *gradient = [CAGradientLayer layer];

gradient.frame = view.bounds;
gradient.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor blackColor].CGColor];

[view.layer insertSublayer:gradient atIndex:0];

Swift:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
let gradient = CAGradientLayer()

gradient.frame = view.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]

view.layer.insertSublayer(gradient, at: 0)

Info: use startPoint and endPoint to change direction of gradient.

If there are any other views added onto this UIView (such as a UILabel), you may want to consider setting the background color of those UIView’s to [UIColor clearColor] so the gradient view is presented instead of the background color for sub views. Using clearColor has a slight performance hit.

How do I Merge two Arrays in VBA?

Unfortunately, the Array type in VB6 didn't have all that many razzmatazz features. You are pretty much going to have to just iterate through the arrays and insert them manually into the third

Assuming both arrays are of the same length

Dim arr1() As Variant
Dim arr2() As Variant
Dim arr3() As Variant

arr1() = Array("A", 1, "B", 2)
arr2() = Array("C", 3, "D", 4)

ReDim arr3(UBound(arr1) + UBound(arr2) + 1)

Dim i As Integer
For i = 0 To UBound(arr1)
    arr3(i * 2) = arr1(i)
    arr3(i * 2 + 1) = arr2(i)
Next i

Updated: Fixed the code. Sorry about the previous buggy version. Took me a few minutes to get access to a VB6 compiler to check it.

Split bash string by newline characters

Another way:

x=$'Some\nstring'
readarray -t y <<<"$x"

Or, if you don't have bash 4, the bash 3.2 equivalent:

IFS=$'\n' read -rd '' -a y <<<"$x"

You can also do it the way you were initially trying to use:

y=(${x//$'\n'/ })

This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'. To make it work, you need to restrict the word separator before parsing it:

IFS=$'\n' y=(${x//$'\n'/ })

...and then, since you are changing the separator, you don't need to convert the \n to space anymore, so you can simplify it to:

IFS=$'\n' y=($x)

This approach will function unless $x contains a matching globbing pattern (such as "*") - in which case it will be replaced by the matched file name(s). The read/readarray methods require newer bash versions, but work in all cases.

How to control border height?

I want to control the height of the border. How could I do this?

You can't. CSS borders will always span across the full height / width of the element.

One workaround idea would be to use absolute positioning (which can accept percent values) to place the border-carrying element inside one of the two divs. For that, you would have to make the element position: relative.

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

How can I create a UIColor from a hex string?

You can create extension class of UIColor as:-

extension UIColor {

// MARK: - getColorFromHex /** This function will convert the color Hex code to RGB.

- parameter color  hex string.

- returns: RGB color code.
*/
class func getColorFromHex(hexString:String)->UIColor{

    var rgbValue : UInt32 = 0
    let scanner:NSScanner =  NSScanner(string: hexString)

    scanner.scanLocation = 1
    scanner.scanHexInt(&rgbValue)

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

}

Syntax error on print with Python 3

It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.

print('Hello world!')

How do I protect javascript files?

From my knowledge, this is not possible.

Your browser has to have access to JS files to be able to execute them. If the browser has access, then browser's user also has access.

If you password protect your JS files, then the browser won't be able to access them, defeating the purpose of having JS in the first place.

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

Oracle SQL Developer: Unable to find a JVM

The secret is you need to copy msvcr100.dll to the path where the installation says msvcr100.dll is missing (dialog box) and then try to install the sql developer.

For me I had to create bin folder in

C:\sqldeveloper\jdk\bin

and Copy msvcr100.dll to it.

If still not working! Try this!

You might also need to change the config file settings found in

C:\sqldeveloper\sqldeveloper\bin

Download and install 32 bit JDK (Windows) and set the path in config file as

SetJavaHome C:/Program Files (x86)/Java/jdk1.7.0_01

Printing HashMap In Java

You have several options

Get the new record primary key ID from MySQL insert query?

You need to use the LAST_INSERT_ID() function: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

Eg:

INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...);
SELECT LAST_INSERT_ID();

This will get you back the PRIMARY KEY value of the last row that you inserted:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client.

So the value returned by LAST_INSERT_ID() is per user and is unaffected by other queries that might be running on the server from other users.

Changing datagridview cell color dynamically

This works for me

dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;

Excel VBA Open workbook, perform actions, save as, close

After discussion posting updated answer:

Option Explicit
Sub test()

    Dim wk As String, yr As String
    Dim fname As String, fpath As String
    Dim owb As Workbook

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    wk = ComboBox1.Value
    yr = ComboBox2.Value
    fname = yr & "W" & wk
    fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"

    On Error GoTo ErrorHandler
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)

    'Do Some Stuff

    With owb
        .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
        .Close
    End With

    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
        .EnableEvents = True
    End With

Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

Else: Call Clear

End Sub

Error Handling:

You could try something like this to catch a specific error:

    On Error Resume Next
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    If Err.Number = 1004 Then
    GoTo FileNotFound
    Else
    End If

    ...
    Exit Sub
    FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

    Else: Call Clear

Deserialize a json string to an object in python

pydantic is an increasingly popular library for python 3.6+ projects. It mainly does data validation and settings management using type hints.

A basic example using different types:

from pydantic import BaseModel

class ClassicBar(BaseModel):
    count_drinks: int
    is_open: bool
 
data = {'count_drinks': '226', 'is_open': 'False'}
cb = ClassicBar(**data)
>>> cb
ClassicBar(count_drinks=226, is_open=False)

What I love about the lib is that you get a lot of goodies for free, like

>>> cb.json()
'{"count_drinks": 226, "is_open": false}'
>>> cb.dict()
{'count_drinks': 226, 'is_open': False}

Where to place $PATH variable assertions in zsh?

Here is the docs from the zsh man pages under STARTUP/SHUTDOWN FILES section.

   Commands  are  first  read from /etc/zshenv this cannot be overridden.
   Subsequent behaviour is modified by the RCS and GLOBAL_RCS options; the
   former  affects all startup files, while the second only affects global
   startup files (those shown here with an path starting with  a  /).   If
   one  of  the  options  is  unset  at  any point, any subsequent startup
   file(s) of the corresponding type will not be read.  It is also  possi-
   ble  for  a  file  in  $ZDOTDIR  to  re-enable GLOBAL_RCS. Both RCS and
   GLOBAL_RCS are set by default.

   Commands are then read from $ZDOTDIR/.zshenv.  If the shell is a  login
   shell,  commands  are  read from /etc/zprofile and then $ZDOTDIR/.zpro-
   file.  Then, if the  shell  is  interactive,  commands  are  read  from
   /etc/zshrc  and then $ZDOTDIR/.zshrc.  Finally, if the shell is a login
   shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.

From this we can see the order files are read is:

/etc/zshenv    # Read for every shell
~/.zshenv      # Read for every shell except ones started with -f
/etc/zprofile  # Global config for login shells, read before zshrc
~/.zprofile    # User config for login shells
/etc/zshrc     # Global config for interactive shells
~/.zshrc       # User config for interactive shells
/etc/zlogin    # Global config for login shells, read after zshrc
~/.zlogin      # User config for login shells
~/.zlogout     # User config for login shells, read upon logout
/etc/zlogout   # Global config for login shells, read after user logout file

You can get more information here.

Converting integer to string in Python

If you need unary numeral system, you can convert an integer like this:

>> n = 6
>> '1' * n
'111111'

If you need a support of negative ints you can just write like that:

>> n = -6
>> '1' * n if n >= 0 else '-' + '1' * (-n)
'-111111'

Zero is special case which takes an empty string in this case, which is correct.

>> n = 0
>> '1' * n if n >= 0 else '-' + '1' * (-n)
''

Fastest Convert from Collection to List<T>

As long as ManagementObjectCollection implements IEnumerable<ManagementObject> you can do:

List<ManagementObject> managementList = new List<ManagementObjec>(managementObjects);

If it doesn't, then you are stuck doing it the way that you are doing it.

Encrypt and decrypt a password in Java

EDIT : this answer is old. Usage of MD5 is now discouraged as it can easily be broken.


MD5 must be good enough for you I imagine? You can achieve it with MessageDigest.

MessageDigest.getInstance("MD5");

There are also other algorithms listed here.

And here's an third party version of it, if you really want: Fast MD5

How would you do a "not in" query with LINQ?

You can use a combination of Where and Any for finding not in:

var NotInRecord =list1.Where(p => !list2.Any(p2 => p2.Email  == p.Email));

Exception: Serialization of 'Closure' is not allowed

Apparently anonymous functions cannot be serialized.

Example

$function = function () {
    return "ABC";
};
serialize($function); // would throw error

From your code you are using Closure:

$callback = function () // <---------------------- Issue
{
    return 'ZendMail_' . microtime(true) . '.tmp';
};

Solution 1 : Replace with a normal function

Example

function emailCallback() {
    return 'ZendMail_' . microtime(true) . '.tmp';
}
$callback = "emailCallback" ;

Solution 2 : Indirect method call by array variable

If you look at http://docs.mnkras.com/libraries_23rdparty_2_zend_2_mail_2_transport_2file_8php_source.html

   public function __construct($options = null)
   63     {
   64         if ($options instanceof Zend_Config) {
   65             $options = $options->toArray();
   66         } elseif (!is_array($options)) {
   67             $options = array();
   68         }
   69 
   70         // Making sure we have some defaults to work with
   71         if (!isset($options['path'])) {
   72             $options['path'] = sys_get_temp_dir();
   73         }
   74         if (!isset($options['callback'])) {
   75             $options['callback'] = array($this, 'defaultCallback'); <- here
   76         }
   77 
   78         $this->setOptions($options);
   79     }

You can use the same approach to send the callback

$callback = array($this,"aMethodInYourClass");

Converting HTML to plain text in PHP for e-mail

For texts in utf-8, it worked for me mb_convert_encoding. To process everything regardless of errors, make sure you use the "@".

The basic code I use is:

$dom = new DOMDocument();
@$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));

$body = $dom->getElementsByTagName('body')->item(0);
echo $body->textContent;

If you want something more advanced, you can iteratively analyze the nodes, but you will encounter many problems with whitespaces.

I have implemented a converter based on what I say here. If you are interested, you can download it from git https://github.com/kranemora/html2text

It may serve as a reference to make yours

You can use it like this:

$html = <<<EOF
<p>Welcome to <strong>html2text<strong></p>
<p>It's <em>works</em> for you?</p>
EOF;

$html2Text = new \kranemora\Html2Text\Html2Text;
$text = $html2Text->convert($html);

Can JavaScript connect with MySQL?

You can connect to MySQL from Javascript through a JAVA applet. The JAVA applet would embed the JDBC driver for MySQL that will allow you to connect to MySQL.

Remember that if you want to connect to a remote MySQL server (other than the one you downloaded the applet from) you will need to ask users to grant extended permissions to applet. By default, applet can only connect to the server they are downloaded from.

Setting the MySQL root user password on OS X

If you have forgot the MySQL root password, can’t remember or want to break in….. you can reset the mysql database password from the command line in either Linux or OS X as long as you know the root user password of the box you are on:

(1) Stop MySQL

sudo /usr/local/mysql/support-files/mysql.server stop

(2) Start it in safe mode:

sudo mysqld_safe --skip-grant-tables

(3) This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:

mysql -u root

UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';

In the UPDATE command above just replace the 'password' with your own new password, make sure to keep the quotation marks

(4) Save and quite

FLUSH PRIVILEGES;

\q

(5) Start MySQL

sudo /usr/local/mysql/support-files/mysql.server start

MySQL SELECT WHERE datetime matches day (and not necessarily time)

... WHERE date_column >='2012-12-25' AND date_column <'2012-12-26' may potentially work better(if you have an index on date_column) than DATE.

Pointer to a string in C?

The same notation is used for pointing at a single character or the first character of a null-terminated string:

char c = 'Z';
char a[] = "Hello world";

char *ptr1 = &c;
char *ptr2 = a;      // Points to the 'H' of "Hello world"
char *ptr3 = &a[0];  // Also points to the 'H' of "Hello world"
char *ptr4 = &a[6];  // Points to the 'w' of "world"
char *ptr5 = a + 6;  // Also points to the 'w' of "world"

The values in ptr2 and ptr3 are the same; so are the values in ptr4 and ptr5. If you're going to treat some data as a string, it is important to make sure it is null terminated, and that you know how much space there is for you to use. Many problems are caused by not understanding what space is available and not knowing whether the string was properly null terminated.

Note that all the pointers above can be dereferenced as if they were an array:

 *ptr1    == 'Z'
  ptr1[0] == 'Z'

 *ptr2    == 'H'
  ptr2[0] == 'H'
  ptr2[4] == 'o'

 *ptr4    == 'w'
  ptr4[0] == 'w'
  ptr4[4] == 'd'

  ptr5[0] ==   ptr3[6]
*(ptr5+0) == *(ptr3+6)

Late addition to question

What does char (*ptr)[N]; represent?

This is a more complex beastie altogether. It is a pointer to an array of N characters. The type is quite different; the way it is used is quite different; the size of the object pointed to is quite different.

char (*ptr)[12] = &a;

(*ptr)[0] == 'H'
(*ptr)[6] == 'w'

*(*ptr + 6) == 'w'

Note that ptr + 1 points to undefined territory, but points 'one array of 12 bytes' beyond the start of a. Given a slightly different scenario:

char b[3][12] = { "Hello world", "Farewell", "Au revoir" };

char (*pb)[12] = &b[0];

Now:

(*(pb+0))[0] == 'H'
(*(pb+1))[0] == 'F'
(*(pb+2))[5] == 'v'

You probably won't come across pointers to arrays except by accident for quite some time; I've used them a few times in the last 25 years, but so few that I can count the occasions on the fingers of one hand (and several of those have been answering questions on Stack Overflow). Beyond knowing that they exist, that they are the result of taking the address of an array, and that you probably didn't want it, you don't really need to know more about pointers to arrays.

Add zero-padding to a string

string strvalue="11".PadRight(4, '0');

output= 1100

string strvalue="301".PadRight(4, '0');

output= 3010

string strvalue="11".PadLeft(4, '0');

output= 0011

string strvalue="301".PadLeft(4, '0');

output= 0301

Best way to parse RSS/Atom feeds with PHP

I use SimplePie to parse a Google Reader feed and it works pretty well and has a decent feature set.

Of course, I haven't tested it with non-well-formed RSS / Atom feeds so I don't know how it copes with those, I'm assuming Google's are fairly standards compliant! :)

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

To handle the situation in which there is no wiring, beans are available with @Autowired required attribute set to false.

But when using @Inject, the Provider interface works with the bean which means that the bean is not injected directly but with the Provider.

Passive Link in Angular 2 - <a href=""> equivalent

There are ways of doing it with angular2, but I strongly disagree this is a bug. I'm not familiarized with angular1, but this seems like a really wrong behavior even though as you claim is useful in some cases, but clearly this should not be the default behavior of any framework.

Disagreements aside you can write a simple directive that grabs all your links and check for href's content and if the length of it it's 0 you execute preventDefault(), here's a little example.

@Directive({
  selector : '[href]',
  host : {
    '(click)' : 'preventDefault($event)'
  }
})
class MyInhertLink {
  @Input() href;
  preventDefault(event) {
    if(this.href.length == 0) event.preventDefault();
  }
}

You can make it to work across your application by adding this directive in PLATFORM_DIRECTIVES

bootstrap(App, [provide(PLATFORM_DIRECTIVES, {useValue: MyInhertLink, multi: true})]);

Here's a plnkr with an example working.

postgresql return 0 if returned value is null

(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).


There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.

For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).

$ create table foo (bar int);
CREATE TABLE

$ select avg(bar) from foo;
 avg 
-----

(1 row)

$ select coalesce(avg(bar), 0) from foo;
 coalesce 
----------
        0
(1 row)

$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
      coalesce      
--------------------
 6.0000000000000000
(1 row)

of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"

Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.

$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
      coalesce      
--------------------
 4.0000000000000000
(1 row)

What is the behavior difference between return-path, reply-to and from?

Let's start with a simple example. Let's say you have an email list, that is going to send out the following RFC2822 content.

From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.

Now, let's say you are going to send it from a mailing list, that implements VERP (or some other bounce tracking mechanism that uses a different return-path). Lets say it will have a return-path of [email protected]. The SMTP session might look like:

{S}220 workstation1 Microsoft ESMTP MAIL Service
{C}HELO workstation1
{S}250 workstation1 Hello [127.0.0.1]
{C}MAIL FROM:<[email protected]>
{S}250 2.1.0 [email protected] OK
{C}RCPT TO:<[email protected]>
{S}250 2.1.5 [email protected] 
{C}DATA
{S}354 Start mail input; end with <CRLF>.<CRLF>
{C}From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.
.

{S}250 Queued mail for delivery
{C}QUIT
{S}221 Service closing transmission channel

Where {C} and {S} represent Client and Server commands, respectively.

The recipient's mail would look like:

Return-Path: [email protected]
From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.

Now, let's describe the different "FROM"s.

  1. The return path (sometimes called the reverse path, envelope sender, or envelope from — all of these terms can be used interchangeably) is the value used in the SMTP session in the MAIL FROM command. As you can see, this does not need to be the same value that is found in the message headers. Only the recipient's mail server is supposed to add a Return-Path header to the top of the email. This records the actual Return-Path sender during the SMTP session. If a Return-Path header already exists in the message, then that header is removed and replaced by the recipient's mail server.

All bounces that occur during the SMTP session should go back to the Return-Path address. Some servers may accept all email, and then queue it locally, until it has a free thread to deliver it to the recipient's mailbox. If the recipient doesn't exist, it should bounce it back to the recorded Return-Path value.

Note, not all mail servers obey this rule; Some mail servers will bounce it back to the FROM address.

  1. The FROM address is the value found in the FROM header. This is supposed to be who the message is FROM. This is what you see as the "FROM" in most mail clients. If an email does not have a Reply-To header, then all human (mail client) replies should go back to the FROM address.

  2. The Reply-To header is added by the sender (or the sender's software). It is where all human replies should be addressed too. Basically, when the user clicks "reply", the Reply-To value should be the value used as the recipient of the newly composed email. The Reply-To value should not be used by any server. It is meant for client-side (MUA) use only.

However, as you can tell, not all mail servers obey the RFC standards or recommendations.

Hopefully this should help clear things up. However, if I missed anything, let me know, and I'll try to answer.