Programs & Examples On #Contravariance

Within the type system of a programming language, covariance and contravariance refers to the ordering of types from narrower to wider and their interchangeability or equivalence in certain situations (such as parameters, generics, and return types)

Extract subset of key-value pairs from Python dictionary object?

interesting_keys = ('l', 'm', 'n')
subdict = {x: bigdict[x] for x in interesting_keys if x in bigdict}

How can I convert string to datetime with format specification in JavaScript?

I think this can help you: http://www.mattkruse.com/javascript/date/

There's a getDateFromFormat() function that you can tweak a little to solve your problem.

Update: there's an updated version of the samples available at javascripttoolbox.com

Java: how to initialize String[]?

In Java 8 we can also make use of streams e.g.

String[] strings = Stream.of("First", "Second", "Third").toArray(String[]::new);

In case we already have a list of strings (stringList) then we can collect into string array as:

String[] strings = stringList.stream().toArray(String[]::new);

How do you clear your Visual Studio cache on Windows Vista?

I had the same issue but when i deleted the cached items from Temp folder the build failed.

In order to make the build work again I had to close the project and reopen it.

Change user-agent for Selenium web-driver

This is a short solution to change the request UserAgent on the fly.

Change UserAgent of a request with Chrome

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = webdriver.Chrome(driver_path)
driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent":"python 2.7", "platform":"Windows"})
driver.get('http://amiunique.org')

then return your useragent:

agent = driver.execute_script("return navigator.userAgent")

Some sources

The source code of webdriver.py from SeleniumHQ (https://github.com/SeleniumHQ/selenium/blob/11c25d75bd7ed22e6172d6a2a795a1d195fb0875/py/selenium/webdriver/chrome/webdriver.py) extends its functionalities through the Chrome Devtools Protocol

def execute_cdp_cmd(self, cmd, cmd_args):
        """
        Execute Chrome Devtools Protocol command and get returned result

We can use the Chrome Devtools Protocol Viewer to list more extended functionalities (https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) as well as the parameters type to use.

XPath with multiple conditions

Use:

/category[@name='Sport' and author/text()[1]='James Small']

or use:

/category[@name='Sport' and author[starts-with(.,'James Small')]]

It is a good rule to try to avoid using the // pseudo-operator whenever possible, because its evaluation can typically be very slow.

Also:

./somename

is equivalent to:

somename

so it is recommended to use the latter.

How do I show the value of a #define at compile-time?

You could write a program that prints out BOOST_VERSION and compile and run it as part of your build system. Otherwise, I think you're out of luck.

How do I copy a string to the clipboard?

I've tried various solutions, but this is the simplest one that passes my test:

#coding=utf-8

import win32clipboard  # http://sourceforge.net/projects/pywin32/

def copy(text):
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT)
    win32clipboard.CloseClipboard()
def paste():
    win32clipboard.OpenClipboard()
    data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
    win32clipboard.CloseClipboard()
    return data

if __name__ == "__main__":  
    text = "Testing\nthe “clip—board”: "
    try: text = text.decode('utf8')  # Python 2 needs decode to make a Unicode string.
    except AttributeError: pass
    print("%r" % text.encode('utf8'))
    copy(text)
    data = paste()
    print("%r" % data.encode('utf8'))
    print("OK" if text == data else "FAIL")

    try: print(data)
    except UnicodeEncodeError as er:
        print(er)
        print(data.encode('utf8'))

Tested OK in Python 3.4 on Windows 8.1 and Python 2.7 on Windows 7. Also when reading Unicode data with Unix linefeeds copied from Windows. Copied data stays on the clipboard after Python exits: "Testing the “clip—board”: "

If you want no external dependencies, use this code (now part of cross-platform pyperclip - C:\Python34\Scripts\pip install --upgrade pyperclip):

def copy(text):
    GMEM_DDESHARE = 0x2000
    CF_UNICODETEXT = 13
    d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None)
    try:  # Python 2
        if not isinstance(text, unicode):
            text = text.decode('mbcs')
    except NameError:
        if not isinstance(text, str):
            text = text.decode('mbcs')
    d.user32.OpenClipboard(0)
    d.user32.EmptyClipboard()
    hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
    pchData = d.kernel32.GlobalLock(hCd)
    ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
    d.kernel32.GlobalUnlock(hCd)
    d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
    d.user32.CloseClipboard()

def paste():
    CF_UNICODETEXT = 13
    d = ctypes.windll
    d.user32.OpenClipboard(0)
    handle = d.user32.GetClipboardData(CF_UNICODETEXT)
    text = ctypes.c_wchar_p(handle).value
    d.user32.CloseClipboard()
    return text

Convert IQueryable<> type object to List<T> type?

Add the following:

using System.Linq

...and call ToList() on the IQueryable<>.

XAMPP - MySQL shutdown unexpectedly

Make sure the system time is correct. Mine was set to the year 2040 somehow, correcting the date solved the problem.

Is it possible to get a list of files under a directory of a website? How?

If you have directory listing disabled in your webserver, then the only way somebody will find it is by guessing or by finding a link to it.

That said, I've seen hacking scripts attempt to "guess" a whole bunch of these common names. "secret.html" would probably be in such a guess list.

The more reasonable solution is to restrict access using a username/password via a htaccess file (for apache) or the equivalent setting for whatever webserver you're using.

Convert generic list to dataset in C#

There is a bug with Lee's extension code above, you need to add the newly filled row to the table t when iterating throught the items in the list.

public static DataSet ToDataSet<T>(this IList<T> list) {

Type elementType = typeof(T);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);

//add a column to table for each public property on T
foreach(var propInfo in elementType.GetProperties())
{
    t.Columns.Add(propInfo.Name, propInfo.PropertyType);
}

//go through each property on T and add each value to the table
foreach(T item in list)
{
    DataRow row = t.NewRow();
    foreach(var propInfo in elementType.GetProperties())
    {
            row[propInfo.Name] = propInfo.GetValue(item, null);
    }

    //This line was missing:
    t.Rows.Add(row);
}


return ds;

}

What does "var" mean in C#?

var is a "contextual keyword" in C# meaning you can only use it as a local variable implicitly in the context of the same class that you are using the variable. If you try to use it in a class that you call from "Main" or some other exterior class, or an interface for example you will get the error CS0825 < https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs0825 >

See the remarks about when you can and can't use it in the documentation here: < https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables#remarks >

Basically, you should only use this when you are declaring a variable with an implicit value such as "var myValue = "This is the value"; This saves a little time in comparison to saying "string" for example but IMHO not much time is saved and places a constraint on the scalability of your project.

SQL select * from column where year = 2010

T-SQL and others;

select * from t where year(Columnx) = 2010

SQL LIKE condition to check for integer?

Which one of those is indexable?

This one is definitely btree-indexable:

WHERE title >= '0' AND title < ':'

Note that ':' comes after '9' in ASCII.

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

Can I display the value of an enum with printf()?

The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.

Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:

main.c:

#include "Enum.h"

CreateEnum(
        EnumerationName,
        ENUMValue1,
        ENUMValue2,
        ENUMValue3);

int main(void)
{
    int i;
    EnumerationName EnumInstance = ENUMValue1;

    /* Prints "ENUMValue1" */
    PrintEnumValue(EnumerationName, EnumInstance);

    /* Prints:
     * ENUMValue1
     * ENUMValue2
     * ENUMValue3
     */
    for (i=0;i<3;i++)
    {
        PrintEnumValue(EnumerationName, i);
    }
    return 0;
}

Enum.h:

#include <stdio.h>
#include <string.h>

#ifdef NDEBUG
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name;
#define PrintEnumValue(name,value)
#else
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name; \
    const char Lookup##name[] = \
        #__VA_ARGS__;
#define PrintEnumValue(name, value) print_enum_value(Lookup##name, value)
void print_enum_value(const char *lookup, int value);
#endif

Enum.c

#include "Enum.h"

#ifndef NDEBUG
void print_enum_value(const char *lookup, int value)
{
    char *lookup_copy;
    int lookup_length;
    char *pch;

    lookup_length = strlen(lookup);
    lookup_copy = malloc((1+lookup_length)*sizeof(char));
    strcpy(lookup_copy, lookup);

    pch = strtok(lookup_copy," ,");
    while (pch != NULL)
    {
        if (value == 0)
        {
            printf("%s\n",pch);
            break;
        }
        else
        {
            pch = strtok(NULL, " ,.-");
            value--;
        }
    }

    free(lookup_copy);
}
#endif

Disclaimer: don't do this.

How to remove all null elements from a ArrayList or String Array?

Mainly I'm using this:

list.removeAll(Collections.singleton(null));

But after I learned Java 8, I switched to this:

List.removeIf(Objects::isNull);

SQL Server - How to lock a table until a stored procedure finishes

BEGIN TRANSACTION

select top 1 *
from table1
with (tablock, holdlock)

-- You do lots of things here

COMMIT

This will hold the 'table lock' until the end of your current "transaction".

How to save a bitmap on internal storage

private static void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().getAbsolutePath();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();

    String fname = "Image-"+ o +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete ();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

Swift: Testing optionals for nil

If you have conditional and would like to unwrap and compare, how about taking advantage of the short-circuit evaluation of compound boolean expression as in

if xyz != nil && xyz! == "some non-nil value" {

}

Granted, this is not as readable as some of the other suggested posts, but gets the job done and somewhat succinct than the other suggested solutions.

TSQL - Cast string to integer or return default value

Joseph's answer pointed out ISNUMERIC also handles scientific notation like '1.3e+3' but his answer doesn't handle this format of number.

Casting to a money or float first handles both the currency and scientific issues:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TryConvertInt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[TryConvertInt]
GO

CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS bigint
AS
BEGIN
    DECLARE @IntValue bigint;

    IF (ISNUMERIC(@Value) = 1)
        IF (@Value like '%e%')
            SET @IntValue = CAST(Cast(@Value as float) as bigint);
        ELSE
            SET @IntValue = CAST(CAST(@Value as money) as bigint);
    ELSE
        SET @IntValue = NULL;

    RETURN @IntValue;
END

The function will fail if the number is bigger than a bigint.

If you want to return a different default value, leave this function so it is generic and replace the null afterwards:

SELECT IsNull(dbo.TryConvertInt('nan') , 1000);

Can you disable tabs in Bootstrap?

Suppose, this is your TAB and you want to disable it

<li class="" id="groups"><a data-toggle="tab" class="navuserli" href="#groups" aria-expanded="false">Groups</a></li>

So you can also disable this tab by adding dynamic css

$('#groups').css('pointer-events', 'none')

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

hexadecimal string to byte array in python

Suppose your hex string is something like

>>> hex_string = "deadbeef"

Convert it to a string (Python = 2.7):

>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"

or since Python 2.7 and Python 3.0:

>>> bytes.fromhex(hex_string)  # Python = 3
b'\xde\xad\xbe\xef'

>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')

Note that bytes is an immutable version of bytearray.

difference between variables inside and outside of __init__()

Example code:

class inside:
    def __init__(self):
        self.l = []

    def insert(self, element):
        self.l.append(element)


class outside:
    l = []             # static variable - the same for all instances

    def insert(self, element):
        self.l.append(element)


def main():
    x = inside()
    x.insert(8)
    print(x.l)      # [8]
    y = inside()
    print(y.l)      # []
    # ----------------------------
    x = outside()
    x.insert(8)
    print(x.l)      # [8]
    y = outside()
    print(y.l)      # [8]           # here is the difference


if __name__ == '__main__':
    main()

How to return a result from a VBA function

The below code stores the return value in to the variable retVal and then MsgBox can be used to display the value:

Dim retVal As Integer
retVal = test()
Msgbox retVal

What's the difference between JPA and Hibernate?

JPA is just a specification which needs concrete implementation. The default implementation provided by oracle is "Eclipselink" now. Toplink is donated by Oracle to Eclipse foundation to merge with eclipselink.

Using Eclipselink, one can be sure that the code is portable to any implementation if need arises. Hibernate is also a full JPA implementation + MORE. Hibernate is super set of JPA with some extra Hibernate specific functionality. So application developed in Hibernate may not be compatible when switched to other implementation. Still hibernate is choice of majority of developers as JPA implementation and widely used.

Another JPA implementation is OpenJPA, which is an extension of Kodo implementation.

JPA vs Hibernate

Vim 80 column layout concerns

I have this set up in my .vimrc:

highlight OverLength ctermbg=red ctermfg=white guibg=#592929
match OverLength /\%81v.\+/

This highlights the background in a subtle red for text that goes over the 80 column limit (subtle in GUI mode, anyway - in terminal mode it's less so).

Download files from SFTP with SSH.NET library

A simple working code to download a file with SSH.NET library is:

using (Stream fileStream = File.Create(@"C:\target\local\path\file.zip"))
{
    sftp.DownloadFile("/source/remote/path/file.zip", fileStream);
}

See also Downloading a directory using SSH.NET SFTP in C#.


To explain, why your code does not work:

The second parameter of SftpClient.DownloadFile is a stream to write a downloaded contents to.

You are passing in a read stream instead of a write stream. And moreover the path you are opening read stream with is a remote path, what cannot work with File class operating on local files only.

Just discard the File.OpenRead line and use a result of previous File.OpenWrite call instead (that you are not using at all now):

Stream file1 = File.OpenWrite(localFileName);

sftp.DownloadFile(file.FullName, file1);

Or even better, use File.Create to discard any previous contents that the local file may have.

I'm not sure if your localFileName is supposed to hold full path, or just file name. So you may need to add a path too, if necessary (combine localFileName with sDir?)

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

I found that this error occurred when I extracted the .rpm file.

I then removed that folder and downloaded jdk-7u79-linux-x64.tar.gz for Linux 64 and extracted the contents of this file instead. Also: export JAVA_HOME=/opt/java/jdk1.7.0_79 export JDK_HOME=/opt/java/jdk1.7.0_79 export PATH=${JAVA_HOME}/bin

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

It seems like it's a bug on Gradle. This solves the problem for me, but it's not a solution. We have to wait for a new version fixing this problems.

On build.gradle in the project set classpath 'com.android.tools.build:gradle:2.3.3' instead classpath 'com.android.tools.build:gradle:3.0.0'.

On gradle-wrapper.properties set https://services.gradle.org/distributions/gradle-3.3-all.zip instead https://services.gradle.org/distributions/gradle-4.1.2-all.zip

How to write data to a text file without overwriting the current data

Best thing is

File.AppendAllText("c:\\file.txt","Your Text");

How to remove leading zeros from alphanumeric text?

You could replace "^0*(.*)" to "$1" with regex

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

aapt dump badging test.apk | grep "VersionName" | sed -e "s/.*versionName='//" -e "s/' .*//"

This answers the question by returning only the version number as a result. However......

The goal as previously stated should be to find out if the apk on the server is newer than the one installed BEFORE attempting to download or install it. The easiest way to do this is include the version number in the filename of the apk hosted on the server eg myapp_1.01.apk

You will need to establish the name and version number of the apps already installed (if it is installed) in order to make the comparison. You will need a rooted device or a means of installing the aapt binary and busybox if they are not already included in the rom.

This script will get the list of apps from your server and compare with any installed apps. The result is a list flagged for upgrade/installation.

#/system/bin/sh
SERVER_LIST=$(wget -qO- "http://demo.server.com/apk/" | grep 'href' | grep '\.apk' | sed 's/.*href="//' | \
              sed 's/".*//' | grep -v '\/' | sed -E "s/%/\\\\x/g" | sed -e "s/x20/ /g" -e "s/\\\\//g")
LOCAL_LIST=$(for APP in $(pm list packages -f | sed -e 's/package://' -e 's/=.*//' | sort -u); do \
              INFO=$(echo -n $(aapt dump badging $APP | grep -e 'package: name=' -e 'application: label=')) 2>/dev/null; \
              PACKAGE=$(echo $INFO | sed "s/.*package: name='//" | sed "s/'.*$//"); \
              LABEL=$(echo $INFO | sed "s/.*application: label='//" | sed "s/'.*$//"); if [ -z "$LABEL" ]; then LABEL="$PACKAGE"; fi; \
              VERSION=$(echo $INFO | sed -e "s/.*versionName='//" -e "s/' .*//"); \
              NAME=$LABEL"_"$VERSION".apk"; echo "$NAME"; \
              done;)
OFS=$IFS; IFS=$'\t\n'
for REMOTE in $SERVER_LIST; do
    INSTALLED=0
    REMOTE_NAME=$(echo $REMOTE | sed 's/_.*//'); REMOTE_VER=$(echo $REMOTE | sed 's/^[^_]*_//g' | sed 's/[^0-9]*//g')
    for LOCAL in $LOCAL_LIST; do
        LOCAL_NAME=$(echo $LOCAL | sed 's/_.*//'); LOCAL_VER=$(echo $LOCAL | sed 's/^[^_]*_//g' | sed 's/[^0-9]*//g')
        if [ "$REMOTE_NAME" == "$LOCAL_NAME" ]; then INSTALLED=1; fi
        if [ "$REMOTE_NAME" == "$LOCAL_NAME" ] && [ ! "$REMOTE_VER" == "$LOCAL_VER" ]; then echo remote=$REMOTE ver=$REMOTE_VER local=$LOCAL ver=$LOCAL_VER; fi
    done
    if [ "$INSTALLED" == "0" ]; then echo "$REMOTE"; fi
done
IFS=$OFS

As somebody asked how to do it without using aapt. It is also possible to extract apk info with apktool and a bit of scripting. This way is slower and not simple in android but will work on windows/mac or linux as long as you have working apktool setup.

#!/bin/sh
APK=/path/to/your.apk
TMPDIR=/tmp/apktool
rm -f -R $TMPDIR
apktool d -q -f -s --force-manifest -o $TMPDIR $APK
APK=$(basename $APK)
VERSION=$(cat $TMPDIR/apktool.yml | grep "versionName" | sed -e "s/versionName: //")
LABEL=$(cat $TMPDIR/res/values/strings.xml | grep 'string name="title"' | sed -e 's/.*">//' -e 's/<.*//')
rm -f -R $TMPDIR
echo ${LABEL}_$(echo $V).apk

Also consider a drop folder on your server. Upload apks to it and a cron task renames and moves them to your update folder.

#!/bin/sh
# Drop Folder script for renaming APKs
# Read apk file from SRC folder and move it to TGT folder while changing filename to APKLABEL_APKVERSION.apk
# If an existing version of the APK exists in the target folder then script will remove it
# Define METHOD as "aapt" or "apktool" depending upon what is available on server 

# Variables
METHOD="aapt"
SRC="/home/user/public_html/dropfolders/apk"
TGT="/home/user/public_html/apk"
if [ -d "$SRC" ];then mkdir -p $SRC
if [ -d "$TGT" ]then mkdir -p $TGT

# Functions
get_apk_filename () {
    if [ "$1" = "" ]; then return 1; fi
    local A="$1"
    case $METHOD in
        "apktool")
            local D=/tmp/apktool
            rm -f -R $D
            apktool d -q -f -s --force-manifest -o $D $A
            local A=$(basename $A)
            local V=$(cat $D/apktool.yml | grep "versionName" | sed -e "s/versionName: //")
            local T=$(cat $D/res/values/strings.xml | grep 'string name="title"' | sed -e 's/.*">//' -e 's/<.*//')
            rm -f -R $D<commands>
            ;;
        "aapt")
            local A=$(aapt dump badging $A | grep -e "application-label:" -e "VersionName")
            local V=$(echo $A | sed -e "s/.*versionName='//" -e "s/' .*//")
            local T=$(echo $A | sed -e "s/.*application-label:'//" -e "s/'.*//")
            ;;
        esac
    echo ${T}_$(echo $V).apk
}

# Begin script
for APK in $(ls "$SRC"/*.apk); do
    APKNAME=$(get_apk_filename "$APK")
    rm -f $TGT/$(echo APKNAME | sed "s/_.*//")_*.apk
    mv "$APK" "$TGT"/$APKNAME
done

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

Getting attribute of element in ng-click function in angularjs

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

var dataValue = obj.srcElement.attributes.data.nodeValue;

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

var dataValue = obj.currentTarget.attributes.data.nodeValue;

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

Delete last N characters from field in a SQL Server database

You could do it using SUBSTRING() function:

UPDATE table SET column = SUBSTRING(column, 0, LEN(column) + 1 - N)

Removes the last N characters from every row in the column

Defining Z order of views of RelativeLayout in Android

If you want to do this in code you can do

View.bringToFront();

see docs

Add colorbar to existing axis

Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
    for col in row:
        im = col.imshow(data, cmap='bone')
        divider = make_axes_locatable(col)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

AngularJS view not updating on model change

setTimout executes outside of angular. You need to use $timeout service for this to work:

var app = angular.module('test', []);

    app.controller('TestCtrl', function ($scope, $timeout) {
       $scope.testValue = 0;

        $timeout(function() {
            console.log($scope.testValue++);
        }, 500);
    });

The reason is that two-way binding in angular uses dirty checking. This is a good article to read about angular's dirty checking. $scope.$apply() kicks off a $digest cycle. This will apply the binding. $timeout handles the $apply for you so it is the recommended service to use when using timeouts.

Essentially, binding happens during the $digest cycle (if the value is seen to be different).

How to compare numbers in bash?

In bash, you should do your check in arithmetic context:

if (( a > b )); then
    ...
fi

For POSIX shells that don't support (()), you can use -lt and -gt.

if [ "$a" -gt "$b" ]; then
    ...
fi

You can get a full list of comparison operators with help test or man test.

Why doesn't "System.out.println" work in Android?

There is no place on your phone that you can read the System.out.println();

Instead, if you want to see the result of something either look at your logcat/console window or make a Toast or a Snackbar (if you're on a newer device) appear on the device's screen with the message :) That's what i do when i have to check for example where it goes in a switch case code! Have fun coding! :)

Easiest way to loop through a filtered list with VBA?

I used the RowHeight property of a range (which means cells as well). If it's zero then it's hidden. So just loop through all rows as you would normally but in the if condition check for that property as in If myRange.RowHeight > 0 then DoStuff where DoStuff is something you want to do with the visible cells.

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

In my side, it is because POSTMAN setting issue, but I don't know why, maybe I copy a query from other. I simply create a new request in POSTMAN and run it, it works.

button image as form input submit button?

You could use an image submit button:

<input type="image" src="images/login.jpg" alt="Submit Form" />

Only get hash value using md5sum (without filename)

A simple array assignment works... Note that the first element of a bash array can be addressed by just the name without the [0] index, ie, $md5 contains only the 32 chars of the md5sum.

md5=($(md5sum file))
echo $md5
# 53c8fdfcbb60cf8e1a1ee90601cc8fe2

How to create file object from URL object (image)

You can convert the URL to a String and use it to create a new File. e.g.

URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());

Get push notification while App in foreground iOS

Best Approach for this is to add UNUserNotificationCenterDelegate in AppDelegate by using extension AppDelegate: UNUserNotificationCenterDelegate That extension tells the app to be able to get notification when in use

And implement this method

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler(.alert)
    }

This method will be called on the delegate only if the application is in the Foreground.

So The final Implementation:

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler(.alert)
    }
}

And To call this you must set the delegate in AppDelegate in didFinishLaunchingWithOptions add this line

UNUserNotificationCenter.current().delegate = self

You can modify

completionHandler(.alert) 

with

completionHandler([.alert, .badge, .sound]))

Transfer data from one HTML file to another

I use this to set Profile image on each page.

On first page set value as:

localStorage.setItem("imageurl", "ur image url");

or on second page get value as :

var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);

How to explicitly obtain post data in Spring MVC?

Another answer to the OP's exact question is to set the consumes content type to "text/plain" and then declare a @RequestBody String input parameter. This will pass the text of the POST data in as the declared String variable (postPayload in the following example).

Of course, this presumes your POST payload is text data (as the OP stated was the case).

Example:

    @RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
    public ModelAndView someMethod(@RequestBody String postPayload) {    
        // ...    
    }

Find index of last occurrence of a substring in a string

Try this:

s = 'hello plombier pantin'
print (s.find('p'))
6
print (s.index('p'))
6
print (s.rindex('p'))
15
print (s.rfind('p'))

How do I open a Visual Studio project in design view?

You can double click directly on the .cs file representing your form in the Solution Explorer :

Solution explorer with Design View circled

This will open Form1.cs [Design], which contains the drag&drop controls.

If you are directly in the code behind (The file named Form1.cs, without "[Design]"), you can press Shift + F7 (or only F7 depending on the project type) instead to open it.

From the design view, you can switch back to the Code Behind by pressing F7.

Deserialize a JSON array in C#

This code is working fine for me,

var a = serializer.Deserialize<List<Entity>>(json);

Your password does not satisfy the current policy requirements

For Laravel users having this issue with MySQL 8.0.x, add

'modes'=> [
             'ONLY_FULL_GROUP_BY',
             'STRICT_TRANS_TABLES',
             'NO_ZERO_IN_DATE',
             'NO_ZERO_DATE',
             'ERROR_FOR_DIVISION_BY_ZERO',
             'NO_ENGINE_SUBSTITUTION',
            ],

to your database.php file as below:

// database.php

    'connections' => [

        'mysql' => [
            'driver'      => 'mysql',
            'host'        => env( 'DB_HOST', '127.0.0.1' ),
            'port'        => env( 'DB_PORT', '3306' ),
            'database'    => env( 'DB_DATABASE', 'forge' ),
            'username'    => env( 'DB_USERNAME', 'forge' ),
            'password'    => env( 'DB_PASSWORD', '' ),
            'unix_socket' => env( 'DB_SOCKET', '' ),
            'charset'     => 'utf8mb4',
            'collation'   => 'utf8mb4_unicode_ci',
            'prefix'      => '',
            'strict'      => true,
            'engine'      => null,
            'modes'       => [
                'ONLY_FULL_GROUP_BY',
                'STRICT_TRANS_TABLES',
                'NO_ZERO_IN_DATE',
                'NO_ZERO_DATE',
                'ERROR_FOR_DIVISION_BY_ZERO',
                'NO_ENGINE_SUBSTITUTION',
            ],
        ],
    ],

It fixed it for me.

How to get the path of the batch script in Windows?

I am working on a Windows 7 machine and I have ended up using the lines below to get the absolute folder path for my bash script.

I got to this solution after looking at http://www.linuxjournal.com/content/bash-parameter-expansion.

#Get the full aboslute filename.
filename=$0
#Remove everything after \. An extra \ seems to be necessary to escape something...
folder="${filename%\\*}"
#Echo...
echo $filename
echo $folder

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

If you're open to a PHP solution:

<td><img src='<?PHP
  $path1 = "path/to/your/image.jpg";
  $path2 = "alternate/path/to/another/image.jpg";

  echo file_exists($path1) ? $path1 : $path2; 
  ?>' alt='' />
</td>

////EDIT OK, here's a JS version:

<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>

<script type='text/javascript'>
  document.getElementById('myImage').src = "newImage.png";

  document.getElementById('myImage').onload = function() { 
    alert("done"); 
  }

  document.getElementById('myImage').onerror = function() { 
    alert("Inserting alternate");
    document.getElementById('myImage').src = "alternate.png"; 
  }
</script>

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

This actually works in AngularJS. Tested on Chrome and Firefox.

.directive('stopScroll', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.bind('mousewheel', function (e) {
                var $this = $(this),
                    scrollTop = this.scrollTop,
                    scrollHeight = this.scrollHeight,
                    height = $this.height(),
                    delta = (e.type == 'DOMMouseScroll' ?
                    e.originalEvent.detail * -40 :
                        e.originalEvent.wheelDelta),
                    up = delta > 0;

                var prevent = function() {
                    e.stopPropagation();
                    e.preventDefault();
                    e.returnValue = false;
                    return false;
                };

                if (!up && -delta > scrollHeight - height - scrollTop) {
                    // Scrolling down, but this will take us past the bottom.
                    $this.scrollTop(scrollHeight);
                    return prevent();
                } else if (up && delta > scrollTop) {
                    // Scrolling up, but this will take us past the top.
                    $this.scrollTop(0);
                    return prevent();
                }
            });
        }
    };
})

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

In my case everything solved after re-cloning the repo and launching it again.

Setup: Xcode 12.4 Mac M1

UILabel - auto-size label to fit text?

you can show one line output then set property Line=0 and show multiple line output then set property Line=1 and more

[self.yourLableName sizeToFit];

Java: Literal percent sign in printf statement

The percent sign is escaped using a percent sign:

System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);

The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

How to check if div element is empty

Like others have already noted, you can use :empty in jQuery like this:

$('#cartContent:empty').remove();

It will remove the #cartContent div if it is empty.

But this and other techniques that people are suggesting here may not do what you want because if it has any text nodes containing whitespace it is not considered empty. So this is not empty:

<div> </div>

while you may want to consider it empty.

I had this problem some time ago and I wrote this tiny jQuery plugin - just add it to your code:

jQuery.expr[':'].space = function(elem) {
  var $elem = jQuery(elem);
  return !$elem.children().length && !$elem.text().match(/\S/);
}

and now you can use

$('#cartContent:space').remove();

which will remove the div if it is empty or contains only whitespace. Of course you can not only remove it but do anything you like, like

$('#cartContent:space').append('<p>It is empty</p>');

and you can use :not like this:

$('#cartContent:not(:space)').append('<p>It is not empty</p>');

I came out with this test that reliably did what I wanted and you can take it out of the plugin to use it as a standalone test:

This one will work for jQuery objects:

function testEmpty($elem) {
  return !$elem.children().length && !$elem.text().match(/\S/);
}

This one will work for DOM nodes:

function testEmpty(elem) {
  var $elem = jQuery(elem);
  return !$elem.children().length && !$elem.text().match(/\S/);
}

This is better than using .trim because the above code first tests if the tested element has any child elements and if it does it tries to find the first non-whitespace character and then stops, without the need to read or mutate the string if it has even one character that is not whitespace.

Hope it helps.

How to show one layout on top of the other programmatically in my case?

FrameLayout is not the better way to do this:

Use RelativeLayout instead. You can position the elements anywhere you like. The element that comes after, has the higher z-index than the previous one (i.e. it comes over the previous one).

Example:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary"
        app:srcCompat="@drawable/ic_information"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a text."
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_margin="8dp"
        android:padding="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:background="#A000"
        android:textColor="@android:color/white"/>
</RelativeLayout>

enter image description here

Error: request entity too large

The following worked for me... Just use

app.use(bodyParser({limit: '50mb'}));

that's it.

Tried all above and none worked. Found that even though we use like the following,

app.use(bodyParser());
app.use(bodyParser({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb'}));

only the 1st app.use(bodyParser()); one gets defined and the latter two lines were ignored.

Refer: https://github.com/expressjs/body-parser/issues/176 >> see 'dougwilson commented on Jun 17, 2016'

Compile error: package javax.servlet does not exist

place jakarta and delete javax

if you download servlet.api.jar :

NOTICE : this answer every time is not correct ( can be javax in JEE )

Correct

jakarta.servlet.*;

Incorrect

javax.servlet.*;

else :

place jar files into JAVA_HOME/jre/lib/ext

Android java.lang.NoClassDefFoundError

I fixed the issue by just adding private libraries of the main project to export here:

Project Properties->Java Build Path->Order And Export

And make sure Android Private Libraries are checked.

Screenshot:

enter image description here

Make sure google-play-services_lib.jar and google-play-services.jar are checked. Clean the project and re-run and the classNotfound exception goes away.

How to push objects in AngularJS between ngRepeat arrays

change your method to:

$scope.toggleChecked = function (index) {
    $scope.checked.push($scope.items[index]);
    $scope.items.splice(index, 1);
};

Working Demo

What is __pycache__?

Python Version 2.x will have .pyc when interpreter compiles the code.

Python Version 3.x will have __pycache__ when interpreter compiles the code.

alok@alok:~$ ls
module.py  module.pyc  __pycache__  test.py
alok@alok:~$

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Here are some more tests

True if string is not empty:

[ -n "$var" ]
[[ -n $var ]]
test -n "$var"
[ "$var" ]
[[ $var ]]
(( ${#var} ))
let ${#var}
test "$var"

True if string is empty:

[ -z "$var" ]
[[ -z $var ]]
test -z "$var"
! [ "$var" ]
! [[ $var ]]
! (( ${#var} ))
! let ${#var}
! test "$var"

SQL Server Script to create a new user

You can use:

CREATE LOGIN <login name> WITH PASSWORD = '<password>' ; GO 

To create the login (See here for more details).

Then you may need to use:

CREATE USER user_name 

To create the user associated with the login for the specific database you want to grant them access too.

(See here for details)

You can also use:

GRANT permission  [ ,...n ] ON SCHEMA :: schema_name

To set up the permissions for the schema's that you assigned the users to.

(See here for details)

Two other commands you might find useful are ALTER USER and ALTER LOGIN.

sql insert into table with select case values

You have the alias inside of the case, it needs to be outside of the END:

Insert into TblStuff (FullName,Address,City,Zip)
Select
  Case
    When Middle is Null 
    Then Fname + LName
    Else Fname +' ' + Middle + ' '+ Lname
  End as FullName,
  Case
    When Address2 is Null Then Address1
    else Address1 +', ' + Address2 
  End as  Address,
  City as City,
  Zip as Zip
from tblImport

Dart/Flutter : Converting timestamp

if anyone come here to convert firebase Timestamp here this will help

Timestamp time;
DateTime.fromMicrosecondsSinceEpoch(time.microsecondsSinceEpoch)

How to add a boolean datatype column to an existing table in sql?

In SQL SERVER it is BIT, though it allows NULL to be stored

ALTER TABLE person add  [AdminApproved] BIT default 'FALSE';

Also there are other mistakes in your query

  1. When you alter a table to add column no need to mention column keyword in alter statement

  2. For adding default constraint no need to use SET keyword

  3. Default value for a BIT column can be ('TRUE' or '1') / ('FALSE' or 0). TRUE or FALSE needs to mentioned as string not as Identifier

Openssl is not recognized as an internal or external command

For those looking for a more recent location to install a windows binary version of openssl (32bit and 64bit) you can find it here:

http://slproweb.com/products/Win32OpenSSL.html

An up to date list of websites that offer binary distributions is here

http://www.openssl.org/related/binaries.html

How do I disable a Pylint warning?

You can also use the following command:

pylint --disable=C0321  test.py

My Pylint version is 0.25.1.

Making an asynchronous task in Flask

Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative.

This solution is based on Miguel Grinberg's PyCon 2016 Flask at Scale presentation, specifically slide 41 in his slide deck. His code is also available on github for those interested in the original source.

From a user perspective the code works as follows:

  1. You make a call to the endpoint that performs the long running task.
  2. This endpoint returns 202 Accepted with a link to check on the task status.
  3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete.

To convert an api call to a background task, simply add the @async_api decorator.

Here is a fully contained example:

from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid

tasks = {}

app = Flask(__name__)
api = Api(app)


@app.before_first_request
def before_first_request():
    """Start a background thread that cleans up old tasks."""
    def clean_old_tasks():
        """
        This function cleans up old tasks from our in-memory data structure.
        """
        global tasks
        while True:
            # Only keep tasks that are running or that finished less than 5
            # minutes ago.
            five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
            tasks = {task_id: task for task_id, task in tasks.items()
                     if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
            time.sleep(60)

    if not current_app.config['TESTING']:
        thread = threading.Thread(target=clean_old_tasks)
        thread.start()


def async_api(wrapped_function):
    @wraps(wrapped_function)
    def new_function(*args, **kwargs):
        def task_call(flask_app, environ):
            # Create a request context similar to that of the original request
            # so that the task can have access to flask.g, flask.request, etc.
            with flask_app.request_context(environ):
                try:
                    tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['return_value'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())

                    # close the database session (if any)

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task_thread': threading.Thread(
            target=task_call, args=(current_app._get_current_object(),
                               request.environ))}
        tasks[task_id]['task_thread'].start()

        # Return a 202 response, with a link that the client can use to
        # obtain task status
        print(url_for('gettaskstatus', task_id=task_id))
        return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
    return new_function


class GetTaskStatus(Resource):
    def get(self, task_id):
        """
        Return status about an asynchronous task. If this request returns a 202
        status code, it means that task hasn't finished yet. Else, the response
        from the task is returned.
        """
        task = tasks.get(task_id)
        if task is None:
            abort(404)
        if 'return_value' not in task:
            return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
        return task['return_value']


class CatchAll(Resource):
    @async_api
    def get(self, path=''):
        # perform some intensive processing
        print("starting processing task, path: '%s'" % path)
        time.sleep(10)
        print("completed processing task, path: '%s'" % path)
        return f'The answer is: {path}'


api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')


if __name__ == '__main__':
    app.run(debug=True)

Is there a way I can retrieve sa password in sql server 2005

There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).

Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.

enter image description here

Now write down the new SA password.

Create a CSV File for a user in PHP

Hey It works very well....!!!! Thanks Peter Mortensen and Connor Burton

<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);

mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());

$start = $_GET["start"];
$end = $_GET["end"];

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

?>

How to hide Bootstrap previous modal when you opening new one?

The best that I've been able to do is

$(this).closest('.modal').modal('toggle');

This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

You can however do this:

$(".modal:visible").modal('toggle');

This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

Changing file permission in Python

You can use, pathlib also

from pathlib import Path

fl = Path("file_name")

fl.chmod(0o444)

How do I use Spring Boot to serve static content located in Dropbox folder?

  • OS: Win 10
  • Spring Boot: 2.1.2

I wanted to serve static content from c:/images

Adding this property worked for me:

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:///C:/images/

I found the original value of the property in the Spring Boot Doc Appendix A

This will make c:/images/image.jpg to be accessible as http://localhost:8080/image.jpg

How can I get the count of milliseconds since midnight for the current?

tl;dr

You ask for the fraction of a second of the current time as a number of milliseconds (not count from epoch).

Instant.now()                               // Get current moment in UTC, then…
       .get( ChronoField.MILLI_OF_SECOND )  // interrogate a `TemporalField`.

2017-04-25T03:01:14.113Z ? 113

  1. Get the fractional second in nanoseconds (billions).
  2. Divide by a thousand to truncate to milliseconds (thousands).

See this code run live at IdeOne.com.

Using java.time

The modern way is with the java.time classes.

Capture the current moment in UTC.

Instant.now()

Use the Instant.get method to interrogate for the value of a TemporalField. In our case, the TemporalField we want is ChronoField.MILLI_OF_SECOND.

int millis = Instant.now().get( ChronoField.MILLI_OF_SECOND ) ;  // Get current moment in UTC, then interrogate a `TemporalField`.

Or do the math yourself.

More likely you are asking this for a specific time zone. The fraction of a second is likely to be the same as with Instant but there are so many anomalies with time zones, I hesitate to make that assumption.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) ;

Interrogate for the fractional second. The Question asked for milliseconds, but java.time classes use a finer resolution of nanoseconds. That means the number of nanoseconds will range from from 0 to 999,999,999.

long nanosFractionOfSecond = zdt.getNano();

If you truly want milliseconds, truncate the finer data by dividing by one million. For example, a half second is 500,000,000 nanoseconds and also is 500 milliseconds.

long millis = ( nanosFractionOfSecond / 1_000_000L ) ;  // Truncate nanoseconds to milliseconds, by a factor of one million.

About java.time

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

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

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

Where to obtain the java.time classes?

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

How to show MessageBox on asp.net?

Messagebox is for windows only. You have to use Javascript

Alert('dd'); 

Convert line endings

Doing this with POSIX is tricky:

  • POSIX Sed does not support \r or \15. Even if it did, the in place option -i is not POSIX

  • POSIX Awk does support \r and \15, however the -i inplace option is not POSIX

  • d2u and dos2unix are not POSIX utilities, but ex is

  • POSIX ex does not support \r, \15, \n or \12

To remove carriage returns:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file

To add carriage returns:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file

Git commit with no commit message

The commit message is a best practice that should be followed at all times. Unless you're the only developer and that isn't going to change any time soon.

git commit -a -m 'asdfasdfadsfsdf'

How to animate the change of image in an UIImageView?

With Swift 3

extension UIImageView{   
 var imageWithFade:UIImage?{
        get{
            return self.image
        }
        set{
            UIView.transition(with: self,
                              duration: 0.5, options: .transitionCrossDissolve, animations: {
                                self.image = newValue
            }, completion: nil)
        }
    }
}

Usage:

myImageView.imageWithFade = myImage

Converting camel case to underscore case in ruby

One-liner Ruby implementation:

class String
   # ruby mutation methods have the expectation to return self if a mutation occurred, nil otherwise. (see http://www.ruby-doc.org/core-1.9.3/String.html#method-i-gsub-21)
   def to_underscore!
     gsub!(/(.)([A-Z])/,'\1_\2')
     downcase!
   end

   def to_underscore
     dup.tap { |s| s.to_underscore! }
   end
end

So "SomeCamelCase".to_underscore # =>"some_camel_case"

How to Configure SSL for Amazon S3 bucket

Custom domain SSL certs were just added today for $600/cert/month. Sign up for your invite below: http://aws.amazon.com/cloudfront/custom-ssl-domains/

Update: SNI customer provided certs are now available for no additional charge. Much cheaper than $600/mo, and with XP nearly killed off, it should work well for most use cases.

@skalee AWS has a mechanism for achieving what the poster asks for, "implement SSL for an Amazon s3 bucket", it's called CloudFront. I'm reading "implement" as "use my SSL certs," not "just put an S on the HTTP URL which I'm sure the OP could have surmised.

Since CloudFront costs exactly the same as S3 ($0.12/GB), but has a ton of additional features around SSL AND allows you to add your own SNI cert at no additional cost, it's the obvious fix for "implementing SSL" on your domain.

Bootstrap Align Image with text

You have two choices, either correct your markup so that it uses correct elements and utilizes the Bootstrap grid system:

_x000D_
_x000D_
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
     <h1>About Me</h1>_x000D_
    <div class="row">_x000D_
        <div class="col-md-4">_x000D_
            <div class="imgAbt">_x000D_
                <img width="220" height="220" src="img/me.jpg" />_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-md-8">_x000D_
            <p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or, if you wish the text to closely wrap the image, change your markup to:

_x000D_
_x000D_
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
    <h1>About Me</h1>_x000D_
    <div class="row">_x000D_
        <div class="col-md-12">_x000D_
            <img style='float:left;width:200px;height:200px; margin-right:10px;' src="img/me.jpg" />_x000D_
            <p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
        </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

How can I get a Unicode character's code?

For me, only "Integer.toHexString(registered)" worked the way I wanted:

char registered = '®';
System.out.println("Answer:"+Integer.toHexString(registered));

This answer will give you only string representations what are usually presented in the tables. Jon Skeet's answer explains more.

How to remove new line characters from data rows in mysql?

Removes trailing returns when importing from Excel. When you execute this, you may receive an error that there is no WHERE; ignore and execute.

UPDATE table_name SET col_name = TRIM(TRAILING '\r' FROM col_name)

Pass in an array of Deferreds to $.when()

I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.

Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.

    // 1st
    function Outer() {
        var deferreds = GetAllData();

        $.when.apply($, deferreds).done(function () {
            // now you can do whatever you want with the updated page
        });
    }

    // 2nd
    function GetAllData() {
        var deferreds = [];
        $('.calculatedField').each(function (data) {
            deferreds.push(GetIndividualData($(this)));
        });
        return deferreds;
    }

    // 3rd
    function GetIndividualData(item) {
        var def = new $.Deferred();
        $.post('@Url.Action("GetData")', function (data) {
            item.html(data.valueFromAjax);
            def.resolve(data);
        });
        return def;
    }

How do I pass a command line argument while starting up GDB in Linux?

Once gdb starts, you can run the program using "r args".

So if you are running your code by:

$ executablefile arg1 arg2 arg3 

Debug it on gdb by:

$ gdb executablefile  
(gdb) r arg1 arg2 arg3

Jump into interface implementation in Eclipse IDE

Well... well... I hope you use Eclipse Helios, because what you asked is available on Helios.

Put your text cursor again on the method and click menu Navigate ? Open Implementation. Now if you have more than one implementation of the method, you will get choice to pick which implementation to open.

alt text

By defining a keybinding on Preferences ? General ? Keys you can even use the feature easier, but before you do that, see if this shortcut is fast enough for you.

Press Ctrl + click and hold. Now move your mouse over the same method. Tadam… you will get choice.

alt text

If you pick Open Implementation you’ll get the same choice as before.

Using sudo with Python script

Many answers focus on how to make your solution work, while very few suggest that your solution is a very bad approach. If you really want to "practice to learn", why not practice using good solutions? Hardcoding your password is learning the wrong approach!

If what you really want is a password-less mount for that volume, maybe sudo isn't needed at all! So may I suggest other approaches?

  • Use /etc/fstab as mensi suggested. Use options user and noauto to let regular users mount that volume.

  • Use Polkit for passwordless actions: Configure a .policy file for your script with <allow_any>yes</allow_any> and drop at /usr/share/polkit-1/actions

  • Edit /etc/sudoers to allow your user to use sudo without typing your password. As @Anders suggested, you can restrict such usage to specific commands, thus avoiding unlimited passwordless root priviledges in your account. See this answer for more details on /etc/sudoers.

All the above allow passwordless root privilege, none require you to hardcode your password. Choose any approach and I can explain it in more detail.

As for why it is a very bad idea to hardcode passwords, here are a few good links for further reading:

SQL Server insert if not exists best practice

Don't know why anyone else hasn't said this yet;

NORMALISE.

You've got a table that models competitions? Competitions are made up of Competitors? You need a distinct list of Competitors in one or more Competitions......

You should have the following tables.....

CREATE TABLE Competitor (
    [CompetitorID] INT IDENTITY(1,1) PRIMARY KEY
    , [CompetitorName] NVARCHAR(255)
    )

CREATE TABLE Competition (
    [CompetitionID] INT IDENTITY(1,1) PRIMARY KEY
    , [CompetitionName] NVARCHAR(255)
    )

CREATE TABLE CompetitionCompetitors (
    [CompetitionID] INT
    , [CompetitorID] INT
    , [Score] INT

    , PRIMARY KEY (
        [CompetitionID]
        , [CompetitorID]
        )
    )

With Constraints on CompetitionCompetitors.CompetitionID and CompetitorID pointing at the other tables.

With this kind of table structure -- your keys are all simple INTS -- there doesn't seem to be a good NATURAL KEY that would fit the model so I think a SURROGATE KEY is a good fit here.

So if you had this then to get the the distinct list of competitors in a particular competition you can issue a query like this:

DECLARE @CompetitionName VARCHAR(50) SET @CompetitionName = 'London Marathon'

    SELECT
        p.[CompetitorName] AS [CompetitorName]
    FROM
        Competitor AS p
    WHERE
        EXISTS (
            SELECT 1
            FROM
                CompetitionCompetitor AS cc
                JOIN Competition AS c ON c.[ID] = cc.[CompetitionID]
            WHERE
                cc.[CompetitorID] = p.[CompetitorID]
                AND cc.[CompetitionName] = @CompetitionNAme
        )

And if you wanted the score for each competition a competitor is in:

SELECT
    p.[CompetitorName]
    , c.[CompetitionName]
    , cc.[Score]
FROM
    Competitor AS p
    JOIN CompetitionCompetitor AS cc ON cc.[CompetitorID] = p.[CompetitorID]
    JOIN Competition AS c ON c.[ID] = cc.[CompetitionID]

And when you have a new competition with new competitors then you simply check which ones already exist in the Competitors table. If they already exist then you don't insert into Competitor for those Competitors and do insert for the new ones.

Then you insert the new Competition in Competition and finally you just make all the links in CompetitionCompetitors.

How to convert a SVG to a PNG with ImageMagick?

The top answer by @808sound did not work for me. I wanted to resize Kenney.nl UI Pack

and got Kenney UI Pack messed up

So instead I opened up Inkscape, then went to File, Export as PNG fileand a GUI box popped up that allowed me to set the exact dimensions I needed.

Version on Ubuntu 16.04 Linux: Inkscape 0.91 (September 2016)

(This image is from Kenney.nl's asset packs by the way)

Main differences between SOAP and RESTful web services in Java

  1. REST has no WSDL (Web Description Language) interface definition.

  2. REST is over HTTP, but SOAP can be over any transport protocols such as HTTP, FTP, SMTP, JMS, etc.

How do I make a C++ macro behave like a function?

C++11 brought us lambdas, which can be incredibly useful in this situation:

#define MACRO(X,Y)                              \
    [&](x_, y_) {                               \
        cout << "1st arg is:" << x_ << endl;    \
        cout << "2nd arg is:" << y_ << endl;    \
        cout << "Sum is:" << (x_ + y_) << endl; \
    }((X), (Y))

You keep the generative power of macros, but have a comfy scope from which you can return whatever you want (including void). Additionally, the issue of evaluating macro parameters multiple times is avoided.

Use RSA private key to generate public key?

The Public Key is not stored in the PEM file as some people think. The following DER structure is present on the Private Key File:

openssl rsa -text -in mykey.pem

RSAPrivateKey ::= SEQUENCE {
  version           Version,
  modulus           INTEGER,  -- n
  publicExponent    INTEGER,  -- e
  privateExponent   INTEGER,  -- d
  prime1            INTEGER,  -- p
  prime2            INTEGER,  -- q
  exponent1         INTEGER,  -- d mod (p-1)
  exponent2         INTEGER,  -- d mod (q-1)
  coefficient       INTEGER,  -- (inverse of q) mod p
  otherPrimeInfos   OtherPrimeInfos OPTIONAL
}

So there is enough data to calculate the Public Key (modulus and public exponent), which is what openssl rsa -in mykey.pem -pubout does

Can I pass parameters by reference in Java?

Another option is to use an array, e.g. void method(SomeClass[] v) { v[0] = ...; } but 1) the array must be initialized before method invoked, 2) still one cannot implement e.g. swap method in this way... This way is used in JDK, e.g. in java.util.concurrent.atomic.AtomicMarkableReference.get(boolean[]).

How can I convert a string with dot and comma into a float in Python

Just remove the , with replace():

float("123,456.908".replace(',',''))

Ansible: copy a directory content to another directory

How to copy directory and sub dirs's and files from ansible server to remote host

- name: copy nmonchart39 directory  to {{ inventory_hostname }}
  copy:
    src: /home/ansib.usr.srv/automation/monitoring/nmonchart39
    dest: /var/nmon/data


Where:
copy entire directory: src: /automation/monitoring/nmonchart39
copy directory contents src: nmonchart39/

Regex number between 1 and 100

Try it, This will work more efficiently.. 1. For number ranging 00 - 99.99 (decimal inclusive)

^([0-9]{1,2}){1}(\.[0-9]{1,2})?$ 

Working fiddle link

https://regex101.com/r/d1Kdw5/1/

2.For number ranging 1-100(inclusive) with no preceding 0.

(?:\b|-)([1-9]{1,2}[0]?|100)\b

Working Fiddle link

http://regex101.com/r/mN1iT5/6

Fastest way to check a string contain another substring in JavaScript?

Does this work for you?

string1.indexOf(string2) >= 0

Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.

Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.

Weird behavior of the != XPath operator

The problem is that the 'and' is being treated as an 'or'.

No, the problem is that you are using the XPath != operator and you aren't aware of its "weird" semantics.

Solution:

Just replace the any x != y expressions with a not(x = y) expression.

In your specific case:

Replace:

<xsl:when test="$AccountNumber != '12345' and $Balance != '0'">

with:

<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')">

Explanation:

By definition whenever one of the operands of the != operator is a nodeset, then the result of evaluating this operator is true if there is a node in the node-set, whose value isn't equal to the other operand.

So:

 $someNodeSet != $someValue

generally doesn't produce the same result as:

 not($someNodeSet = $someValue)

The latter (by definition) is true exactly when there isn't a node in $someNodeSet whose string value is equal to $someValue.

Lesson to learn:

Never use the != operator, unless you are absolutely sure you know what you are doing.

How do you set autocommit in an SQL Server session?

Autocommit is SQL Server's default transaction management mode. (SQL 2000 onwards)

Ref: Autocommit Transactions

MySQL connection not working: 2002 No such file or directory

On a Mac, before doing all the hard work, simply check your settings in System Preferences > MySQL. More often than not, I've experienced the team running into this problem since The MySQL Server Instance is stopped.

Click the Start MySQL Server button, and magic will happen.

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

Here is a slight improvement on the this answer above taking care of both .xlsx and .xls files in the same routine, in case it helps someone!

I also add a line to choose to save with the active sheet name instead of the workbook, which is most practical for me often:

Sub ExportAsCSV()

    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook

    Set CurrentWB = ActiveWorkbook
    ActiveWorkbook.ActiveSheet.UsedRange.Copy

    Set TempWB = Application.Workbooks.Add(1)
    With TempWB.Sheets(1).Range("A1")
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
    End With

    MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, InStrRev(CurrentWB.Name, ".") - 1) & ".csv"
    'Optionally, comment previous line and uncomment next one to save as the current sheet name
    'MyFileName = CurrentWB.Path & "\" & CurrentWB.ActiveSheet.Name & ".csv"


    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True
End Sub

How do I (or can I) SELECT DISTINCT on multiple columns?

If your DBMS doesn't support distinct with multiple columns like this:

select distinct(col1, col2) from table

Multi select in general can be executed safely as follows:

select distinct * from (select col1, col2 from table ) as x

As this can work on most of the DBMS and this is expected to be faster than group by solution as you are avoiding the grouping functionality.

How to change MenuItem icon in ActionBar programmatically

Instead of getViewById(), use

MenuItem item = getToolbar().getMenu().findItem(Menu.FIRST);

replacing the Menu.FIRST with your menu item id.

Java: How to convert String[] to List or Set

java.util.Arrays.asList(new String[]{"a", "b"})

What is a NoReverseMatch error, and how do I fix it?

And make sure your route in the list of routes:

./manage.py show_urls | grep path_or_name

https://github.com/django-extensions/django-extensions

SQL SERVER: Get total days between two dates

Another date format

select datediff(day,'20110101','20110301')

How to grep, excluding some patterns?

-v is the "inverted match" flag, so piping is a very good way:

grep "loom" ~/projects/**/trunk/src/**/*.@(h|cpp)| grep -v "gloom"

Wrap text in <td> tag

Apply classes to your TDs, apply the appropriate widths (remember to leave one of them without a width so it assumes the remainder of the width), then apply the appropriate styles. Copy and paste the code below into an editor and view in a browser to see it function.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
td { vertical-align: top; }
.leftcolumn { background: #CCC; width: 20%; padding: 10px; }
.centercolumn { background: #999; padding: 10px; width: 15%; }
.rightcolumn { background: #666; padding: 10px; }
-->
</style>
</head>

<body>
<table border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td class="leftcolumn">This is the left column. It is set to 20% width.</td>
    <td class="centercolumn">
        <p>Hi,</p>
        <p>I want to wrap a text that is added to the TD. I have tried with style="word-wrap: break-word;" width="15%". But the wrap is not happening. Is it mandatory to give 100% width ? But I have got other controls to display so only 15% width available.</p>
        <p>Need help.</p>
        <p>TIA.</p>
    </td>
    <td class="rightcolumn">This is the right column, it has no width so it assumes the remainder from the 15% and 20% assumed by the others. By default, if a width is applied and no white-space declarations are made, your text will automatically wrap.</td>
  </tr>
</table>
</body>
</html>

SELECT INTO USING UNION QUERY

INSERT INTO #Temp1
SELECT val1, val2 
FROM TABLE1
 UNION
SELECT val1, val2
FROM TABLE2

How to convert an iterator to a stream?

Create Spliterator from Iterator using Spliterators class contains more than one function for creating spliterator, for example here am using spliteratorUnknownSize which is getting iterator as parameter, then create Stream using StreamSupport

Spliterator<Model> spliterator = Spliterators.spliteratorUnknownSize(
        iterator, Spliterator.NONNULL);
Stream<Model> stream = StreamSupport.stream(spliterator, false);

Nodejs - Redirect url

To indicate a missing file/resource and serve a 404 page, you need not redirect. In the same request you must generate the response with the status code set to 404 and the content of your 404 HTML page as response body. Here is the sample code to demonstrate this in Node.js.

var http = require('http'),
    fs = require('fs'),
    util = require('util'),
    url = require('url');

var server = http.createServer(function(req, res) {
    if(url.parse(req.url).pathname == '/') {
        res.writeHead(200, {'content-type': 'text/html'});
        var rs = fs.createReadStream('index.html');
        util.pump(rs, res);
    } else {
        res.writeHead(404, {'content-type': 'text/html'});
        var rs = fs.createReadStream('404.html');
        util.pump(rs, res);
    }
});

server.listen(8080);

CSS background-size: cover replacement for Mobile Safari

I found the following on Stephen Gilbert's website - http://stephen.io/mediaqueries/. It includes additional devices and their orientations. Works for me!

Note: If you copy the code from his site, you'll want to edit it for extra spaces, depending on the editor you're using.

/*iPad in portrait & landscape*/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) { /* STYLES GO HERE */}

/*iPad in landscape*/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) { /* STYLES GO HERE */}

/*iPad in portrait*/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) { /* STYLES GO HERE */ }

Simple division in Java - is this a bug or a feature?

You're using integer division.

Try 7.0/10 instead.

Swipe ListView item From right to left show delete button

It's a lose of time to implement from scratch this functionality. I implemented the library recommended by SalutonMondo and I am very satisfied. It is very simple to use and very quick. I improved the original library and I added a new click listener for item click. Also I added font awesome library (http://fortawesome.github.io/Font-Awesome/) and now you can simply add a new item title and specify the icon name from font awesome.

Here is the github link

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

Are the days of passing const std::string & as a parameter over?

See “Herb Sutter "Back to the Basics! Essentials of Modern C++ Style”. Among other topics, he reviews the parameter passing advice that’s been given in the past, and new ideas that come in with C++11 and specifically looks at the idea of passing strings by value.

slide 24

The benchmarks show that passing std::strings by value, in cases where the function will copy it in anyway, can be significantly slower!

This is because you are forcing it to always make a full copy (and then move into place), while the const& version will update the old string which may reuse the already-allocated buffer.

See his slide 27: For “set” functions, option 1 is the same as it always was. Option 2 adds an overload for rvalue reference, but this gives a combinatorial explosion if there are multiple parameters.

It is only for “sink” parameters where a string must be created (not have its existing value changed) that the pass-by-value trick is valid. That is, constructors in which the parameter directly initializes the member of the matching type.

If you want to see how deep you can go in worrying about this, watch Nicolai Josuttis’s presentation and good luck with that (“Perfect — Done!” n times after finding fault with the previous version. Ever been there?)


This is also summarized as ?F.15 in the Standard Guidelines.

Create Table from View

SELECT * INTO [table_a] FROM dbo.myView

Usage of @see in JavaDoc?

The @see tag is a bit different than the @link tag,
limited in some ways and more flexible in others:

different JavaDoc link types Different JavaDoc link types

  1. Displays the member name for better learning, and is refactorable; the name will update when renaming by refactor
  2. Refactorable and customizable; your text is displayed instead of the member name
  3. Displays name, refactorable
  4. Refactorable, customizable
  5. A rather mediocre combination that is:
  • Refactorable, customizable, and stays in the See Also section
  • Displays nicely in the Eclipse hover
  • Displays the link tag and its formatting when generated
  • When using multiple @see items, commas in the description make the output confusing
  1. Completely illegal; causes unexpected content and illegal character errors in the generator

See the results below:

JavaDoc generation results with different link types JavaDoc generation results with different link types

Best regards.

Run a .bat file using python code

If you are trying to call another exe file inside the bat-file. You must use SET Path inside the bat-file that you are calling. set Path should point into the directory there the exe-file is located:

set PATH=C:\;C:\DOS     {Sets C:\;C:\DOS as the current search path.} 

How can you dynamically create variables via a while loop?

NOTE: This should be considered a discussion rather than an actual answer.

An approximate approach is to operate __main__ in the module you want to create variables. For example there's a b.py:

#!/usr/bin/env python
# coding: utf-8


def set_vars():
    import __main__
    print '__main__', __main__
    __main__.B = 1

try:
    print B
except NameError as e:
    print e

set_vars()

print 'B: %s' % B

Running it would output

$ python b.py
name 'B' is not defined
__main__ <module '__main__' from 'b.py'>
B: 1

But this approach only works in a single module script, because the __main__ it import will always represent the module of the entry script being executed by python, this means that if b.py is involved by other code, the B variable will be created in the scope of the entry script instead of in b.py itself. Assume there is a script a.py:

#!/usr/bin/env python
# coding: utf-8

try:
    import b
except NameError as e:
    print e

print 'in a.py: B', B

Running it would output

$ python a.py
name 'B' is not defined
__main__ <module '__main__' from 'a.py'>
name 'B' is not defined
in a.py: B 1

Note that the __main__ is changed to 'a.py'.

How to add days to the current date?

In SQL Server 2008 and above just do this:

SELECT DATEADD(day, 1, Getdate()) AS DateAdd;

How to mount host volumes into docker containers in Dockerfile during build

There is a way to mount a volume during a build, but it doesn't involve Dockerfiles.

The technique would be to create a container from whatever base you wanted to use (mounting your volume(s) in the container with the -v option), run a shell script to do your image building work, then commit the container as an image when done.

Not only will this leave out the excess files you don't want (this is good for secure files as well, like SSH files), it also creates a single image. It has downsides: the commit command doesn't support all of the Dockerfile instructions, and it doesn't let you pick up when you left off if you need to edit your build script.

UPDATE:

For example,

CONTAINER_ID=$(docker run -dit ubuntu:16.04)
docker cp build.sh $CONTAINER_ID:/build.sh
docker exec -t $CONTAINER_ID /bin/sh -c '/bin/sh /build.sh'
docker commit $CONTAINER_ID $REPO:$TAG
docker stop $CONTAINER_ID

How do I pass a variable by reference?

There are no variables in Python

The key to understanding parameter passing is to stop thinking about "variables". There are names and objects in Python and together they appear like variables, but it is useful to always distinguish the three.

  1. Python has names and objects.
  2. Assignment binds a name to an object.
  3. Passing an argument into a function also binds a name (the parameter name of the function) to an object.

That is all there is to it. Mutability is irrelevant to this question.

Example:

a = 1

This binds the name a to an object of type integer that holds the value 1.

b = x

This binds the name b to the same object that the name x is currently bound to. Afterward, the name b has nothing to do with the name x anymore.

See sections 3.1 and 4.2 in the Python 3 language reference.

How to read the example in the question

In the code shown in the question, the statement self.Change(self.variable) binds the name var (in the scope of function Change) to the object that holds the value 'Original' and the assignment var = 'Changed' (in the body of function Change) assigns that same name again: to some other object (that happens to hold a string as well but could have been something else entirely).

How to pass by reference

So if the thing you want to change is a mutable object, there is no problem, as everything is effectively passed by reference.

If it is an immutable object (e.g. a bool, number, string), the way to go is to wrap it in a mutable object.
The quick-and-dirty solution for this is a one-element list (instead of self.variable, pass [self.variable] and in the function modify var[0]).
The more pythonic approach would be to introduce a trivial, one-attribute class. The function receives an instance of the class and manipulates the attribute.

How to generate unique ID with node.js

to install uuid

npm install --save uuid

uuid is updated and the old import

const uuid= require('uuid/v4');

is not working and we should now use this import

const {v4:uuid} = require('uuid');

and for using it use as a funciton like this

const  createdPlace = {
    id: uuid(),
    title,
    description,
    location:coordinates,
    address,
    creator
  };

How do I query using fields inside the new PostgreSQL JSON datatype?

Postgres 9.2

I quote Andrew Dunstan on the pgsql-hackers list:

At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.

Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.

Postgres 9.3

Offers an arsenal of new functions and operators to add "json-processing".

The answer to the original question in Postgres 9.3:

SELECT *
FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ]'
  ) AS elem
WHERE elem->>'name' = 'Toby';

Advanced example:

For bigger tables you may want to add an expression index to increase performance:

Postgres 9.4

Adds jsonb (b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb also supports GIN, btree and hash indexes, GIN being the most potent of these.

The manual goes as far as suggesting:

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

Bold emphasis mine.

Performance benefits from general improvements to GIN indexes.

Postgres 9.5

Complete jsonb functions and operators. Add more functions to manipulate jsonb in place and for display.

How to format a QString?

You can use QString.arg like this

QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"

This method is preferred over sprintf because:

Changing the position of the string without having to change the ordering of substitution, e.g.

// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");

Or, changing the type of the arguments doesn't require changing the format string, e.g.

// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));

As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.

One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.

UPDATE: Examples are updated thanks to Frank Osterfeld.

UPDATE: Examples are updated thanks to alexisdm.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

Yes Fiddler is an option for me:

  1. Open Fiddler menu > Rules > Customize Rules (this effectively edits CustomRules.js).
  2. Find the function OnBeforeResponse
  3. Add the following lines:

    oSession.oResponse.headers.Remove("X-Frame-Options");
    oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
    
  4. Remember to save the script!

Correct way to convert size in bytes to KB, MB, GB in JavaScript

I originally used @Aliceljm's answer for a file upload project I was working on, but recently ran into an issue where a file was 0.98kb but being read as 1.02mb. Here's the updated code I'm now using.

function formatBytes(bytes){
  var kb = 1024;
  var ndx = Math.floor( Math.log(bytes) / Math.log(kb) );
  var fileSizeTypes = ["bytes", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"];

  return {
    size: +(bytes / kb / kb).toFixed(2),
    type: fileSizeTypes[ndx]
  };
}

The above would then be called after a file was added like so

// In this case `file.size` equals `26060275` 
formatBytes(file.size);
// returns `{ size: 24.85, type: "mb" }`

Granted, Windows reads the file as being 24.8mb but I'm fine with the extra precision.

jQuery: Check if special characters exists in string

var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
var check = function(string){
    for(i = 0; i < specialChars.length;i++){
        if(string.indexOf(specialChars[i]) > -1){
            return true
        }
    }
    return false;
}

if(check($('#Search').val()) == false){
    // Code that needs to execute when none of the above is in the string
}else{
    alert('Your search string contains illegal characters.');
}

How to parse a JSON object to a TypeScript Object

Your JSON data may have some properties that you do not have in your class. For mapping You can do simple custom mapping

export class Employe{ ////
    static parse(json: string) {
           var data = JSON.parse(json);
            return new Employe(data.typeOfEmployee_id, data.firstName.. and others);
       }
}

and also specifying constructor in your Employee class.

"error: assignment to expression with array type error" when I assign a struct field (C)

typedef struct{
     char name[30];
     char surname[30];
     int age;
} data;

defines that data should be a block of memory that fits 60 chars plus 4 for the int (see note)

[----------------------------,------------------------------,----]
 ^ this is name              ^ this is surname              ^ this is age

This allocates the memory on the stack.

data s1;

Assignments just copies numbers, sometimes pointers.

This fails

s1.name = "Paulo";

because the compiler knows that s1.name is the start of a struct 64 bytes long, and "Paulo" is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.

To copy "Paulo" into the struct at the point name and "Rossi" into the struct at point surname.

memcpy(s1.name,    "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;

You end up with

[Paulo0----------------------,Rossi0-------------------------,0001]

strcpy does the same thing but it knows about \0 termination so does not need the length hardcoded.

Alternatively you can define a struct which points to char arrays of any length.

typedef struct {
  char *name;
  char *surname;
  int age;
} data;

This will create

[----,----,----]

This will now work because you are filling the struct with pointers.

s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;

Something like this

[---4,--10,---1]

Where 4 and 10 are pointers.

Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.

converting multiple columns from character to numeric format in r

I realize this is an old thread but wanted to post a solution similar to your request for a function (just ran into the similar issue myself trying to format an entire table to percentage labels).

Assume you have a df with 5 character columns you want to convert. First, I create a table containing the names of the columns I want to manipulate:

col_to_convert <- data.frame(nrow = 1:5
                            ,col = c("col1","col2","col3","col4","col5"))

for (i in 1:max(cal_to_convert$row))
  {
    colname <- col_to_convert$col[i]
    colnum <- which(colnames(df) == colname)
        for (j in 1:nrow(df))
          {
           df[j,colnum] <- as.numericdf(df[j,colnum])
          }
  }

This is not ideal for large tables as it goes cell by cell, but it would get the job done.

How to use comparison and ' if not' in python?

There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that:

if not ((u0 <= u) and (u < u0+step)):

Adding blur effect to background in swift

U can also use CoreImage to create blurred image with dark effect

  1. Make snapshot for image

    func snapShotImage() -> UIImage {
        UIGraphicsBeginImageContext(self.frame.size)
        if let context = UIGraphicsGetCurrentContext() {
            self.layer.renderInContext(context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    
        return UIImage()
    }
    
  2. Apply CoreImage Filters as u wish with

    private func bluredImage(view:UIView, radius:CGFloat = 1) -> UIImage {
    let image = view.snapShotImage()
    
    if let source = image.CGImage {
        let context = CIContext(options: nil)
        let inputImage = CIImage(CGImage: source)
    
        let clampFilter = CIFilter(name: "CIAffineClamp")
        clampFilter?.setDefaults()
        clampFilter?.setValue(inputImage, forKey: kCIInputImageKey)
    
        if let clampedImage = clampFilter?.valueForKey(kCIOutputImageKey) as? CIImage {
            let explosureFilter = CIFilter(name: "CIExposureAdjust")
            explosureFilter?.setValue(clampedImage, forKey: kCIInputImageKey)
            explosureFilter?.setValue(-1.0, forKey: kCIInputEVKey)
    
            if let explosureImage = explosureFilter?.valueForKey(kCIOutputImageKey) as? CIImage {
                let filter = CIFilter(name: "CIGaussianBlur")
                filter?.setValue(explosureImage, forKey: kCIInputImageKey)
                filter?.setValue("\(radius)", forKey:kCIInputRadiusKey)
    
                if let result = filter?.valueForKey(kCIOutputImageKey) as? CIImage {
                    let bounds = UIScreen.mainScreen().bounds
                    let cgImage = context.createCGImage(result, fromRect: bounds)
                    let returnImage = UIImage(CGImage: cgImage)
                    return returnImage
                }
            }
        }
    }
    return UIImage()
    }
    

Calling a class function inside of __init__

How about:

class MyClass(object):
    def __init__(self, filename):
        self.filename = filename 
        self.stats = parse_file(filename)

def parse_file(filename):
    #do some parsing
    return results_from_parse

By the way, if you have variables named stat1, stat2, etc., the situation is begging for a tuple: stats = (...).

So let parse_file return a tuple, and store the tuple in self.stats.

Then, for example, you can access what used to be called stat3 with self.stats[2].

Error Dropping Database (Can't rmdir '.test\', errno: 17)

In my case I didn't see any tables under my database on phpMyAdmin I am using Wamp server but when I checked the directory under C:\wamp\bin\mysql\mysql5.6.12\data I found this employed.ibd when I deleted this file manually I was able to drop the database from phpMyAdmin smoothly without any problems.

PHP equivalent of .NET/Java's toString()

For primitives just use (string)$var or print this variable straight away. PHP is dynamically typed language and variable will be casted to string on the fly.

If you want to convert objects to strings you will need to define __toString() method that returns string. This method is forbidden to throw exceptions.

Leaflet - How to find existing markers, and delete markers?

What I did to remove marker was this create a button who allow me do it

Hope i can help someone :)

_x000D_
_x000D_
//Button who active deleteBool
const button = document.getElementById('btn')

//Boolean who let me delete marker
let deleteBool = false

//Button function to enable boolean
button.addEventListener('click',()=>{
  deleteBool = true
})

// Function to delete marker 
const deleteMarker = (e) => {
    if (deleteBool) {
        e.target.removeFrom(map)
        deleteBooly = false
    }
}

//Initiate map
var map = L.map('map').setView([51.505, -0.09], 13);

//Create one marker
let marker = L.marker([51.5, -0.09]).addTo(map)
//Add Marker Function
marker.on('click', deleteMarker)
_x000D_
body {
  display: flex;
  flex-direction: column;
}

#map{
  width: 500px;
  height: 500px;
  margin: auto;
}

#btn{
  width: 50px;
  height: 50px;
  margin: 2em auto; 
}
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
    <title>MovieCenter</title>
</head>

<body>
    <div id="map"></div>
    <button id="btn">Click me!</button>
    <script script="script" src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
    <script src="script.js"></script>
</body>

</html>
_x000D_
_x000D_
_x000D_

MongoDB logging all queries

MongoDB has a sophisticated feature of profiling. The logging happens in system.profile collection. The logs can be seen from:

db.system.profile.find()

There are 3 logging levels (source):

  • Level 0 - the profiler is off, does not collect any data. mongod always writes operations longer than the slowOpThresholdMs threshold to its log. This is the default profiler level.
  • Level 1 - collects profiling data for slow operations only. By default slow operations are those slower than 100 milliseconds. You can modify the threshold for “slow” operations with the slowOpThresholdMs runtime option or the setParameter command. See the Specify the Threshold for Slow Operations section for more information.
  • Level 2 - collects profiling data for all database operations.

To see what profiling level the database is running in, use

db.getProfilingLevel()

and to see the status

db.getProfilingStatus()

To change the profiling status, use the command

db.setProfilingLevel(level, milliseconds)

Where level refers to the profiling level and milliseconds is the ms of which duration the queries needs to be logged. To turn off the logging, use

db.setProfilingLevel(0)

The query to look in the system profile collection for all queries that took longer than one second, ordered by timestamp descending will be

db.system.profile.find( { millis : { $gt:1000 } } ).sort( { ts : -1 } )

ANTLR: Is there a simple example?

ANTLR mega tutorial by Gabriele Tomassetti is very helpful

It has grammar examples, examples of visitors in different languages (Java, JavaScript, C# and Python) and many other things. Highly recommended.

EDIT: other useful articles by Gabriele Tomassetti on ANTLR

sqlplus statement from command line

I'm able to execute your exact query by just making sure there is a semicolon at the end of my select statement. (Output is actual, connection params removed.)

echo "select 1 from dual;" | sqlplus -s username/password@host:1521/service 

Output:

         1
----------
         1

Note that is should matter but this is running on Mac OS X Snow Leopard and Oracle 11g.

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I had the same problem. After spending hours, I came across the solution that I already added dependency for "spring-webmvc" but missed for "spring-web". So just add the below dependency to resolve this issue. If you already have, just update both to the latest version. It will work for sure.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.6.RELEASE</version>
</dependency>

You could update the version to "5.1.2" or latest. I used V4.1.6 therefore the build was failing, because this is an old version (one might face compatibility issues).

Identify duplicate values in a list in Python

You can use list compression and set to reduce the complexity.

my_list = [3, 5, 2, 1, 4, 4, 1]
opt = [item for item in set(my_list) if my_list.count(item) > 1]

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

You can compute pairwise cosine similarity on the rows of a sparse matrix directly using sklearn. As of version 0.17 it also supports sparse output:

from sklearn.metrics.pairwise import cosine_similarity
from scipy import sparse

A =  np.array([[0, 1, 0, 0, 1], [0, 0, 1, 1, 1],[1, 1, 0, 1, 0]])
A_sparse = sparse.csr_matrix(A)

similarities = cosine_similarity(A_sparse)
print('pairwise dense output:\n {}\n'.format(similarities))

#also can output sparse matrices
similarities_sparse = cosine_similarity(A_sparse,dense_output=False)
print('pairwise sparse output:\n {}\n'.format(similarities_sparse))

Results:

pairwise dense output:
[[ 1.          0.40824829  0.40824829]
[ 0.40824829  1.          0.33333333]
[ 0.40824829  0.33333333  1.        ]]

pairwise sparse output:
(0, 1)  0.408248290464
(0, 2)  0.408248290464
(0, 0)  1.0
(1, 0)  0.408248290464
(1, 2)  0.333333333333
(1, 1)  1.0
(2, 1)  0.333333333333
(2, 0)  0.408248290464
(2, 2)  1.0

If you want column-wise cosine similarities simply transpose your input matrix beforehand:

A_sparse.transpose()

(WAMP/XAMP) send Mail using SMTP localhost

Here's the steps to achieve this:

  • Download the sendmail.zip through this link

    • Now, extract the folder and put it to C:/wamp/. Make sure that these four files are present: sendmail.exe, libeay32.dll, ssleay32.ddl and sendmail.ini.
    • Open sendmail.ini and set the configuration as follows:

    • smtp_server=smtp.gmail.com

    • smtp_port=465
    • smtp_ssl=ssl
    • default_domain=localhost
    • error_logfile=error.log
    • debug_logfile=debug.log
    • auth_username=[your_gmail_account_username]@gmail.com
    • auth_password=[your_gmail_account_password]
    • pop3_server=
    • pop3_username=
    • pop3_password=
    • force_sender=
    • force_recipient=
    • hostname=localhost

    • Access your email account. Click the Gear Tool > Settings > Forwarding and POP/IMAP > IMAP access. Click "Enable IMAP", then save your changes.

    • Run your WAMP Server. Enable ssl_module under Apache Module.

    • Next, enable php_openssl and php_sockets under PHP.

    • Open php.ini and configure it as the codes below. Basically, you just have to set the sendmail_path.

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP =
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]
; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t -i"
  • Restart Wamp Server

I hope this will work for you..

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

the error can be due to one of several missing package. Below command will install several packages like g++, gcc, etc.

sudo apt-get install build-essential

RuntimeError on windows trying python multiprocessing

Though the earlier answers are correct, there's a small complication it would help to remark on.

In case your main module imports another module in which global variables or class member variables are defined and initialized to (or using) some new objects, you may have to condition that import in the same way:

if __name__ ==  '__main__':
  import my_module

How to debug Ruby scripts

As of Ruby 2.4.0, it is easier to start an IRB REPL session in the middle of any Ruby program. Put these lines at the point in the program that you want to debug:

require 'irb'
binding.irb

You can run Ruby code and print out local variables. Type Ctrl+D or quit to end the REPL and let Ruby program keep running.

You can also use puts and p to print out values from your program as it is running.

Sleeping in a batch file

Or command line Python, for example, for 6 and a half seconds:

python -c "import time;time.sleep(6.5)"

Update only specific fields in a models.Model

To update a subset of fields, you can use update_fields:

survey.save(update_fields=["active"]) 

The update_fields argument was added in Django 1.5. In earlier versions, you could use the update() method instead:

Survey.objects.filter(pk=survey.pk).update(active=True)

How to remove empty lines with or without whitespace in Python

lines = bigstring.split('\n')
lines = [line for line in lines if line.strip()]

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Show percent % instead of counts in charts of categorical variables

Since version 3.3 of ggplot2, we have access to the convenient after_stat() function.

We can do something similar to @Andrew's answer, but without using the .. syntax:

# original example data
mydata <- c("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc")

# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
                     y = after_stat(count/sum(count)))) +
  geom_bar() +
  scale_y_continuous(labels = scales::percent)

You can find all the "computed variables" available to use in the documentation of the geom_ and stat_ functions. For example, for geom_bar(), you can access the count and prop variables. (See the documentation for computed variables.)

One comment about your NULL values: they are ignored when you create the vector (i.e. you end up with a vector of length 9, not 11). If you really want to keep track of missing data, you will have to use NA instead (ggplot2 will put NAs at the right end of the plot):

# use NA instead of NULL
mydata <- c("aa", "bb", NA, "bb", "cc", "aa", "aa", "aa", "ee", NA, "cc")
length(mydata)
#> [1] 11

# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
                     y = after_stat(count/sum(count)))) +
  geom_bar() +
  scale_y_continuous(labels = scales::percent)

Created on 2021-02-09 by the reprex package (v1.0.0)

(Note that using chr or fct data will not make a difference for your example.)

Is it possible to get the current spark context settings in PySpark?

For a complete overview of your Spark environment and configuration I found the following code snippets useful:

SparkContext:

for item in sorted(sc._conf.getAll()): print(item)

Hadoop Configuration:

hadoopConf = {}
iterator = sc._jsc.hadoopConfiguration().iterator()
while iterator.hasNext():
    prop = iterator.next()
    hadoopConf[prop.getKey()] = prop.getValue()
for item in sorted(hadoopConf.items()): print(item)

Environment variables:

import os
for item in sorted(os.environ.items()): print(item)

How can I capture the result of var_dump to a string?

I really like var_dump()'s verbose output and wasn't satisfied with var_export()'s or print_r()'s output because it didn't give as much information (e.g. data type missing, length missing).

To write secure and predictable code, sometimes it's useful to differentiate between an empty string and a null. Or between a 1 and a true. Or between a null and a false. So I want my data type in the output.

Although helpful, I didn't find a clean and simple solution in the existing responses to convert the colored output of var_dump() to a human-readable output into a string without the html tags and including all the details from var_dump().

Note that if you have a colored var_dump(), it means that you have Xdebug installed which overrides php's default var_dump() to add html colors.

For that reason, I created this slight variation giving exactly what I need:

function dbg_var_dump($var)
    {
        ob_start();
        var_dump($var);
        $result = ob_get_clean();
        return strip_tags(strtr($result, ['=&gt;' => '=>']));
    }

Returns the below nice string:

array (size=6)
  'functioncall' => string 'add-time-property' (length=17)
  'listingid' => string '57' (length=2)
  'weekday' => string '0' (length=1)
  'starttime' => string '00:00' (length=5)
  'endtime' => string '00:00' (length=5)
  'price' => string '' (length=0)

Hope it helps someone.

how to concatenate two dictionaries to create a new one in Python?

Use the dict constructor

d1={1:2,3:4}
d2={5:6,7:9}
d3={10:8,13:22}

d4 = reduce(lambda x,y: dict(x, **y), (d1, d2, d3))

As a function

from functools import partial
dict_merge = partial(reduce, lambda a,b: dict(a, **b))

The overhead of creating intermediate dictionaries can be eliminated by using thedict.update() method:

from functools import reduce
def update(d, other): d.update(other); return d
d4 = reduce(update, (d1, d2, d3), {})

lexical or preprocessor issue file not found occurs while archiving?

Spaces in a folder name in your header search path can cause this problem. Make sure the folders in your project do not have spaces in their names.

flow 2 columns of text automatically with CSS

Not an expert here, but this is what I did and it worked

<html>
<style>
/*Style your div container, must specify height*/
.content {width:1000px; height:210px; margin:20px auto; font-size:16px;}
/*Style the p tag inside your div container with half the with of your container, and float left*/
.content p {width:490px; margin-right:10px; float:left;}
</style>

<body>
<!--Put your text inside a div with a class-->
<div class="content">
            <h1>Title</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus gravida laoreet lectus. Pellentesque ultrices consequat placerat. Etiam luctus euismod tempus. In sed eros dignissim tortor faucibus dapibus ut non neque. Ut ante odio, luctus eu pharetra vitae, consequat sit amet nunc. Aenean dolor felis, fringilla sagittis hendrerit vel, egestas eget eros. Mauris suscipit bibendum massa, nec mattis lorem dignissim sit amet. </p>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer eget dolor neque. Phasellus tellus odio, egestas ut blandit sed, egestas sit amet velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;</p>
</div>     
</body>
</html>

Once the text inside the <p> tags has reached the height of the container div, the other text will flow to the right of the container.

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

Is there a method for String conversion to Title Case?

You can use apache commons langs like this :

WordUtils.capitalizeFully("this is a text to be capitalize")

you can find the java doc here : WordUtils.capitalizeFully java doc

and if you want to remove the spaces in between the worlds you can use :

StringUtils.remove(WordUtils.capitalizeFully("this is a text to be capitalize")," ")

you can find the java doc for String StringUtils.remove java doc

i hope this help.

How to uninstall Ruby from /usr/local?

It's not a good idea to uninstall 1.8.6 if it's in /usr/bin. That is owned by the OS and is expected to be there.

If you put /usr/local/bin in your PATH before /usr/bin then things you have installed in /usr/local/bin will be found before any with the same name in /usr/bin, effectively overwriting or updating them, without actually doing so. You can still reach them by explicitly using /usr/bin in your #! interpreter invocation line at the top of your code.

@Anurag recommended using RVM, which I'll second. I use it to manage 1.8.7 and 1.9.1 in addition to the OS's 1.8.6.

How to update core-js to core-js@3 dependency?

For npm

 npm install --save core-js@^3

for yarn

yarn add core-js@^3

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

I tried a few things in this scenario.

I removed ios and installed many times. Went down the path of deleting Splash screens to no avail! Bitcode on/off so many times.

However, after selecting a iOS provisioning team, and running pod update inside ./platforms/ios, I am pleased to announce this resolved my problems.

Hopefully you can try the same and get some resolution?

How to create a windows service from java app

I didn't like the licensing for the Java Service Wrapper. I went with ActiveState Perl to write a service that does the work.

I thought about writing a service in C#, but my time constraints were too tight.

ReactJS lifecycle method inside a function Component

Edit: With the introduction of Hooks it is possible to implement a lifecycle kind of behavior as well as the state in the functional Components. Currently

Hooks are a new feature proposal that lets you use state and other React features without writing a class. They are released in React as a part of v16.8.0

useEffect hook can be used to replicate lifecycle behavior, and useState can be used to store state in a function component.

Basic syntax:

useEffect(callbackFunction, [dependentProps]) => cleanupFunction

You can implement your use case in hooks like

const grid = (props) => {
    console.log(props);
    let {skuRules} = props;

    useEffect(() => {
        if(!props.fetched) {
            props.fetchRules();
        }
        console.log('mount it!');
    }, []); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour

    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
}

useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners, replicating the behavior of componentWillUnmount:

Eg: componentWillUnmount

useEffect(() => {
    window.addEventListener('unhandledRejection', handler);
    return () => {
       window.removeEventListener('unhandledRejection', handler);
    }
}, [])

To make useEffect conditional on specific events, you may provide it with an array of values to check for changes:

Eg: componentDidUpdate

componentDidUpdate(prevProps, prevState) {
     const { counter } = this.props;
     if (this.props.counter !== prevState.counter) {
      // some action here
     }
}

Hooks Equivalent

useEffect(() => {
     // action here
}, [props.counter]); // checks for changes in the values in this array

If you include this array, make sure to include all values from the component scope that change over time (props, state), or you may end up referencing values from previous renders.

There are some subtleties to using useEffect; check out the API Here.


Before v16.7.0

The property of function components is that they don't have access to Reacts lifecycle functions or the this keyword. You need to extend the React.Component class if you want to use the lifecycle function.

class Grid extends React.Component  {
    constructor(props) {
       super(props)
    }

    componentDidMount () {
        if(!this.props.fetched) {
            this.props.fetchRules();
        }
        console.log('mount it!');
    }
    render() {
    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
  }
}

Function components are useful when you only want to render your Component without the need of extra logic.

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.

For those still facing this problem, I was able to resolve it as follows:

$ git commit --allow-empty -n -m "Initial commit".

dereferencing pointer to incomplete type

Another possible reason is indirect reference. If a code references to a struct that not included in current c file, the compiler will complain.

a->b->c //error if b not included in current c file

When to use margin vs padding in CSS

Advanced Margin versus Padding Explained

It is inappropriate to use padding to space content in an element; you must utilize margin on the child element instead. Older browsers such as Internet Explorer misinterpreted the box model except when it came to using margin which works perfectly in Internet Explorer 4.

There are two exceptions when using padding is appropriate to use:

  1. It is applied to an inline element which can not contain any child elements such as an input element.

  2. You are compensating for a highly miscellaneous browser bug which a vendor *cough* Mozilla *cough* refuses to fix and are certain (to the degree that you hold regular exchanges with W3C and WHATWG editors) that you must have a working solution and this solution will not effect the styling of anything other then the bug you are compensating for.

When you have a 100% width element with padding: 50px; you effectively get width: calc(100% + 100px);. Since margin is not added to the width it will not cause unexpected layout problems when you use margin on child elements instead of padding directly on the element.

So if you're not doing one of those two things do not add padding to the element but to it's direct child/children element(s) to ensure you're going to get the expected behavior in all browsers.

How to get length of a string using strlen function

Function strlen shows the number of character before \0 and using it for std::string may report wrong length.

strlen(str.c_str()); // It may return wrong length.

In C++, a string can contain \0 within the characters but C-style-zero-terminated strings can not but at the end. If the std::string has a \0 before the last character then strlen reports a length less than the actual length.

Try to use .length() or .size(), I prefer second one since another standard containers have it.

str.size()

Improve INSERT-per-second performance of SQLite

I coudn't get any gain from transactions until I raised cache_size to a higher value i.e. PRAGMA cache_size=10000;

What's causing my java.net.SocketException: Connection reset?

I was getting this error because the port I tried to connect to was closed.

How to find length of a string array?

I think you are looking for this

String[] car = new String[10];
int size = car.length;

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

Loop Through All Subfolders Using VBA

And to complement Rich's recursive answer, a non-recursive method.

Public Sub NonRecursiveMethod()
    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("your folder path variable") 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
            '...insert any file processing code here...
        Next oFile
    Loop

End Sub

You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1) with Set oFolder = queue(queue.Count) and replace queue.Remove(1) with queue.Remove(queue.Count), and probably rename the variable...)

ipynb import another ipynb file

Run

!pip install ipynb

and then import the other notebook as

from ipynb.fs.full.<notebook_name> import *

or

from ipynb.fs.full.<notebook_name> import <function_name>

Make sure that all the notebooks are in the same directory.

Edit 1: You can see the official documentation here - https://ipynb.readthedocs.io/en/stable/

Also, if you would like to import only class & function definitions from a notebook (and not the top level statements), you can use ipynb.fs.defs instead of ipynb.fs.full. Full uppercase variable assignment will get evaluated as well.

How to call a Python function from Node.js

I'm on node 10 and child process 1.0.2. The data from python is a byte array and has to be converted. Just another quick example of making a http request in python.

node

const process = spawn("python", ["services/request.py", "https://www.google.com"])

return new Promise((resolve, reject) =>{
    process.stdout.on("data", data =>{
        resolve(data.toString()); // <------------ by default converts to utf-8
    })
    process.stderr.on("data", reject)
})

request.py

import urllib.request
import sys

def karl_morrison_is_a_pedant():   
    response = urllib.request.urlopen(sys.argv[1])
    html = response.read()
    print(html)
    sys.stdout.flush()

karl_morrison_is_a_pedant()

p.s. not a contrived example since node's http module doesn't load a few requests I need to make

Why does GitHub recommend HTTPS over SSH?

Either you are quoting wrong or github has different recommendation on different pages or they may learned with time and updated their reco.

We strongly recommend using an SSH connection when interacting with GitHub. SSH keys are a way to identify trusted computers, without involving passwords. The steps below will walk you through generating an SSH key and then adding the public key to your GitHub account.

https://help.github.com/articles/generating-ssh-keys

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

I had a similar problem and update the input[type="number"] example on angular docs for works with decimals precision and I'm using this approach to solve it.

PS: A quick reminder is that the browsers supports the characters 'e' and 'E' in the input[type="number"], because that the keypress event is required.

angular.module('numfmt-error-module', [])
.directive('numbersOnly', function() {
  return {
    require: 'ngModel',
    scope: {
      precision: '@'
    },
    link: function(scope, element, attrs, modelCtrl) {
      var currencyDigitPrecision = scope.precision;

      var currencyDigitLengthIsInvalid = function(inputValue) {
        return countDecimalLength(inputValue) > currencyDigitPrecision;
      };

      var parseNumber = function(inputValue) {
        if (!inputValue) return null;
        inputValue.toString().match(/-?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?/g).join('');
        var precisionNumber = Math.round(inputValue.toString() * 100) % 100;

        if (!!currencyDigitPrecision && currencyDigitLengthIsInvalid(inputValue)) {
          inputValue = inputValue.toFixed(currencyDigitPrecision);
          modelCtrl.$viewValue = inputValue;
        }
        return inputValue;
      };

      var countDecimalLength = function (number) { 
         var str = '' + number;
         var index = str.indexOf('.');
         if (index >= 0) {
           return str.length - index - 1;
         } else {
           return 0;
         }
      };

      element.on('keypress', function(evt) {
        var charCode, isACommaEventKeycode, isADotEventKeycode, isANumberEventKeycode;
        charCode = String.fromCharCode(evt.which || event.keyCode);
        isANumberEventKeycode = '0123456789'.indexOf(charCode) !== -1;
        isACommaEventKeycode = charCode === ',';
        isADotEventKeycode = charCode === '.';

        var forceRenderComponent = false;

        if (modelCtrl.$viewValue != null && !!currencyDigitPrecision) {
          forceRenderComponent = currencyDigitLengthIsInvalid(modelCtrl.$viewValue);
        }

        var isAnAcceptedCase = isANumberEventKeycode || isACommaEventKeycode || isADotEventKeycode;

        if (!isAnAcceptedCase) {
          evt.preventDefault();
        }

        if (forceRenderComponent) {
          modelCtrl.$render(modelCtrl.$viewValue);
        }

        return isAnAcceptedCase;
      });

      modelCtrl.$render = function(inputValue) {
        return element.val(parseNumber(inputValue));
      };

      modelCtrl.$parsers.push(function(inputValue) {

        if (!inputValue) {
          return inputValue;
        }

        var transformedInput;
        modelCtrl.$setValidity('number', true);
        transformedInput = parseNumber(inputValue);

        if (transformedInput !== inputValue) {

          modelCtrl.$viewValue = transformedInput;
          modelCtrl.$commitViewValue();
          modelCtrl.$render(transformedInput);
        }
        return transformedInput;
      });
    }
  };
});

And in your html you can use this approach

<input 
  type="number" 
  numbers-only 
  precision="2" 
  ng-model="model.value" 
  step="0.10" />

Here is the plunker with this snippet

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

d = dict([(x,0) for x in a])

**edit Tim's solution is better because it uses generators see the comment to his answer.

How to import an existing directory into Eclipse?

I Using below simple way to create a project 1- First in a directory that desire to make it project, create a .project file with below contents:

<projectDescription>
    <name>Project-Name</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
    </buildSpec>
    <natures>
    </natures>
</projectDescription>

2- Now instead of "Project-Name", write your project name, maybe current directory name

3- Now save this file to directory that desire to make that directory as project with name ".project" ( for save like this, use Notepad )

4- Now go to Eclips and open project and add your files to it.

How to generate components in a specific folder with Angular CLI?

I wasn't having any luck with the above answers (including --flat), but what worked for me was:

cd path/to/specific/directory

From there, I ran the ng g c mynewcomponent

Map with Key as String and Value as List in Groovy

Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below:

// Java syntax 

Map<String,List> map1  = new HashMap<>();
List list1 = new ArrayList();
list1.add("hello");
map1.put("abc", list1); 
assert map1.get("abc") == list1;

// slightly less Java-esque

def map2  = new HashMap<String,List>()
def list2 = new ArrayList()
list2.add("hello")
map2.put("abc", list2)
assert map2.get("abc") == list2

// typical Groovy

def map3  = [:]
def list3 = []
list3 << "hello"
map3.'abc'= list3
assert map3.'abc' == list3

Single vs double quotes in JSON

you can use ast.literal_eval()

>>> import ast
>>> s = "{'username':'dfdsfdsf'}"
>>> ast.literal_eval(s)
{'username': 'dfdsfdsf'}

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Documenting in detail for future readers:

The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url) method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request) method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.

The below is the skeleton on how you would accomplish this:

class CustomWebViewClient extends WebViewClient {

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        final Uri uri = Uri.parse(url);
        return handleUri(uri);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        final Uri uri = request.getUrl();
        return handleUri(uri);
    }

    private boolean handleUri(final Uri uri) {
        Log.i(TAG, "Uri =" + uri);
        final String host = uri.getHost();
        final String scheme = uri.getScheme();
        // Based on some condition you need to determine if you are going to load the url 
        // in your web view itself or in a browser. 
        // You can use `host` or `scheme` or any part of the `uri` to decide.
        if (/* any condition */) {
            // Returning false means that you are going to load this url in the webView itself
            return false;
        } else {
            // Returning true means that you need to handle what to do with the url
            // e.g. open web page in a Browser
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        }
    }
}

Just like shouldOverrideUrlLoading, you can come up with a similar approach for shouldInterceptRequest method.

How do you make sure email you send programmatically is not automatically marked as spam?

Sign up for an account on as many major email providers as possible (gmail/yahoo/hotmail/aol/etc). If you make changes to your emails, either major rewording, changes to the code that sends the emails, changes to your email servers, etc, make sure to send test messages to all your accounts and verify that they are not being marked as spam.

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

Class file has wrong version 52.0, should be 50.0

In your IntelliJ idea find tools.jar replace it with tools.jar from yout JDK8