Programs & Examples On #Waveout

Play audio from a stream using C#

I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.

I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.

Python: finding lowest integer

l = [-1.2, 0.0, 1]

x = 100.0
for i in l:
    if i < x:
        x = i
print (x)

This is the answer, i needed this for my homework, took your code, and i deleted the " " around the numbers, it then worked, i hope this helped

How to convert a string to character array in c (or) how to extract a single char form string?

In C, a string is actually stored as an array of characters, so the 'string pointer' is pointing to the first character. For instance,

char myString[] = "This is some text";

You can access any character as a simple char by using myString as an array, thus:

char myChar = myString[6];
printf("%c\n", myChar); // Prints s

Hope this helps! David

How does the SQL injection from the "Bobby Tables" XKCD comic work?

It drops the students table.

The original code in the school's program probably looks something like

q = "INSERT INTO Students VALUES ('" + FNMName.Text + "', '" + LName.Text + "')";

This is the naive way to add text input into a query, and is very bad, as you will see.

After the values from the first name, middle name textbox FNMName.Text (which is Robert'); DROP TABLE STUDENTS; --) and the last name textbox LName.Text (let's call it Derper) are concatenated with the rest of the query, the result is now actually two queries separated by the statement terminator (semicolon). The second query has been injected into the first. When the code executes this query against the database, it will look like this

INSERT INTO Students VALUES ('Robert'); DROP TABLE Students; --', 'Derper')

which, in plain English, roughly translates to the two queries:

Add a new record to the Students table with a Name value of 'Robert'

and

Delete the Students table

Everything past the second query is marked as a comment: --', 'Derper')

The ' in the student's name is not a comment, it's the closing string delimiter. Since the student's name is a string, it's needed syntactically to complete the hypothetical query. Injection attacks only work when the SQL query they inject results in valid SQL.

Edited again as per dan04's astute comment

How to split a String by space

Simple to Spit String by Space

    String CurrentString = "First Second Last";
    String[] separated = CurrentString.split(" ");

    for (int i = 0; i < separated.length; i++) {

         if (i == 0) {
             Log.d("FName ** ", "" + separated[0].trim() + "\n ");
         } else if (i == 1) {
             Log.d("MName ** ", "" + separated[1].trim() + "\n ");
         } else if (i == 2) {
             Log.d("LName ** ", "" + separated[2].trim());
         }
     }

How do I wait for a promise to finish before returning the variable of a function?

Instead of returning a resultsArray you return a promise for a results array and then then that on the call site - this has the added benefit of the caller knowing the function is performing asynchronous I/O. Coding concurrency in JavaScript is based on that - you might want to read this question to get a broader idea:

function resultsByName(name)
{   
    var Card = Parse.Object.extend("Card");
    var query = new Parse.Query(Card);
    query.equalTo("name", name.toString());

    var resultsArray = [];

    return query.find({});                           

}

// later
resultsByName("Some Name").then(function(results){
    // access results here by chaining to the returned promise
});

You can see more examples of using parse promises with queries in Parse's own blog post about it.

How can I create download link in HTML?

This thread is probably ancient by now, but this works in html5 for my local file.

For pdfs:

<p><a href="file:///........example.pdf" download target="_blank">test pdf</a></p>

This should open the pdf in a new windows and allow you to download it (in firefox at least). For any other file, just make it the filename. For images and music, you'd want to store them in the same directory as your site though. So it'd be like

<p><a href="images/logo2.png" download>test pdf</a></p>

Accessing Session Using ASP.NET Web API

Last one is not working now, take this one, it worked for me.

in WebApiConfig.cs at App_Start

    public static string _WebApiExecutionPath = "api";

    public static void Register(HttpConfiguration config)
    {
        var basicRouteTemplate = string.Format("{0}/{1}", _WebApiExecutionPath, "{controller}");

        // Controller Only
        // To handle routes like `/api/VTRouting`
        config.Routes.MapHttpRoute(
            name: "ControllerOnly",
            routeTemplate: basicRouteTemplate//"{0}/{controller}"
        );

        // Controller with ID
        // To handle routes like `/api/VTRouting/1`
        config.Routes.MapHttpRoute(
            name: "ControllerAndId",
            routeTemplate: string.Format ("{0}/{1}", basicRouteTemplate, "{id}"),
            defaults: null,
            constraints: new { id = @"^\d+$" } // Only integers 
        );

Global.asax

protected void Application_PostAuthorizeRequest()
{
  if (IsWebApiRequest())
  {
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
  }
}

private static bool IsWebApiRequest()
{
  return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(_WebApiExecutionPath);
}

fournd here: http://forums.asp.net/t/1773026.aspx/1

Full-screen iframe with a height of 100%

3 approaches for creating a fullscreen iframe:


  • Approach 1 - Viewport-percentage lengths

    In supported browsers, you can use viewport-percentage lengths such as height: 100vh.

    Where 100vh represents the height of the viewport, and likewise 100vw represents the width.

    Example Here

    _x000D_
    _x000D_
    body {_x000D_
        margin: 0;            /* Reset default margin */_x000D_
    }_x000D_
    iframe {_x000D_
        display: block;       /* iframes are inline by default */_x000D_
        background: #000;_x000D_
        border: none;         /* Reset default border */_x000D_
        height: 100vh;        /* Viewport-relative units */_x000D_
        width: 100vw;_x000D_
    }
    _x000D_
    <iframe></iframe>
    _x000D_
    _x000D_
    _x000D_


  • Approach 2 - Fixed positioning

    This approach is fairly straight-forward. Just set the positioning of the fixed element and add a height/width of 100%.

    Example Here

    _x000D_
    _x000D_
    iframe {_x000D_
        position: fixed;_x000D_
        background: #000;_x000D_
        border: none;_x000D_
        top: 0; right: 0;_x000D_
        bottom: 0; left: 0;_x000D_
        width: 100%;_x000D_
        height: 100%;_x000D_
    }
    _x000D_
    <iframe></iframe>
    _x000D_
    _x000D_
    _x000D_


  • Approach 3

    For this last method, just set the height of the body/html/iframe elements to 100%.

    Example Here

    _x000D_
    _x000D_
    html, body {_x000D_
        height: 100%;_x000D_
        margin: 0;         /* Reset default margin on the body element */_x000D_
    }_x000D_
    iframe {_x000D_
        display: block;       /* iframes are inline by default */_x000D_
        background: #000;_x000D_
        border: none;         /* Reset default border */_x000D_
        width: 100%;_x000D_
        height: 100%;_x000D_
    }
    _x000D_
    <iframe></iframe>
    _x000D_
    _x000D_
    _x000D_

How to escape indicator characters (i.e. : or - ) in YAML

Another way that works with the YAML parser used in Jekyll:

title: My Life&#58; A Memoir

Colons not followed by spaces don't seem to bother Jekyll's YAML parser, on the other hand. Neither do dashes.

Python if not == vs if !=

In the first one Python has to execute one more operations than necessary(instead of just checking not equal to it has to check if it is not true that it is equal, thus one more operation). It would be impossible to tell the difference from one execution, but if run many times, the second would be more efficient. Overall I would use the second one, but mathematically they are the same

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

How to convert URL parameters to a JavaScript object?

Edit

This edit improves and explains the answer based on the comments.

var search = location.search.substring(1);
JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')

Example

Parse abc=foo&def=%5Basf%5D&xyz=5 in five steps:

  • decodeURI: abc=foo&def=[asf]&xyz=5
  • Escape quotes: same, as there are no quotes
  • Replace &: abc=foo","def=[asf]","xyz=5
  • Replace =: abc":"foo","def":"[asf]","xyz":"5
  • Suround with curlies and quotes: {"abc":"foo","def":"[asf]","xyz":"5"}

which is legal JSON.

An improved solution allows for more characters in the search string. It uses a reviver function for URI decoding:

var search = location.search.substring(1);
JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })

Example

search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";

gives

Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}

Original answer

A one-liner:

JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')

Test a string for a substring

There are several other ways, besides using the in operator (easiest):

index()

>>> try:
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found

find()

>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found

re

>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found

Can I access variables from another file?

As Fermin said, a variable in the global scope should be accessible to all scripts loaded after it is declared. You could also use a property of window or (in the global scope) this to get the same effect.

// first.js
var colorCodes = {

  back  : "#fff",
  front : "#888",
  side  : "#369"

};

... in another file ...

// second.js
alert (colorCodes.back); // alerts `#fff`

... in your html file ...

<script type="text/javascript" src="first.js"></script> 
<script type="text/javascript" src="second.js"></script> 

Android Open External Storage directory(sdcard) for storing file

The internal storage is referred to as "external storage" in the API.

As mentioned in the Environment documentation

Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.

To distinguish whether "Environment.getExternalStorageDirectory()" actually returned physically internal or external storage, call Environment.isExternalStorageEmulated(). If it's emulated, than it's internal. On newer devices that have internal storage and sdcard slot Environment.getExternalStorageDirectory() will always return the internal storage. While on older devices that have only sdcard as a media storage option it will always return the sdcard.

There is no way to retrieve all storages using current Android API.

I've created a helper based on Vitaliy Polchuk's method in the answer below

How can I get the list of mounted external storage of android device

NOTE: starting KitKat secondary storage is accessible only as READ-ONLY, you may want to check for writability using the following method

/**
 * Checks whether the StorageVolume is read-only
 * 
 * @param volume
 *            StorageVolume to check
 * @return true, if volume is mounted read-only
 */
public static boolean isReadOnly(@NonNull final StorageVolume volume) {
    if (volume.mFile.equals(Environment.getExternalStorageDirectory())) {
        // is a primary storage, check mounted state by Environment
        return android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED_READ_ONLY);
    } else {
        if (volume.getType() == Type.USB) {
            return volume.isReadOnly();
        }
        //is not a USB storagem so it's read-only if it's mounted read-only or if it's a KitKat device
        return volume.isReadOnly() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    }
}

StorageHelper class

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;

import android.os.Environment;

public final class StorageHelper {

    //private static final String TAG = "StorageHelper";

    private StorageHelper() {
    }

    private static final String STORAGES_ROOT;

    static {
        final String primaryStoragePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        final int index = primaryStoragePath.indexOf(File.separatorChar, 1);
        if (index != -1) {
            STORAGES_ROOT = primaryStoragePath.substring(0, index + 1);
        } else {
            STORAGES_ROOT = File.separator;
        }
    }

    private static final String[] AVOIDED_DEVICES = new String[] {
        "rootfs", "tmpfs", "dvpts", "proc", "sysfs", "none"
    };

    private static final String[] AVOIDED_DIRECTORIES = new String[] {
        "obb", "asec"
    };

    private static final String[] DISALLOWED_FILESYSTEMS = new String[] {
        "tmpfs", "rootfs", "romfs", "devpts", "sysfs", "proc", "cgroup", "debugfs"
    };

    /**
     * Returns a list of mounted {@link StorageVolume}s Returned list always
     * includes a {@link StorageVolume} for
     * {@link Environment#getExternalStorageDirectory()}
     * 
     * @param includeUsb
     *            if true, will include USB storages
     * @return list of mounted {@link StorageVolume}s
     */
    public static List<StorageVolume> getStorages(final boolean includeUsb) {
        final Map<String, List<StorageVolume>> deviceVolumeMap = new HashMap<String, List<StorageVolume>>();

        // this approach considers that all storages are mounted in the same non-root directory
        if (!STORAGES_ROOT.equals(File.separator)) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader("/proc/mounts"));
                String line;
                while ((line = reader.readLine()) != null) {
                    // Log.d(TAG, line);
                    final StringTokenizer tokens = new StringTokenizer(line, " ");

                    final String device = tokens.nextToken();
                    // skipped devices that are not sdcard for sure
                    if (arrayContains(AVOIDED_DEVICES, device)) {
                        continue;
                    }

                    // should be mounted in the same directory to which
                    // the primary external storage was mounted
                    final String path = tokens.nextToken();
                    if (!path.startsWith(STORAGES_ROOT)) {
                        continue;
                    }

                    // skip directories that indicate tha volume is not a storage volume
                    if (pathContainsDir(path, AVOIDED_DIRECTORIES)) {
                        continue;
                    }

                    final String fileSystem = tokens.nextToken();
                    // don't add ones with non-supported filesystems
                    if (arrayContains(DISALLOWED_FILESYSTEMS, fileSystem)) {
                        continue;
                    }

                    final File file = new File(path);
                    // skip volumes that are not accessible
                    if (!file.canRead() || !file.canExecute()) {
                        continue;
                    }

                    List<StorageVolume> volumes = deviceVolumeMap.get(device);
                    if (volumes == null) {
                        volumes = new ArrayList<StorageVolume>(3);
                        deviceVolumeMap.put(device, volumes);
                    }

                    final StorageVolume volume = new StorageVolume(device, file, fileSystem);
                    final StringTokenizer flags = new StringTokenizer(tokens.nextToken(), ",");
                    while (flags.hasMoreTokens()) {
                        final String token = flags.nextToken();
                        if (token.equals("rw")) {
                            volume.mReadOnly = false;
                            break;
                        } else if (token.equals("ro")) {
                            volume.mReadOnly = true;
                            break;
                        }
                    }
                    volumes.add(volume);
                }

            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ex) {
                        // ignored
                    }
                }
            }
        }

        // remove volumes that are the same devices
        boolean primaryStorageIncluded = false;
        final File externalStorage = Environment.getExternalStorageDirectory();
        final List<StorageVolume> volumeList = new ArrayList<StorageVolume>();
        for (final Entry<String, List<StorageVolume>> entry : deviceVolumeMap.entrySet()) {
            final List<StorageVolume> volumes = entry.getValue();
            if (volumes.size() == 1) {
                // go ahead and add
                final StorageVolume v = volumes.get(0);
                final boolean isPrimaryStorage = v.file.equals(externalStorage);
                primaryStorageIncluded |= isPrimaryStorage;
                setTypeAndAdd(volumeList, v, includeUsb, isPrimaryStorage);
                continue;
            }
            final int volumesLength = volumes.size();
            for (int i = 0; i < volumesLength; i++) {
                final StorageVolume v = volumes.get(i);
                if (v.file.equals(externalStorage)) {
                    primaryStorageIncluded = true;
                    // add as external storage and continue
                    setTypeAndAdd(volumeList, v, includeUsb, true);
                    break;
                }
                // if that was the last one and it's not the default external
                // storage then add it as is
                if (i == volumesLength - 1) {
                    setTypeAndAdd(volumeList, v, includeUsb, false);
                }
            }
        }
        // add primary storage if it was not found
        if (!primaryStorageIncluded) {
            final StorageVolume defaultExternalStorage = new StorageVolume("", externalStorage, "UNKNOWN");
            defaultExternalStorage.mEmulated = Environment.isExternalStorageEmulated();
            defaultExternalStorage.mType =
                    defaultExternalStorage.mEmulated ? StorageVolume.Type.INTERNAL
                            : StorageVolume.Type.EXTERNAL;
            defaultExternalStorage.mRemovable = Environment.isExternalStorageRemovable();
            defaultExternalStorage.mReadOnly =
                    Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
            volumeList.add(0, defaultExternalStorage);
        }
        return volumeList;
    }

    /**
     * Sets {@link StorageVolume.Type}, removable and emulated flags and adds to
     * volumeList
     * 
     * @param volumeList
     *            List to add volume to
     * @param v
     *            volume to add to list
     * @param includeUsb
     *            if false, volume with type {@link StorageVolume.Type#USB} will
     *            not be added
     * @param asFirstItem
     *            if true, adds the volume at the beginning of the volumeList
     */
    private static void setTypeAndAdd(final List<StorageVolume> volumeList,
            final StorageVolume v,
            final boolean includeUsb,
            final boolean asFirstItem) {
        final StorageVolume.Type type = resolveType(v);
        if (includeUsb || type != StorageVolume.Type.USB) {
            v.mType = type;
            if (v.file.equals(Environment.getExternalStorageDirectory())) {
                v.mRemovable = Environment.isExternalStorageRemovable();
            } else {
                v.mRemovable = type != StorageVolume.Type.INTERNAL;
            }
            v.mEmulated = type == StorageVolume.Type.INTERNAL;
            if (asFirstItem) {
                volumeList.add(0, v);
            } else {
                volumeList.add(v);
            }
        }
    }

    /**
     * Resolved {@link StorageVolume} type
     * 
     * @param v
     *            {@link StorageVolume} to resolve type for
     * @return {@link StorageVolume} type
     */
    private static StorageVolume.Type resolveType(final StorageVolume v) {
        if (v.file.equals(Environment.getExternalStorageDirectory())
                && Environment.isExternalStorageEmulated()) {
            return StorageVolume.Type.INTERNAL;
        } else if (containsIgnoreCase(v.file.getAbsolutePath(), "usb")) {
            return StorageVolume.Type.USB;
        } else {
            return StorageVolume.Type.EXTERNAL;
        }
    }

    /**
     * Checks whether the array contains object
     * 
     * @param array
     *            Array to check
     * @param object
     *            Object to find
     * @return true, if the given array contains the object
     */
    private static <T> boolean arrayContains(T[] array, T object) {
        for (final T item : array) {
            if (item.equals(object)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks whether the path contains one of the directories
     * 
     * For example, if path is /one/two, it returns true input is "one" or
     * "two". Will return false if the input is one of "one/two", "/one" or
     * "/two"
     * 
     * @param path
     *            path to check for a directory
     * @param dirs
     *            directories to find
     * @return true, if the path contains one of the directories
     */
    private static boolean pathContainsDir(final String path, final String[] dirs) {
        final StringTokenizer tokens = new StringTokenizer(path, File.separator);
        while (tokens.hasMoreElements()) {
            final String next = tokens.nextToken();
            for (final String dir : dirs) {
                if (next.equals(dir)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Checks ifString contains a search String irrespective of case, handling.
     * Case-insensitivity is defined as by
     * {@link String#equalsIgnoreCase(String)}.
     * 
     * @param str
     *            the String to check, may be null
     * @param searchStr
     *            the String to find, may be null
     * @return true if the String contains the search String irrespective of
     *         case or false if not or {@code null} string input
     */
    public static boolean containsIgnoreCase(final String str, final String searchStr) {
        if (str == null || searchStr == null) {
            return false;
        }
        final int len = searchStr.length();
        final int max = str.length() - len;
        for (int i = 0; i <= max; i++) {
            if (str.regionMatches(true, i, searchStr, 0, len)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Represents storage volume information
     */
    public static final class StorageVolume {

        /**
         * Represents {@link StorageVolume} type
         */
        public enum Type {
            /**
             * Device built-in internal storage. Probably points to
             * {@link Environment#getExternalStorageDirectory()}
             */
            INTERNAL,

            /**
             * External storage. Probably removable, if no other
             * {@link StorageVolume} of type {@link #INTERNAL} is returned by
             * {@link StorageHelper#getStorages(boolean)}, this might be
             * pointing to {@link Environment#getExternalStorageDirectory()}
             */
            EXTERNAL,

            /**
             * Removable usb storage
             */
            USB
        }

        /**
         * Device name
         */
        public final String device;

        /**
         * Points to mount point of this device
         */
        public final File file;

        /**
         * File system of this device
         */
        public final String fileSystem;

        /**
         * if true, the storage is mounted as read-only
         */
        private boolean mReadOnly;

        /**
         * If true, the storage is removable
         */
        private boolean mRemovable;

        /**
         * If true, the storage is emulated
         */
        private boolean mEmulated;

        /**
         * Type of this storage
         */
        private Type mType;

        StorageVolume(String device, File file, String fileSystem) {
            this.device = device;
            this.file = file;
            this.fileSystem = fileSystem;
        }

        /**
         * Returns type of this storage
         * 
         * @return Type of this storage
         */
        public Type getType() {
            return mType;
        }

        /**
         * Returns true if this storage is removable
         * 
         * @return true if this storage is removable
         */
        public boolean isRemovable() {
            return mRemovable;
        }

        /**
         * Returns true if this storage is emulated
         * 
         * @return true if this storage is emulated
         */
        public boolean isEmulated() {
            return mEmulated;
        }

        /**
         * Returns true if this storage is mounted as read-only
         * 
         * @return true if this storage is mounted as read-only
         */
        public boolean isReadOnly() {
            return mReadOnly;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((file == null) ? 0 : file.hashCode());
            return result;
        }

        /**
         * Returns true if the other object is StorageHelper and it's
         * {@link #file} matches this one's
         * 
         * @see Object#equals(Object)
         */
        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final StorageVolume other = (StorageVolume) obj;
            if (file == null) {
                return other.file == null;
            }
            return file.equals(other.file);
        }

        @Override
        public String toString() {
            return file.getAbsolutePath() + (mReadOnly ? " ro " : " rw ") + mType + (mRemovable ? " R " : "")
                    + (mEmulated ? " E " : "") + fileSystem;
        }
    }
}

Singleton with Arguments in Java

I think this is a common problem. Separating the "initialization" of the singleton from the "get" of the singleton might work (this example uses a variation of double checked locking).

public class MySingleton {

    private static volatile MySingleton INSTANCE;

    @SuppressWarnings("UnusedAssignment")
    public static void initialize(
            final SomeDependency someDependency) {

        MySingleton result = INSTANCE;

        if (result != null) {
            throw new IllegalStateException("The singleton has already "
                    + "been initialized.");
        }

        synchronized (MySingleton.class) {
            result = INSTANCE;

            if (result == null) {
                INSTANCE = result = new MySingleton(someDependency);
            } 
        }
    }

    public static MySingleton get() {
        MySingleton  result = INSTANCE;

        if (result == null) {
            throw new IllegalStateException("The singleton has not been "
                    + "initialized. You must call initialize(...) before "
                    + "calling get()");
        }

       return result;
    }

    ...
}

Aesthetics must either be length one, or the same length as the dataProblems

I encountered this problem because the dataset was filtered wrongly and the resultant data frame was empty. Even the following caused the error to show:

ggplot(df, aes(x="", y = y, fill=grp))

because df was empty.

sorting a vector of structs

As others have mentioned, you could use a comparison function, but you can also overload the < operator and the default less<T> functor will work as well:

struct data {
    string word;
    int number;
    bool operator < (const data& rhs) const {
        return word.size() < rhs.word.size();
    }
};

Then it's just:

std::sort(info.begin(), info.end());

Edit

As James McNellis pointed out, sort does not actually use the less<T> functor by default. However, the rest of the statement that the less<T> functor will work as well is still correct, which means that if you wanted to put struct datas into a std::map or std::set this would still work, but the other answers which provide a comparison function would need additional code to work with either.

Where are SQL Server connection attempts logged?

Another way to check on connection attempts is to look at the server's event log. On my Windows 2008 R2 Enterprise machine I opened the server manager (right-click on Computer and select Manage. Then choose Diagnostics -> Event Viewer -> Windows Logs -> Applcation. You can filter the log to isolate the MSSQLSERVER events. I found a number that looked like this

Login failed for user 'bogus'. The user is not associated with a trusted SQL Server connection. [CLIENT: 10.12.3.126]

Angularjs loading screen on ajax request

I built on @DavidLin's answer a little to simplify it - removing any dependency on jQuery in the directive. I can confirm this works as I use it in a production application

function AjaxLoadingOverlay($http) {

    return {
        restrict: 'A',
        link: function ($scope, $element, $attributes) {

            $scope.loadingOverlay = false;

            $scope.isLoading = function () {
                return $http.pendingRequests.length > 0;
            };

            $scope.$watch($scope.isLoading, function (isLoading) {
                $scope.loadingOverlay = isLoading;
            });
        }
    };
}   

I use a ng-show instead of a jQuery call to hide/show the <div>.

Here's the <div> which I placed just below the opening <body> tag:

<div ajax-loading-overlay class="loading-overlay" ng-show="loadingOverlay">
    <img src="Resources/Images/LoadingAnimation.gif" />
</div>

And here's the CSS that provides the overlay to block UI while a $http call is being made:

.loading-overlay {
    position: fixed;
    z-index: 999;
    height: 2em;
    width: 2em;
    overflow: show;
    margin: auto;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

.loading-overlay:before {
    content: '';
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.3);
}

/* :not(:required) hides these rules from IE9 and below */
.loading-overlay:not(:required) {
    font: 0/0 a;
    color: transparent;
    text-shadow: none;
    background-color: transparent;
    border: 0;
}

CSS credit goes to @Steve Seeger's - his post: https://stackoverflow.com/a/35470281/335545

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

in angularjs how to access the element that triggered the event?

There is a solution using $element in the controller if you don't want to create another directive for this problem:

appControllers.controller('YourCtrl', ['$scope', '$timeout', '$element',
        function($scope, $timeout, $element) {

    $scope.updateTypeahead = function() {
       // ... some logic here
       $timeout(function() {
           $element[0].getElementsByClassName('search-query')[0].focus();
           // if you have unique id you can use $window instead of $element:
           // $window.document.getElementById('searchText').focus();
       });
    }
}]);

And this will work with ng-change:

<input id="searchText" type="text" class="search-query" ng-change="updateTypeahead()" ng-model="searchText" />

How to study design patterns?

I have found that it is a bit hard to comprehend or understand the benefits of some patterns until one understands the problems they solve and the other (worse) ways the problems have been implemented.

Other than the GOF and POSA books I have not really read any so I can't give you other recommendations. Really you just have to have an understanding of the problems domains and I think that many less experienced developers may not be able to appreciate the benefits of patterns. This is no slight against them. It is a lot easier to embrace, understand and appreciate good solutions when one has to struggle with poor alternatives first.

Good luck

Are there any log file about Windows Services Status?

Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.

In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.

enter image description here

The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:

"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."

How do I find duplicates across multiple columns?

Using count(*) over(partition by...) provides a simple and efficient means to locate unwanted repetition, whilst also list all affected rows and all wanted columns:

SELECT
    t.*
FROM (
    SELECT
        s.*
      , COUNT(*) OVER (PARTITION BY s.name, s.city) AS qty
    FROM stuff s
    ) t
WHERE t.qty > 1
ORDER BY t.name, t.city

While most recent RDBMS versions support count(*) over(partition by...) MySQL V 8.0 introduced "window functions", as seen below (in MySQL 8.0)

CREATE TABLE stuff(
   id   INTEGER  NOT NULL
  ,name VARCHAR(60) NOT NULL
  ,city VARCHAR(60) NOT NULL
);
INSERT INTO stuff(id,name,city) VALUES 
  (904834,'jim','London')
, (904835,'jim','London')
, (90145,'Fred','Paris')
, (90132,'Fred','Paris')
, (90133,'Fred','Paris')

, (923457,'Barney','New York') # not expected in result
;
SELECT
    t.*
FROM (
    SELECT
        s.*
      , COUNT(*) OVER (PARTITION BY s.name, s.city) AS qty
    FROM stuff s
    ) t
WHERE t.qty > 1
ORDER BY t.name, t.city
    id | name | city   | qty
-----: | :--- | :----- | --:
 90145 | Fred | Paris  |   3
 90132 | Fred | Paris  |   3
 90133 | Fred | Paris  |   3
904834 | jim  | London |   2
904835 | jim  | London |   2

db<>fiddle here

Window functions. MySQL now supports window functions that, for each row from a query, perform a calculation using rows related to that row. These include functions such as RANK(), LAG(), and NTILE(). In addition, several existing aggregate functions now can be used as window functions; for example, SUM() and AVG(). For more information, see Section 12.21, “Window Functions”.

Excel VBA select range at last row and column

The simplest modification (to the code in your question) is this:

    Range("A" & Rows.Count).End(xlUp).Select
    Selection.EntireRow.Delete

Which can be simplified to:

    Range("A" & Rows.Count).End(xlUp).EntireRow.Delete

Android: Tabs at the BOTTOM

For all those of you that try to remove the separating line of the tabWidget, here is an example project (and its respective tutorial), that work great for customizing the tabs and thus removing problems when tabs are at bottom. Eclipse Project: android-custom-tabs ; Original explanation: blog; Hope this helped.

How to identify platform/compiler from preprocessor macros?

If you're writing C++, I can't recommend using the Boost libraries strongly enough.

The latest version (1.55) includes a new Predef library which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.

#include <boost/predef.h>

// ...

#if BOOST_OS_WINDOWS

#elif BOOST_OS_LINUX

#elif BOOST_OS_MACOS

#endif

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

The resolution is to use TypedQuery instead. When creating a query from the EntityManager instead call it like this:

TypedQuery<[YourClass]> query = entityManager.createQuery("[your sql]", [YourClass].class);
List<[YourClass]> list = query.getResultList(); //no type warning

This also works the same for named queries, native named queries, etc. The corresponding methods have the same names as the ones that would return the vanilla query. Just use this instead of a Query whenever you know the return type.

What is the difference between MOV and LEA?

None of the previous answers quite got to the bottom of my own confusion, so I'd like to add my own.

What I was missing is that lea operations treat the use of parentheses different than how mov does.

Think of C. Let's say I have an array of long that I call array. Now the expression array[i] performs a dereference, loading the value from memory at the address array + i * sizeof(long) [1].

On the other hand, consider the expression &array[i]. This still contains the sub-expression array[i], but no dereferencing is performed! The meaning of array[i] has changed. It no longer means to perform a deference but instead acts as a kind of a specification, telling & what memory address we're looking for. If you like, you could alternatively think of the & as "cancelling out" the dereference.

Because the two use-cases are similar in many ways, they share the syntax array[i], but the existence or absence of a & changes how that syntax is interpreted. Without &, it's a dereference and actually reads from the array. With &, it's not. The value array + i * sizeof(long) is still calculated, but it is not dereferenced.

The situation is very similar with mov and lea. With mov, a dereference occurs that does not happen with lea. This is despite the use of parentheses that occurs in both. For instance, movq (%r8), %r9 and leaq (%r8), %r9. With mov, these parentheses mean "dereference"; with lea, they don't. This is similar to how array[i] only means "dereference" when there is no &.

An example is in order.

Consider the code

movq (%rdi, %rsi, 8), %rbp

This loads the value at the memory location %rdi + %rsi * 8 into the register %rbp. That is: get the value in the register %rdi and the value in the register %rsi. Multiply the latter by 8, and then add it to the former. Find the value at this location and place it into the register %rbp.

This code corresponds to the C line x = array[i];, where array becomes %rdi and i becomes %rsi and x becomes %rbp. The 8 is the length of the data type contained in the array.

Now consider similar code that uses lea:

leaq (%rdi, %rsi, 8), %rbp

Just as the use of movq corresponded to dereferencing, the use of leaq here corresponds to not dereferencing. This line of assembly corresponds to the C line x = &array[i];. Recall that & changes the meaning of array[i] from dereferencing to simply specifying a location. Likewise, the use of leaq changes the meaning of (%rdi, %rsi, 8) from dereferencing to specifying a location.

The semantics of this line of code are as follows: get the value in the register %rdi and the value in the register %rsi. Multiply the latter by 8, and then add it to the former. Place this value into the register %rbp. No load from memory is involved, just arithmetic operations [2].

Note that the only difference between my descriptions of leaq and movq is that movq does a dereference, and leaq doesn't. In fact, to write the leaq description, I basically copy+pasted the description of movq, and then removed "Find the value at this location".

To summarize: movq vs. leaq is tricky because they treat the use of parentheses, as in (%rsi) and (%rdi, %rsi, 8), differently. In movq (and all other instruction except lea), these parentheses denote a genuine dereference, whereas in leaq they do not and are purely convenient syntax.


[1] I've said that when array is an array of long, the expression array[i] loads the value from the address array + i * sizeof(long). This is true, but there's a subtlety that should be addressed. If I write the C code

long x = array[5];

this is not the same as typing

long x = *(array + 5 * sizeof(long));

It seems that it should be based on my previous statements, but it's not.

What's going on is that C pointer addition has a trick to it. Say I have a pointer p pointing to values of type T. The expression p + i does not mean "the position at p plus i bytes". Instead, the expression p + i actually means "the position at p plus i * sizeof(T) bytes".

The convenience of this is that to get "the next value" we just have to write p + 1 instead of p + 1 * sizeof(T).

This means that the C code long x = array[5]; is actually equivalent to

long x = *(array + 5)

because C will automatically multiply the 5 by sizeof(long).

So in the context of this StackOverflow question, how is this all relevant? It means that when I say "the address array + i * sizeof(long)", I do not mean for "array + i * sizeof(long)" to be interpreted as a C expression. I am doing the multiplication by sizeof(long) myself in order to make my answer more explicit, but understand that due to that, this expression should not be read as C. Just as normal math that uses C syntax.

[2] Side note: because all lea does is arithmetic operations, its arguments don't actually have to refer to valid addresses. For this reason, it's often used to perform pure arithmetic on values that may not be intended to be dereferenced. For instance, cc with -O2 optimization translates

long f(long x) {
  return x * 5;
}

into the following (irrelevant lines removed):

f:
  leaq (%rdi, %rdi, 4), %rax  # set %rax to %rdi + %rdi * 4
  ret

How to update single value inside specific array item in redux

In my case I did something like this, based on Luis's answer:

...State object...
userInfo = {
name: '...',
...
}

...Reducer's code...
case CHANGED_INFO:
return {
  ...state,
  userInfo: {
    ...state.userInfo,
    // I'm sending the arguments like this: changeInfo({ id: e.target.id, value: e.target.value }) and use them as below in reducer!
    [action.data.id]: action.data.value,
  },
};

Does the join order matter in SQL?

Oracle optimizer chooses join order of tables for inner join. Optimizer chooses the join order of tables only in simple FROM clauses . U can check the oracle documentation in their website. And for the left, right outer join the most voted answer is right. The optimizer chooses the optimal join order as well as the optimal index for each table. The join order can affect which index is the best choice. The optimizer can choose an index as the access path for a table if it is the inner table, but not if it is the outer table (and there are no further qualifications).

The optimizer chooses the join order of tables only in simple FROM clauses. Most joins using the JOIN keyword are flattened into simple joins, so the optimizer chooses their join order.

The optimizer does not choose the join order for outer joins; it uses the order specified in the statement.

When selecting a join order, the optimizer takes into account: The size of each table The indexes available on each table Whether an index on a table is useful in a particular join order The number of rows and pages to be scanned for each table in each join order

Unit testing private methods in C#

Yes, don't Test private methods.... The idea of a unit test is to test the unit by its public 'API'.

If you are finding you need to test a lot of private behavior, most likely you have a new 'class' hiding within the class you are trying to test, extract it and test it by its public interface.

One piece of advice / Thinking tool..... There is an idea that no method should ever be private. Meaning all methods should live on a public interface of an object.... if you feel you need to make it private, it most likely lives on another object.

This piece of advice doesn't quite work out in practice, but its mostly good advice, and often it will push people to decompose their objects into smaller objects.

How to create a DB link between two oracle instances

Creation of DB Link

CREATE DATABASE LINK dblinkname
CONNECT TO $usename
IDENTIFIED BY $password
USING '$sid';

(Note: sid is being passed between single quotes above. )

Example Queries for above DB Link

select * from tableA@dblinkname;

insert into tableA(select * from tableA@dblinkname);

UTL_FILE.FOPEN() procedure not accepting path for directory?

You need to have your DBA modify the init.ora file, adding the directory you want to access to the 'utl_file_dir' parameter. Your database instance will then need to be stopped and restarted because init.ora is only read when the database is brought up.

You can view (but not change) this parameter by running the following query:

SELECT *
  FROM V$PARAMETER
  WHERE NAME = 'utl_file_dir'

Share and enjoy.

How do I update a GitHub forked repository?

A lot of answers end up moving your fork one commit ahead of the parent repository. This answer summarizes the steps found here which will move your fork to the same commit as the parent.

  1. Change directory to your local repository.

    • Switch to master branch if you are not git checkout master
  2. Add the parent as a remote repository, git remote add upstream <repo-location>

  3. Issue git fetch upstream
  4. Issue git rebase upstream/master

    • At this stage you check that commits what will be merged by typing git status
  5. Issue git push origin master

For more information about these commands, refer to step 3.

create a text file using javascript

From a web page this cannot work since IE restricts the use of that object.

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<?php 
    $sessionDetails = $this->Session->read('Auth.User');

    if (!empty($sessionDetails)) {


        $loginFlag = 1;
        # code...
    }else{
        $loginFlag =  0;
    }


?>

<script type="text/javascript">

    var sessionValue = '<?php echo $loginFlag; ?>';
    if (sessionValue = 0) {

        //model show
    }
</script>

Find which commit is currently checked out in Git

You have at least 5 different ways to view the commit you currently have checked out into your working copy during a git bisect session (note that options 1-4 will also work when you're not doing a bisect):

  1. git show.
  2. git log -1.
  3. Bash prompt.
  4. git status.
  5. git bisect visualize.

I'll explain each option in detail below.

Option 1: git show

As explained in this answer to the general question of how to determine which commit you currently have checked-out (not just during git bisect), you can use git show with the -s option to suppress patch output:

$ git show --oneline -s
a9874fd Merge branch 'epic-feature'

Option 2: git log -1

You can also simply do git log -1 to find out which commit you're currently on.

$ git log -1 --oneline
c1abcde Add feature-003

Option 3: Bash prompt

In Git version 1.8.3+ (or was it an earlier version?), if you have your Bash prompt configured to show the current branch you have checked out into your working copy, then it will also show you the current commit you have checked out during a bisect session or when you're in a "detached HEAD" state. In the example below, I currently have c1abcde checked out:

# Prompt during a bisect
user ~ (c1abcde...)|BISECTING $

# Prompt at detached HEAD state 
user ~ (c1abcde...) $

Option 4: git status

Also as of Git version 1.8.3+ (and possibly earlier, again not sure), running git status will also show you what commit you have checked out during a bisect and when you're in detached HEAD state:

$ git status
# HEAD detached at c1abcde <== RIGHT HERE

Option 5: git bisect visualize

Finally, while you're doing a git bisect, you can also simply use git bisect visualize or its built-in alias git bisect view to launch gitk, so that you can graphically view which commit you are on, as well as which commits you have marked as bad and good so far. I'm pretty sure this existed well before version 1.8.3, I'm just not sure in which version it was introduced:

git bisect visualize 
git bisect view # shorter, means same thing

enter image description here

How to know a Pod's own IP address from inside a container in the Pod?

In some cases, instead of relying on downward API, programmatically reading the local IP address (from network interfaces) from inside of the container also works.

For example, in golang: https://stackoverflow.com/a/31551220/6247478

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

There's a really simple answer, which nobody else has mentioned:

function isLowerCase(str) {
    return str !== str.toUpperCase();
}

If str.toUpperCase() does not return the same str, it has to be lower case. To test for upper case you change it to str !== str.toLowererCase().

Unlike some other answers, it works correctly on non-alpha characters (returns false) and it works for other alphabets, accented characters etc.

How to force the browser to reload cached CSS and JavaScript files

Here is my Bash script-based cache busting solution:

  1. I assume you have CSS and JavaScript files referenced in your index.html file
  2. Add a timestamp as a parameter for .js and .css in index.html as below (one time only)
  3. Create a timestamp.txt file with the above timestamp.
  4. After any update to .css or .js file, just run the below .sh script

Sample index.html entries for .js and .css with a timestamp:

<link rel="stylesheet" href="bla_bla.css?v=my_timestamp">
<script src="scripts/bla_bla.js?v=my_timestamp"></script>

File timestamp.txt should only contain same timestamp 'my_timestamp' (will be searched for and replaced by script later on)

Finally here is the script (let's call it cache_buster.sh :D)

old_timestamp=$(cat timestamp.txt)
current_timestamp=$(date +%s)
sed -i -e "s/$old_timestamp/$current_timestamp/g" index.html
echo "$current_timestamp" >timestamp.txt

(Visual Studio Code users) you can put this script in a hook, so it gets called each time a file is saved in your workspace.

Size of Matrix OpenCV

If you are using the Python wrappers, then (assuming your matrix name is mat):

  • mat.shape gives you an array of the type- [height, width, channels]

  • mat.size gives you the size of the array

Sample Code:

import cv2
mat = cv2.imread('sample.png')
height, width, channel = mat.shape[:3]
size = mat.size

Two arrays in foreach loop

Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

becomes:

$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');

How do you perform address validation?

Yahoo has also a Placemaker API. It is good only for locations but it has an universal id for all world locations.

It look that there is no standard in ISO list.

Assigning default values to shell variables with a single command in bash

FWIW, you can provide an error message like so:

USERNAME=${1:?"Specify a username"}

This displays a message like this and exits with code 1:

./myscript.sh
./myscript.sh: line 2: 1: Specify a username

A more complete example of everything:

#!/bin/bash
ACTION=${1:?"Specify 'action' as argv[1]"}
DIRNAME=${2:-$PWD}
OUTPUT_DIR=${3:-${HOMEDIR:-"/tmp"}}

echo "$ACTION"
echo "$DIRNAME"
echo "$OUTPUT_DIR"

Output:

$ ./script.sh foo
foo
/path/to/pwd
/tmp

$ export HOMEDIR=/home/myuser
$ ./script.sh foo
foo
/path/to/pwd
/home/myuser
  • $ACTION takes the value of the first argument, and exits if empty
  • $DIRNAME is the 2nd argument, and defaults to the current directory
  • $OUTPUT_DIR is the 3rd argument, or $HOMEDIR (if defined), else, /tmp. This works on OS X, but I'm not positive that it's portable.

"Operation must use an updateable query" error in MS Access

This is a shot in the dark but try putting the two operands for the AND in parentheses

On ((A = B) And (C = D))

Better way to sort array in descending order

Yes, you can pass predicate to sort. That would be your reverse implementation.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

A little late to the party, but if you are looking for a solution like Yury's the following code will help you identify if the issue is related to a self-sign certificate and, if so ignore the self-sign error. You could obviously check for other SSL errors if you so desired.

The code we use (courtesy of Microsoft - http://msdn.microsoft.com/en-us/library/office/dd633677(v=exchg.80).aspx) is as follows:

  private static bool CertificateValidationCallBack(
         object sender,
         System.Security.Cryptography.X509Certificates.X509Certificate certificate,
         System.Security.Cryptography.X509Certificates.X509Chain chain,
         System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
  // If the certificate is a valid, signed certificate, return true.
  if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
  {
    return true;
  }

  // If there are errors in the certificate chain, look at each error to determine the cause.
  if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
  {
    if (chain != null && chain.ChainStatus != null)
    {
      foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
      {
        if ((certificate.Subject == certificate.Issuer) &&
           (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
        {
          // Self-signed certificates with an untrusted root are valid. 
          continue;
        }
        else
        {
          if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
          {
            // If there are any other errors in the certificate chain, the certificate is invalid,
         // so the method returns false.
            return false;
          }
        }
      }
    }

    // When processing reaches this line, the only errors in the certificate chain are 
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
    return true;
  }
  else
  {
 // In all other cases, return false.
    return false;
  }
}

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

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

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

setting screenshot

Write to .txt file?

FILE *fp;
char* str = "string";
int x = 10;

fp=fopen("test.txt", "w");
if(fp == NULL)
    exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);

Why do I keep getting Delete 'cr' [prettier/prettier]?

in the file .eslintrc.json in side roles add this code it will solve this issue

      "rules": {
    "prettier/prettier": ["error",{
      "endOfLine": "auto"}
    ]

  }

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

"java.lang.SecurityException: class" org.hamcrest.Matchers "'s signer information does not match signer information of other classes in the same package"

Do it: Right-click on your package click on Build Path -> Configure Build Path Click on the Libraries tab Remove JUnit Apply and close Ready.

How to achieve pagination/table layout with Angular.js?

I would use table and implement the pagination in the controller to control how much is shown and buttons to move to the next page. This Fiddle might help you.

example of the pagination

 <table class="table table-striped table-condensed table-hover">
                <thead>
                    <tr>
                        <th class="id">Id&nbsp;<a ng-click="sort_by('id')"><i class="icon-sort"></i></a></th>
                        <th class="name">Name&nbsp;<a ng-click="sort_by('name')"><i class="icon-sort"></i></a></th>
                        <th class="description">Description&nbsp;<a ng-click="sort_by('description')"><i class="icon-sort"></i></a></th>
                        <th class="field3">Field 3&nbsp;<a ng-click="sort_by('field3')"><i class="icon-sort"></i></a></th>
                        <th class="field4">Field 4&nbsp;<a ng-click="sort_by('field4')"><i class="icon-sort"></i></a></th>
                        <th class="field5">Field 5&nbsp;<a ng-click="sort_by('field5')"><i class="icon-sort"></i></a></th>
                    </tr>
                </thead>
                <tfoot>
                    <td colspan="6">
                        <div class="pagination pull-right">
                            <ul>
                                <li ng-class="{disabled: currentPage == 0}">
                                    <a href ng-click="prevPage()">« Prev</a>
                                </li>
                                <li ng-repeat="n in range(pagedItems.length)"
                                    ng-class="{active: n == currentPage}"
                                ng-click="setPage()">
                                    <a href ng-bind="n + 1">1</a>
                                </li>
                                <li ng-class="{disabled: currentPage == pagedItems.length - 1}">
                                    <a href ng-click="nextPage()">Next »</a>
                                </li>
                            </ul>
                        </div>
                    </td>
                </tfoot>
                <tbody>
                    <tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.description}}</td>
                        <td>{{item.field3}}</td>
                        <td>{{item.field4}}</td>
                        <td>{{item.field5}}</td>
                    </tr>
                </tbody>
            </table> 

the $scope.range in the fiddle example should be:

$scope.range = function (size,start, end) {
    var ret = [];        
    console.log(size,start, end);

       if (size < end) {
        end = size;
        if(size<$scope.gap){
             start = 0;
        }else{
             start = size-$scope.gap;
        }

    }
    for (var i = start; i < end; i++) {
        ret.push(i);
    }        
     console.log(ret);        
    return ret;
};

Partly cherry-picking a commit with Git

If "partly cherry picking" means "within files, choosing some changes but discarding others", it can be done by bringing in git stash:

  1. Do the full cherry pick.
  2. git reset HEAD^ to convert the entire cherry-picked commit into unstaged working changes.
  3. Now git stash save --patch: interactively select unwanted material to stash.
  4. Git rolls back the stashed changes from your working copy.
  5. git commit
  6. Throw away the stash of unwanted changes: git stash drop.

Tip: if you give the stash of unwanted changes a name: git stash save --patch junk then if you forget to do (6) now, later you will recognize the stash for what it is.

Django - Did you forget to register or load this tag?

You need to change:

{% endblock content %}

to

{% endblock %}

Maven: The packaging for this project did not assign a file to the build artifact

I had the same issue but I executed mvn install initially (not install:install as it was mentioned earlier).

The solution is to include:

 <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.5.2</version>
 </plugin>

Into plugin management section.

How to display (print) vector in Matlab?

You can use

x = [1, 2, 3]
disp(sprintf('Answer: (%d, %d, %d)', x))

This results in

Answer: (1, 2, 3)

For vectors of arbitrary size, you can use

disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))

An alternative way would be

disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))

Difference between res.send and res.json in Express.js

https://github.com/visionmedia/express/blob/ee228f7aea6448cf85cc052697f8d831dce785d5/lib/response.js#L174

res.json eventually calls res.send, but before that it:

  • respects the json spaces and json replacer app settings
  • ensures the response will have utf8 charset and application/json content-type

Applying function with multiple arguments to create a new pandas column

If you need to create multiple columns at once:

  1. Create the dataframe:

    import pandas as pd
    df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
    
  2. Create the function:

    def fab(row):                                                  
        return row['A'] * row['B'], row['A'] + row['B']
    
  3. Assign the new columns:

    df['newcolumn'], df['newcolumn2'] = zip(*df.apply(fab, axis=1))
    

What is fastest children() or find() in jQuery?

None of the other answers dealt with the case of using .children() or .find(">") to only search for immediate children of a parent element. So, I created a jsPerf test to find out, using three different ways to distinguish children.

As it happens, even when using the extra ">" selector, .find() is still a lot faster than .children(); on my system, 10x so.

So, from my perspective, there does not appear to be much reason to use the filtering mechanism of .children() at all.

Passing arguments to "make run"

for standard make you can pass arguments by defining macros like this

make run arg1=asdf

then use them like this

run: ./prog $(arg1)
   etc

References for make Microsoft's NMake

How can I scale an entire web page with CSS?

As Johannes says -- not enough rep to comment directly on his answer -- you can indeed do this as long as all elements' "dimensions are specified as a multiple of the font's size. Meaning, everything where you used %, em or ex units". Although I think % are based on containing element, not font-size.

And you wouldn't normally use these relative units for images, given they are composed of pixels, but there's a trick which makes this a lot more practical.

If you define body{font-size: 62.5%}; then 1em will be equivalent to 10px. As far as I know this works across all main browsers.

Then you can specify your (e.g.) 100px square images with width: 10em; height: 10em; and assuming Firefox's scaling is set to default, the images will be their natural size.

Make body{font-size: 125%}; and everything - including images - wil be double original size.

Check if character is number?

This function works for all test cases that i could find. It's also faster than:

function isNumeric (n) {
  if (!isNaN(parseFloat(n)) && isFinite(n) && !hasLeading0s(n)) {
    return true;
  }
  var _n = +n;
  return _n === Infinity || _n === -Infinity;
}

_x000D_
_x000D_
var isIntegerTest = /^\d+$/;_x000D_
var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0];_x000D_
_x000D_
function hasLeading0s(s) {_x000D_
  return !(typeof s !== 'string' ||_x000D_
    s.length < 2 ||_x000D_
    s[0] !== '0' ||_x000D_
    !isDigitArray[s[1]] ||_x000D_
    isIntegerTest.test(s));_x000D_
}_x000D_
var isWhiteSpaceTest = /\s/;_x000D_
_x000D_
function fIsNaN(n) {_x000D_
  return !(n <= 0) && !(n > 0);_x000D_
}_x000D_
_x000D_
function isNumber(s) {_x000D_
  var t = typeof s;_x000D_
  if (t === 'number') {_x000D_
    return (s <= 0) || (s > 0);_x000D_
  } else if (t === 'string') {_x000D_
    var n = +s;_x000D_
    return !(fIsNaN(n) || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));_x000D_
  } else if (t === 'object') {_x000D_
    return !(!(s instanceof Number) || fIsNaN(+s));_x000D_
  }_x000D_
  return false;_x000D_
}_x000D_
_x000D_
function testRunner(IsNumeric) {_x000D_
  var total = 0;_x000D_
  var passed = 0;_x000D_
  var failedTests = [];_x000D_
_x000D_
  function test(value, result) {_x000D_
    total++;_x000D_
    if (IsNumeric(value) === result) {_x000D_
      passed++;_x000D_
    } else {_x000D_
      failedTests.push({_x000D_
        value: value,_x000D_
        expected: result_x000D_
      });_x000D_
    }_x000D_
  }_x000D_
  // true_x000D_
  test(0, true);_x000D_
  test(1, true);_x000D_
  test(-1, true);_x000D_
  test(Infinity, true);_x000D_
  test('Infinity', true);_x000D_
  test(-Infinity, true);_x000D_
  test('-Infinity', true);_x000D_
  test(1.1, true);_x000D_
  test(-0.12e-34, true);_x000D_
  test(8e5, true);_x000D_
  test('1', true);_x000D_
  test('0', true);_x000D_
  test('-1', true);_x000D_
  test('1.1', true);_x000D_
  test('11.112', true);_x000D_
  test('.1', true);_x000D_
  test('.12e34', true);_x000D_
  test('-.12e34', true);_x000D_
  test('.12e-34', true);_x000D_
  test('-.12e-34', true);_x000D_
  test('8e5', true);_x000D_
  test('0x89f', true);_x000D_
  test('00', true);_x000D_
  test('01', true);_x000D_
  test('10', true);_x000D_
  test('0e1', true);_x000D_
  test('0e01', true);_x000D_
  test('.0', true);_x000D_
  test('0.', true);_x000D_
  test('.0e1', true);_x000D_
  test('0.e1', true);_x000D_
  test('0.e00', true);_x000D_
  test('0xf', true);_x000D_
  test('0Xf', true);_x000D_
  test(Date.now(), true);_x000D_
  test(new Number(0), true);_x000D_
  test(new Number(1e3), true);_x000D_
  test(new Number(0.1234), true);_x000D_
  test(new Number(Infinity), true);_x000D_
  test(new Number(-Infinity), true);_x000D_
  // false_x000D_
  test('', false);_x000D_
  test(' ', false);_x000D_
  test(false, false);_x000D_
  test('false', false);_x000D_
  test(true, false);_x000D_
  test('true', false);_x000D_
  test('99,999', false);_x000D_
  test('#abcdef', false);_x000D_
  test('1.2.3', false);_x000D_
  test('blah', false);_x000D_
  test('\t\t', false);_x000D_
  test('\n\r', false);_x000D_
  test('\r', false);_x000D_
  test(NaN, false);_x000D_
  test('NaN', false);_x000D_
  test(null, false);_x000D_
  test('null', false);_x000D_
  test(new Date(), false);_x000D_
  test({}, false);_x000D_
  test([], false);_x000D_
  test(new Int8Array(), false);_x000D_
  test(new Uint8Array(), false);_x000D_
  test(new Uint8ClampedArray(), false);_x000D_
  test(new Int16Array(), false);_x000D_
  test(new Uint16Array(), false);_x000D_
  test(new Int32Array(), false);_x000D_
  test(new Uint32Array(), false);_x000D_
  test(new BigInt64Array(), false);_x000D_
  test(new BigUint64Array(), false);_x000D_
  test(new Float32Array(), false);_x000D_
  test(new Float64Array(), false);_x000D_
  test('.e0', false);_x000D_
  test('.', false);_x000D_
  test('00e1', false);_x000D_
  test('01e1', false);_x000D_
  test('00.0', false);_x000D_
  test('01.05', false);_x000D_
  test('00x0', false);_x000D_
  test(new Number(NaN), false);_x000D_
  test(new Number('abc'), false);_x000D_
  console.log('Passed ' + passed + ' of ' + total + ' tests.');_x000D_
  if (failedTests.length > 0) console.log({_x000D_
    failedTests: failedTests_x000D_
  });_x000D_
}_x000D_
testRunner(isNumber)
_x000D_
_x000D_
_x000D_

Does Google Chrome work with Selenium IDE (as Firefox does)?

Just fyi . This is available as nuget package in visual studio environment. Please let me know if you need more information as I have used it. URL can be found Link to nuget

You can also find some information here. Blog with more details

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

Remove rows with all or some NAs (missing values) in data.frame

If you want control over how many NAs are valid for each row, try this function. For many survey data sets, too many blank question responses can ruin the results. So they are deleted after a certain threshold. This function will allow you to choose how many NAs the row can have before it's deleted:

delete.na <- function(DF, n=0) {
  DF[rowSums(is.na(DF)) <= n,]
}

By default, it will eliminate all NAs:

delete.na(final)
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
6 ENSG00000221312    0    1    2    3    2

Or specify the maximum number of NAs allowed:

delete.na(final, 2)
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
4 ENSG00000207604    0   NA   NA    1    2
6 ENSG00000221312    0    1    2    3    2

How to set breakpoints in inline Javascript in Google Chrome?

Refresh the page containing the script whilst the developer tools are open on the scripts tab. This will add a (program) entry in the file list which shows the html of the page including the script. From here you can add breakpoints.

Swift GET request with parameters

When building a GET request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also use URLComponents.

var url = URLComponents(string: "https://www.google.com/search/")!

url.queryItems = [
    URLQueryItem(name: "q", value: "War & Peace")
]

The only trick is that most web services need + character percent escaped (because they'll interpret that as a space character as dictated by the application/x-www-form-urlencoded specification). But URLComponents will not percent escape it. Apple contends that + is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning in application/x-www-form-urlencoded requests and really should not be passed unescaped.

Apple acknowledges that we have to percent escaping the + characters, but advises that we do it manually:

var url = URLComponents(string: "https://www.wolframalpha.com/input/")!

url.queryItems = [
    URLQueryItem(name: "i", value: "1+2")
]

url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")

This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a + character and you have a server that interprets them as spaces.

So, combining that with your sendRequest routine, you end up with something like:

func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
    var components = URLComponents(string: url)!
    components.queryItems = parameters.map { (key, value) in 
        URLQueryItem(name: key, value: value) 
    }
    components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
    let request = URLRequest(url: components.url!)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data,                            // is there data
            let response = response as? HTTPURLResponse,  // is there HTTP response
            (200 ..< 300) ~= response.statusCode,         // is statusCode 2XX
            error == nil else {                           // was there no error, otherwise ...
                completion(nil, error)
                return
        }

        let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
        completion(responseObject, nil)
    }
    task.resume()
}

And you'd call it like:

sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
    guard let responseObject = responseObject, error == nil else {
        print(error ?? "Unknown error")
        return
    }

    // use `responseObject` here
}

Personally, I'd use JSONDecoder nowadays and return a custom struct rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.


See previous revision of this answer for Swift 2 and manual percent escaping renditions.

Rename Excel Sheet with VBA Macro

The "no frills" options are as follows:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

PHP Redirect with POST data

Try this:

Send data and request with http header in page B to redirect to Gateway

<?php
$host = "www.example.com";
$path = "/path/to/script.php";
$data = "data1=value1&data2=value2";
$data = urlencode($data);

header("POST $path HTTP/1.1\\r\
" );
header("Host: $host\\r\
" );
header("Content-type: application/x-www-form-urlencoded\\r\
" );
header("Content-length: " . strlen($data) . "\\r\
" );
header("Connection: close\\r\
\\r\
" );
header($data);
?>

Additional Headers :

Accept: \*/\*
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like 
Gecko) Chrome/74.0.3729.169 Safari/537.36

How can I run a directive after the dom has finished rendering?

It depends on how your $('site-header') is constructed.

You can try to use $timeout with 0 delay. Something like:

return function(scope, element, attrs) {
    $timeout(function(){
        $('.main').height( $('.site-header').height() -  $('.site-footer').height() );
    });        
}

Explanations how it works: one, two.

Don't forget to inject $timeout in your directive:

.directive('sticky', function($timeout)

Set drawable size programmatically

The setBounds() method doesn't work for every type of container (did work for some of my ImageView's, however).

Try the method below to scale the drawable itself:

// Read your drawable from somewhere
Drawable dr = getResources().getDrawable(R.drawable.somedrawable);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
// Scale it to 50 x 50
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50, 50, true));
// Set your new, scaled drawable "d"

What is the difference between rb and r+b modes in file objects

My understanding is that adding r+ opens for both read and write (just like w+, though as pointed out in the comment, will truncate the file). The b just opens it in binary mode, which is supposed to be less aware of things like line separators (at least in C++).

numpy: most efficient frequency counts for unique values in an array

This is by far the most general and performant solution; surprised it hasn't been posted yet.

import numpy as np

def unique_count(a):
    unique, inverse = np.unique(a, return_inverse=True)
    count = np.zeros(len(unique), np.int)
    np.add.at(count, inverse, 1)
    return np.vstack(( unique, count)).T

print unique_count(np.random.randint(-10,10,100))

Unlike the currently accepted answer, it works on any datatype that is sortable (not just positive ints), and it has optimal performance; the only significant expense is in the sorting done by np.unique.

Delete all objects in a list

Here's how you delete every item from a list.

del c[:]

Here's how you delete the first two items from a list.

del c[:2]

Here's how you delete a single item from a list (a in your case), assuming c is a list.

del c[0]

1030 Got error 28 from storage engine

My /tmp was %100. After removing all files and restarting mysql everything worked fine.

re.sub erroring with "Expected string or bytes-like object"

I suppose better would be to use re.match() function. here is an example which may help you.

import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]  
sentences

Safely remove migration In Laravel

This works for me:

  1. I deleted all tables in my database, mainly the migrations table.
  2. php artisan migrate:refresh

in laravel 5.5.43

JQuery: dynamic height() with window resize()

Okay, how about a CSS answer! We use display: table. Then each of the divs are rows, and finally we apply height of 100% to middle 'row' and voilà.

http://jsfiddle.net/NfmX3/3/

body { display: table; }
div { display: table-row; }
#content {
    width:450px; 
    margin:0 auto;
    text-align: center;
    background-color: blue;
    color: white;
    height: 100%;
}

Cleanest way to reset forms

Add a reference to the ngForm directive in your html code and this gives you access to the form.

<form #myForm="ngForm" (ngSubmit)="addPost(); myForm.reset()"> ... </form>

Or pass the form to the function:

<form #myForm="ngForm" (ngSubmit)="addPost(myForm)"> ... </form>
addPost(form: NgForm){
    this.newPost = {
        title: this.title,
        body: this.body
    }
    this._postService.addPost(this.newPost);
    form.resetForm(); // or form.reset();
}

The difference between resetForm and reset is that the former will clear the form fields as well as any validation, while the later will only clear the fields. Use resetForm after the form is validated and submitted, otherwise use reset.


Adding another example for people who can't get the above to work.

With button press:

<form #heroForm="ngForm">
    ...
    <button type="button" class="btn btn-default" (click)="newHero(); heroForm.reset()">New Hero</button>
</form>

Same thing applies above, you can also choose to pass the form to the newHero function.

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

What is the difference between Subject and BehaviorSubject?

BehaviourSubject

BehaviourSubject will return the initial value or the current value on Subscription

var bSubject= new Rx.BehaviorSubject(0);  // 0 is the initial value

bSubject.subscribe({
  next: (v) => console.log('observerA: ' + v)  // output initial value, then new values on `next` triggers
});

bSubject.next(1);  // output new value 1 for 'observer A'
bSubject.next(2);  // output new value 2 for 'observer A', current value 2 for 'Observer B' on subscription

bSubject.subscribe({
  next: (v) => console.log('observerB: ' + v)  // output current value 2, then new values on `next` triggers
});

bSubject.next(3);

With output:

observerA: 0
observerA: 1
observerA: 2
observerB: 2
observerA: 3
observerB: 3

Subject

Subject does not return the current value on Subscription. It triggers only on .next(value) call and return/output the value

var subject = new Rx.Subject();

subject.next(1); //Subjects will not output this value

subject.subscribe({
  next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
  next: (v) => console.log('observerB: ' + v)
});

subject.next(2);
subject.next(3);

With the following output on the console:

observerA: 2
observerB: 2
observerA: 3
observerB: 3

Converting java.util.Properties to HashMap<String,String>

I would use following Guava API: com.google.common.collect.Maps#fromProperties

Properties properties = new Properties();
Map<String, String> map = Maps.fromProperties(properties);

How to run sql script using SQL Server Management Studio?

This website has a concise tutorial on how to use SQL Server Management Studio. As you will see you can open a "Query Window", paste your script and run it. It does not allow you to execute scripts by using the file path. However, you can do this easily by using the command line (cmd.exe):

sqlcmd -S .\SQLExpress -i SqlScript.sql

Where SqlScript.sql is the script file name located at the current directory. See this Microsoft page for more examples

What port is used by Java RMI connection?

With reference to other answers above, here is my view -

there are ports involved on both client and server side.

  • for server/remote side, if you export the object without providing a port , remote object would use a random port to listen.

  • a client, when looks up the remote object, it would always use a random port on its side and will connect to the remote object port as listed above.

Programmatically navigate using React router

Using the "useHistory" hook is the best option if you're using a newer version of react

Can we instantiate an abstract class?

Abstract classes cannot be instantiated, but they can be subclassed. See This Link

The best example is

Although Calender class has a abstract method getInstance(), but when you say Calendar calc=Calendar.getInstance();

calc is referring to the class instance of class GregorianCalendar as "GregorianCalendar extends Calendar "

Infact annonymous inner type allows you to create a no-name subclass of the abstract class and an instance of this.

How to transfer data from JSP to servlet when submitting HTML form

Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet and inside it you will have two methods that look like

public void doPost(HttpServletRequest req, HttpServletResponse resp){

}

and

public void doGet(HttpServletRequest req, HttpServletResponse resp){

}

One of them is called to handle GET operations and another is used to handle POST operations. You will then use the HttpServletRequest object to get the parameters that were passed as part of the form like so:

String name = req.getParameter("name");

Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.

Normalize data in pandas

This is how you do it column-wise:

[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]

JPA Query selecting only specific columns without using Criteria Query?

Projections can be used to select only specific properties(columns) of an entity object.

From the docs

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons. In this section, you will learn how to define projections to serve up simplified and reduced views of resources.

Define an interface with only the getters you want.

interface CustomObject {  
    String getA(); // Actual property name is A
    String getB(); // Actual property name is B 
}

Now return CustomObject from your repository like so :

public interface YOU_REPOSITORY_NAME extends JpaRepository<YOUR_ENTITY, Long> {
    CustomObject findByObjectName(String name);
}

How to get the index of an item in a list in a single step?

  1. Simple solution to find index for any string value in the List.

Here is code for List Of String:

int indexOfValue = myList.FindIndex(a => a.Contains("insert value from list"));
  1. Simple solution to find index for any Integer value in the List.

Here is Code for List Of Integer:

    int indexOfNumber = myList.IndexOf(/*insert number from list*/);

Is there an equivalent to background-size: cover and contain for image elements?

No, you can't get it quite like background-size:cover but..

This approach is pretty damn close: it uses JavaScript to determine if the image is landscape or portrait, and applies styles accordingly.

JS

 $('.myImages img').load(function(){
        var height = $(this).height();
        var width = $(this).width();
        console.log('widthandheight:',width,height);
        if(width>height){
            $(this).addClass('wide-img');
        }else{
            $(this).addClass('tall-img');
        }
    });

CSS

.tall-img{
    margin-top:-50%;
    width:100%;
}
.wide-img{
    margin-left:-50%;
    height:100%;
}

http://jsfiddle.net/b3PbT/

How do I deploy Node.js applications as a single executable file?

You could create a git repo and setup a link to the node git repo as a dependency. Then any user who clones the repo could also install node.

#git submodule [--quiet] add [-b branch] [-f|--force]
git submodule add /var/Node-repo.git common

You could easily package a script up to automatically clone the git repo you have hosted somewhere and "install" from one that one script file.

#!/bin/sh
#clone git repo
git clone your-repo.git

MySQL parameterized queries

Here is another way to do it. It's documented on the MySQL official website. https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

In the spirit, it's using the same mechanic of @Trey Stout's answer. However, I find this one prettier and more readable.

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

And to better illustrate any need for variables:

NB: note the escape being done.

employee_id = 2
first_name = "Jane"
last_name = "Doe"

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (employee_id, conn.escape_string(first_name), conn.escape_string(last_name), datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

Managing large binary files with Git

You can also use git-fat. I like that it only depends on stock Python and rsync. It also supports the usual Git workflow, with the following self explanatory commands:

git fat init
git fat push
git fat pull

In addition, you need to check in a .gitfat file into your repository and modify your .gitattributes to specify the file extensions you want git fat to manage.

You add a binary using the normal git add, which in turn invokes git fat based on your gitattributes rules.

Finally, it has the advantage that the location where your binaries are actually stored can be shared across repositories and users and supports anything rsync does.

UPDATE: Do not use git-fat if you're using a Git-SVN bridge. It will end up removing the binary files from your Subversion repository. However, if you're using a pure Git repository, it works beautifully.

Remote branch is not showing up in "git branch -r"

Update your remote if you still haven't done so:

$ git remote update
$ git branch -r

Calculating days between two dates with Java

In Java 8, you could accomplish this by using LocalDate and DateTimeFormatter. From the Javadoc of LocalDate:

LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day.

And the pattern can be constructed using DateTimeFormatter. Here is the Javadoc, and the relevant pattern characters I used:

Symbol - Meaning - Presentation - Examples

y - year-of-era - year - 2004; 04

M/L - month-of-year - number/text - 7; 07; Jul; July; J

d - day-of-month - number - 10

Here is the example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Java8DateExample {
    public static void main(String[] args) throws IOException {
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MM yyyy");
        final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        final String firstInput = reader.readLine();
        final String secondInput = reader.readLine();
        final LocalDate firstDate = LocalDate.parse(firstInput, formatter);
        final LocalDate secondDate = LocalDate.parse(secondInput, formatter);
        final long days = ChronoUnit.DAYS.between(firstDate, secondDate);
        System.out.println("Days between: " + days);
    }
}

Example input/output with more recent last:

23 01 1997
27 04 1997
Days between: 94

With more recent first:

27 04 1997
23 01 1997
Days between: -94

Well, you could do it as a method in a simpler way:

public static long betweenDates(Date firstDate, Date secondDate) throws IOException
{
    return ChronoUnit.DAYS.between(firstDate.toInstant(), secondDate.toInstant());
}

Mongodb: failed to connect to server on first connect

For me,issue was mongo was not running.So first i started "mongod" command in the console.And later in another console tab I have run "mongo". Now the connection is successful. Now run your app your problem should be solved.

How to check whether java is installed on the computer

1)Open the command prompt or terminal based on your OS.

2)Then type java --version in the terminal.

3) If java is installed successfullly it will show the respective version .

How to use Typescript with native ES6 Promises

As of TypeScript 2.0 you can include typings for native promises by including the following in your tsconfig.json

"compilerOptions": {
    "lib": ["es5", "es2015.promise"]
}

This will include the promise declarations that comes with TypeScript without having to set the target to ES6.

Random character generator with a range of (A..Z, 0..9) and punctuation

  1. Pick a random number between [0, x), where x is the number of different symbols. Hopefully the choice is uniformly chosen and not predictable :-)

  2. Now choose the symbol representing x.

  3. Profit!

I would start reading up Pseudorandomness and then some common Pseudo-random number generators. Of course, your language hopefully already has a suitable "random" function :-)

C# Get/Set Syntax Usage

You are not able to access those properties as they are marked as protected meaning:

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

C# - Simplest way to remove first occurrence of a substring from another string

int index = sourceString.IndexOf(removeString);
string cleanPath = (index < 0)
    ? sourceString
    : sourceString.Remove(index, removeString.Length);

Running python script inside ipython

The %run magic has a parameter file_finder that it uses to get the full path to the file to execute (see here); as you note, it just looks in the current directory, appending ".py" if necessary.

There doesn't seem to be a way to specify which file finder to use from the %run magic, but there's nothing to stop you from defining your own magic command that calls into %run with an appropriate file finder.

As a very nasty hack, you could override the default file_finder with your own:

IPython.core.magics.execution.ExecutionMagics.run.im_func.func_defaults[2] = my_file_finder

To be honest, at the rate the IPython API is changing that's as likely to continue to work as defining your own magic is.

How to keep the header static, always on top while scrolling?

I personally needed a table with both the left and top headers visible at all times. Inspired by several articles, I think I have a good solution that you may find helpful. This version does not have the wrapping problem that other soltions have with floating divs or flexible/auto sizing of columns and rows.

<!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>
    <title></title>
    <script language="javascript" type="text/javascript" src="/Scripts/jquery-1.7.2.min.js"></script>
    <script language="javascript" type="text/javascript">
        // Handler for scrolling events
        function scrollFixedHeaderTable() {
            var outerPanel = $("#_outerPanel");
            var cloneLeft = $("#_cloneLeft");
            var cloneTop = $("#_cloneTop");
            cloneLeft.css({ 'margin-top': -outerPanel.scrollTop() });
            cloneTop.css({ 'margin-left': -outerPanel.scrollLeft() });
        }

        function initFixedHeaderTable() {
            var outerPanel = $("#_outerPanel");
            var innerPanel = $("#_innerPanel");
            var clonePanel = $("#_clonePanel");
            var table = $("#_table");
            // We will clone the table 2 times: For the top rowq and the left column. 
            var cloneLeft = $("#_cloneLeft");
            var cloneTop = $("#_cloneTop");
            var cloneTop = $("#_cloneTopLeft");
            // Time to create the table clones
            cloneLeft = table.clone();
            cloneTop = table.clone();
            cloneTopLeft = table.clone();
            cloneLeft.attr('id', '_cloneLeft');
            cloneTop.attr('id', '_cloneTop');
            cloneTopLeft.attr('id', '_cloneTopLeft');
            cloneLeft.css({
                position: 'fixed',
                'pointer-events': 'none',
                top: outerPanel.offset().top,
                'z-index': 1 // keep lower than top-left below
            });
            cloneTop.css({
                position: 'fixed',
                'pointer-events': 'none',
                top: outerPanel.offset().top,
                'z-index': 1 // keep lower than top-left below
            });
            cloneTopLeft.css({
                position: 'fixed',
                'pointer-events': 'none',
                top: outerPanel.offset().top,
                'z-index': 2 // higher z-index than the left and top to make the top-left header cell logical
            });
            // Add the controls to the control-tree
            clonePanel.append(cloneLeft);
            clonePanel.append(cloneTop);
            clonePanel.append(cloneTopLeft);
            // Keep all hidden: We will make the individual header cells visible in a moment
            cloneLeft.css({ visibility: 'hidden' });
            cloneTop.css({ visibility: 'hidden' });
            cloneTopLeft.css({ visibility: 'hidden' });
            // Make the lef column header cells visible in the left clone
            $("#_cloneLeft td._hdr.__row").css({
                visibility: 'visible',
            });
            // Make the top row header cells visible in the top clone
            $("#_cloneTop td._hdr.__col").css({
                visibility: 'visible',
            });
            // Make the top-left cell visible in the top-left clone
            $("#_cloneTopLeft td._hdr.__col.__row").css({
                visibility: 'visible',
            });
            // Clipping. First get the inner width/height by measuring it (normal innerWidth did not work for me)
            var helperDiv = $('<div style="positions: absolute; top: 0; right: 0; bottom: 0; left: 0; height: 100%;"></div>');
            outerPanel.append(helperDiv);
            var innerWidth = helperDiv.width();
            var innerHeight = helperDiv.height();
            helperDiv.remove(); // because we dont need it anymore, do we?
            // Make sure all the panels are clipped, or the clones will extend beyond them
            outerPanel.css({ clip: 'rect(0px,' + String(outerPanel.width()) + 'px,' + String(outerPanel.height()) + 'px,0px)' });
            // Clone panel clipping to prevent the clones from covering the outerPanel's scrollbars (this is why we use a separate div for this)
            clonePanel.css({ clip: 'rect(0px,' + String(innerWidth) + 'px,' + String(innerHeight) + 'px,0px)'   });
            // Subscribe the scrolling of the outer panel to our own handler function to move the clones as needed.
            $("#_outerPanel").scroll(scrollFixedHeaderTable);
        }


        $(document).ready(function () {
            initFixedHeaderTable();
        });

    </script>
    <style type="text/css">
        * {
            clip: rect font-family: Arial;
            font-size: 16px;
            margin: 0;
            padding: 0;
        }

        #_outerPanel {
            margin: 0px;
            padding: 0px;
            position: absolute;
            left: 50px;
            top: 50px;
            right: 50px;
            bottom: 50px;
            overflow: auto;
            z-index: 1000;
        }

        #_innerPanel {
            overflow: visible;
            position: absolute;
        }

        #_clonePanel {
            overflow: visible;
            position: fixed;
        }

        table {
        }

        td {
            white-space: nowrap;
            border-right: 1px solid #000;
            border-bottom: 1px solid #000;
            padding: 2px 2px 2px 2px;
        }

        td._hdr {
            color: Blue;
            font-weight: bold;
        }
        td._hdr.__row {
            background-color: #eee;
            border-left: 1px solid #000;
        }
        td._hdr.__col {
            background-color: #ddd;
            border-top: 1px solid #000;
        }
    </style>
</head>
<body>
    <div id="_outerPanel">
        <div id="_innerPanel">
            <div id="_clonePanel"></div>
            <table id="_table" border="0" cellpadding="0" cellspacing="0">
                <thead id="_topHeader" style="background-color: White;">
                    <tr class="row">
                        <td class="_hdr __col __row">
                            &nbsp;
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                    </tr>
                </thead>
                <tbody>
                    <tr class="row">
                        <td class="_hdr __row">
                            MY HEADER COLUMN:
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                    </tr>
                    <tr class="row">
                        <td class="_hdr __row">
                            MY HEADER COLUMN:
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div id="_bottomAnchor">
        </div>
    </div>
</body>
</html>

Python sys.argv lists and indexes

So if I wanted to return a first name and last name like: Hello Fred Gerbig I would use the code below, this code works but is it actually the most correct way to do it?

import sys
def main():
  if len(sys.argv) >= 2:
    fname = sys.argv[1]
    lname = sys.argv[2]
  else:
    name = 'World'
  print 'Hello', fname, lname
if __name__ == '__main__':
  main()

Edit: Found that the above code works with 2 arguments but crashes with 1. Tried to set len to 3 but that did nothing, still crashes (re-read the other answers and now understand why the 3 did nothing). How do I bypass the arguments if only one is entered? Or how would error checking look that returned "You must enter 2 arguments"?

Edit 2: Got it figured out:

import sys
def main():
  if len(sys.argv) >= 2:
    name = sys.argv[1] + " " + sys.argv[2]
  else:
    name = 'World'
  print 'Hello', name
if __name__ == '__main__':
  main()

Caching a jquery ajax response in javascript/browser

I was looking for caching for my phonegap app storage and I found the answer of @TecHunter which is great but done using localCache.

I found and come to know that localStorage is another alternative to cache the data returned by ajax call. So, I created one demo using localStorage which will help others who may want to use localStorage instead of localCache for caching.

Ajax Call:

$.ajax({
    type: "POST",
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    url: url,
    data: '{"Id":"' + Id + '"}',
    cache: true, //It must "true" if you want to cache else "false"
    //async: false,
    success: function (data) {
        var resData = JSON.parse(data);
        var Info = resData.Info;
        if (Info) {
            customerName = Info.FirstName;
        }
    },
    error: function (xhr, textStatus, error) {
        alert("Error Happened!");
    }
});

To store data into localStorage:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.cache) {
    var success = originalOptions.success || $.noop,
        url = originalOptions.url;

    options.cache = false; //remove jQuery cache as we have our own localStorage
    options.beforeSend = function () {
        if (localStorage.getItem(url)) {
            success(localStorage.getItem(url));
            return false;
        }
        return true;
    };
    options.success = function (data, textStatus) {
        var responseData = JSON.stringify(data.responseJSON);
        localStorage.setItem(url, responseData);
        if ($.isFunction(success)) success(responseJSON); //call back to original ajax call
    };
}
});

If you want to remove localStorage, use following statement wherever you want:

localStorage.removeItem("Info");

Hope it helps others!

find all the name using mysql query which start with the letter 'a'

You can use like 'A%' expression, but if you want this query to run fast for large tables I'd recommend you to put number of first button into separate field with tiny int type.

How do I download and save a file locally on iOS using objective C?

NSURLSession introduced in iOS 7, is the recommended SDK way of downloading a file. No need to import 3rd party libraries.

NSURL *url = [NSURL URLWithString:@"http://www.something.com/file"];
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
self.downloadTask = [self.urlSession downloadTaskWithRequest:downloadRequest];
[self.downloadTask resume];

You can then use the NSURLSessionDownloadDelegate delegate methods to monitor errors, download completion, download progress etc... There are inline block completion handler callback methods too if you prefer. Apples docs explain when you need to use one over the other.

Have a read of these articles:

objc.io NSURLConnection to NSURLSession

URL Loading System Programming Guide

How to delete the top 1000 rows from a table using Sql Server 2008?

I agree with the Hamed elahi and Glorfindel.

My suggestion to add is you can delete and update using aliases

/* 
  given a table bi_customer_actions
  with a field bca_delete_flag of tinyint or bit
    and a field bca_add_date of datetime

  note: the *if 1=1* structure allows me to fold them and turn them on and off
 */
declare
        @Nrows int = 1000

if 1=1 /* testing the inner select */
begin
  select top (@Nrows) * 
    from bi_customer_actions
    where bca_delete_flag = 1
    order by bca_add_date
end

if 1=1 /* delete or update or select */
begin
  --select bca.*
  --update bca  set bca_delete_flag = 0
  delete bca
    from (
      select top (@Nrows) * 
        from bi_customer_actions
        where bca_delete_flag = 1
        order by bca_add_date
    ) as bca
end 

c# .net change label text

If I understand correctly you may be experiencing the problem because in order to be able to set the labels "text" property you actually have to use the "content" property.

so instead of:

  Label output = null;
        output = Label1;
        output.Text = "hello";

try:

Label output = null;
            output = Label1;
            output.Content = "hello";

How can I configure my makefile for debug and release builds?

Completing the answers from earlier... You need to reference the variables you define info in your commands...

DEBUG ?= 1
ifeq (DEBUG, 1)
    CFLAGS =-g3 -gdwarf2 -DDEBUG
else
    CFLAGS=-DNDEBUG
endif

CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)

all: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

CommandParser.tab.o: CommandParser.y
    bison -d CommandParser.y
    $(CXX) -c CommandParser.tab.c

Command.o: Command.cpp
    $(CXX) -c Command.cpp

clean:
    rm -f CommandParser.tab.* CommandParser.yy.* output *.o

if else statement in AngularJS templates

Angularjs (versions below 1.1.5) does not provide the if/else functionality . Following are a few options to consider for what you want to achieve:

(Jump to the update below (#5) if you are using version 1.1.5 or greater)

1. Ternary operator:

As suggested by @Kirk in the comments, the cleanest way of doing this would be to use a ternary operator as follows:

<span>{{isLarge ? 'video.large' : 'video.small'}}</span>

2. ng-switch directive:

can be used something like the following.

<div ng-switch on="video">
    <div ng-switch-when="video.large">
        <!-- code to render a large video block-->
    </div>
    <div ng-switch-default>
        <!-- code to render the regular video block -->
    </div>
</div>

3. ng-hide / ng-show directives

Alternatively, you might also use ng-show/ng-hide but using this will actually render both a large video and a small video element and then hide the one that meets the ng-hide condition and shows the one that meets ng-show condition. So on each page you'll actually be rendering two different elements.

4. Another option to consider is ng-class directive.

This can be used as follows.

<div ng-class="{large-video: video.large}">
    <!-- video block goes here -->
</div>

The above basically will add a large-video css class to the div element if video.large is truthy.

UPDATE: Angular 1.1.5 introduced the ngIf directive

5. ng-if directive:

In the versions above 1.1.5 you can use the ng-if directive. This would remove the element if the expression provided returns false and re-inserts the element in the DOM if the expression returns true. Can be used as follows.

<div ng-if="video == video.large">
    <!-- code to render a large video block-->
</div>
<div ng-if="video != video.large">
    <!-- code to render the regular video block -->
</div>

How do I set default terminal to terminator?

Copy-paste the following into your current terminal:

gsettings set org.gnome.desktop.default-applications.terminal exec /usr/bin/terminator
gsettings set org.gnome.desktop.default-applications.terminal exec-arg "-x"

This modifies the dconf to make terminator the default program. You could also use dconf-editor (a GUI-based tool) to make changes to the dconf, as another answer has suggested. If you would like to learn and understand more about this topic, this may help you.

How to edit .csproj file

You can right click the project file, select "Unload project" then you can open the file directly for editing by selecting "Edit project name.csproj".

You will have to load the project back after you have saved your changes in order for it to compile.

See How to: Unload and Reload Projects on MSDN.


Since project files are XML files, you can also simply edit them using any text editor that supports Unicode (notepad, notepad++ etc...)

However, I would be very reluctant to edit these files by hand - use the Solution explorer for this if at all possible. If you have errors and you know how to fix them manually, go ahead, but be aware that you can completely ruin the project file if you don't know exactly what you are doing.

Generate war file from tomcat webapp folder

Its just like creating a WAR file of your project, you can do it in several ways (from Eclipse, command line, maven).

If you want to do from command line, the command is

jar -cvf my_web_app.war * 

Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)

CSS word-wrapping in div

It's pretty hard to say definitively without seeing what the rendered html looks like and what styles are being applied to the elements within the treeview div, but the thing that jumps out at me right away is the

overflow-x: scroll;

What happens if you remove that?

What is the best Java email address validation method?

What do you want to validate? The email address?

The email address can only be checked for its format conformance. See the standard: RFC2822. Best way to do that is a regular expression. You will never know if really exists without sending an email.

I checked the commons validator. It contains an org.apache.commons.validator.EmailValidator class. Seems to be a good starting point.

Pass multiple parameters in Html.BeginForm MVC

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id)

or

 @using(Html.BeginForm("action", "controller",
                       new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)

Getting URL hash location, and using it in jQuery

I would suggest better cek first if the current page has a hash. Otherwise it will be undefined.

$(window).on('load', function(){        
    if( location.hash && location.hash.length ) {
       var hash = decodeURIComponent(location.hash.substr(1));
       $('ul'+hash+':first').show();;
    }       
});

MVC4 input field placeholder

 @Html.TextBoxFor(m => m.UserName, new { @class = "form-control",@placeholder = "Name"  })  

Rails select helper - Default selected value, how?

Rails 3.0.9

select options_for_select([value1, value2, value3], default)

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

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

 module.exports = {
     hbd: handlebar
 }

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

Parsing date string in Go

I will suggest using time.RFC3339 constant from time package. You can check other constants from time package. https://golang.org/pkg/time/#pkg-constants

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Time parsing");
    dateString := "2014-11-12T11:45:26.371Z"
    time1, err := time.Parse(time.RFC3339,dateString);
    if err!=nil {
    fmt.Println("Error while parsing date :", err);
    }
    fmt.Println(time1); 
}

Maximum number of threads per process in Linux?

proper 100k threads on linux:

ulimit -s  256
ulimit -i  120000
echo 120000 > /proc/sys/kernel/threads-max
echo 600000 > /proc/sys/vm/max_map_count
echo 200000 > /proc/sys/kernel/pid_max 

 ./100k-pthread-create-app

2018 update from @Thomas, on systemd systems:

/etc/systemd/logind.conf: UserTasksMax=100000

WSDL vs REST Pros and Cons

In defence of REST it closely follows the principles of HTTP and addressability e.g. read operations use GET, update operations use POST etc. I find this to be a far cleaner approach. The Oreilly book RESTful Web Services explains this far better than I can, if you read it I think you would prefer the REST approach

How to automatically indent source code?

In Visual Studio 2010

Ctrl +k +d indent the complete page.

Ctrl +k +f indent the selected Code.

For more help visit : http://msdn.microsoft.com/en-us/library/da5kh0wa.aspx

every thing is there.

What is an Android PendingIntent?

A PendingIntent wraps the general Intent with a token that you give to foreign app to execute with your permission. For eg:

The notification of your music app can't play/pause the music if you didn't give the PendingIntent to send broadcast because your music app has READ_EXTERNAL_STORAGE permission which the notification app doesn't. Notification is a system service (so it's a foreign app).

Transparent background in JPEG image

JPG doesn't support transparency

View stored procedure/function definition in MySQL

You can use table proc in database mysql:

mysql> SELECT body FROM mysql.proc
WHERE db = 'yourdb' AND name = 'procedurename' ;

Note that you must have a grant for select to mysql.proc:

mysql> GRANT SELECT ON mysql.proc TO 'youruser'@'yourhost' IDENTIFIED BY 'yourpass' ;

What is the difference between dynamic programming and greedy approach?

the major difference between greedy method and dynamic programming is in greedy method only one optimal decision sequence is ever generated and in dynamic programming more than one optimal decision sequence may be generated.

Git credential helper - update password

None of these answers ended up working for my Git credential issue. Here is what did work if anyone needs it (I'm using Git 1.9 on Windows 8.1).

To update your credentials, go to Control PanelCredential ManagerGeneric Credentials. Find the credentials related to your Git account and edit them to use the updated password.

Reference: How to update your Git credentials on Windows

Note that to use the Windows Credential Manager for Git you need to configure the credential helper like so:

git config --global credential.helper wincred

If you have multiple GitHub accounts that you use for different repositories, then you should configure credentials to use the full repository path (rather than just the domain, which is the default):

git config --global credential.useHttpPath true

When should I use Memcache instead of Memcached?

This is 2013. Forget about the 2009 comments. Likewise, if you are running serious traffic loads, do not even contemplate how to make-do with a windows based memcache. When dealing with a very large scale (500+ front end web servers) and 20+ back end database servers and replicants (mysql & mssql mix), a farm of memcached servers (12 servers in group) supports multiple high volume OLTP applications answering 25K ~ 40K mc->get calls per-second. These calls are those that do NOT have to reach a database.

IMHO, this use of memcached provided SERIOUS $$$,$$$savings on CAPEX for new DB servers & licences as well as on support contracts for large commercial designs.

How to delete images from a private docker registry?

Simple ruby script based on this answer: registry_cleaner.

You can run it on local machine:

./registry_cleaner.rb --host=https://registry.exmpl.com --repository=name --tags_count=4

And then on the registry machine remove blobs with /bin/registry garbage-collect /etc/docker/registry/config.yml.

Html.BeginForm and adding properties

As part of htmlAttributes,e.g.

Html.BeginForm(
    action, controller, FormMethod.Post, new { enctype="multipart/form-data"})

Or you can pass null for action and controller to get the same default target as for BeginForm() without any parameters:

Html.BeginForm(
    null, null, FormMethod.Post, new { enctype="multipart/form-data"})

GridView - Show headers on empty data source

    <asp:GridView ID="gvEmployee" runat="server"    
                     AutoGenerateColumns="False" ShowHeaderWhenEmpty=”True”>  
                        <Columns>  
                            <asp:BoundField DataField="Id" HeaderText="Id" />  
                            <asp:BoundField DataField="Name" HeaderText="Name" />  
                            <asp:BoundField DataField="Designation" HeaderText="Designation" />  
                            <asp:BoundField DataField="Salary" HeaderText="Salary"  />  
                        </Columns>  
                        <EmptyDataTemplate>No Record Available</EmptyDataTemplate>  
                    </asp:GridView>  


    in CS Page

    gvEmployee.DataSource = dt;  
    gvEmployee.DataBind();  

Help.. see that link:
http://www.c-sharpcorner.com/UploadFile/d0e913/how-to-display-the-empty-gridview-in-case-of-no-records-in-d/

Where does Anaconda Python install on Windows?

If you installed as admin ( and meant for all users )

C:\ProgramData\Anaconda3\Scripts\anaconda.exe

If you install as a normal user

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe

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

Add { } while importing and exporting: export { ... }; | import { ... } from './Template';

exportimport { ... } from './Template'

export defaultimport ... from './Template'


Here is a working example:

// ExportExample.js
import React from "react";

function DefaultExport() {
  return "This is the default export";
}

function Export1() {
  return "Export without default 1";
}

function Export2() {
  return "Export without default 2";
}

export default DefaultExport;
export { Export1, Export2 };

// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";

export default function App() {
  return (
    <>
      <strong>
        <DefaultExport />
      </strong>
      <br />
      <Export1 />
      <br />
      <Export2 />
    </>
  );
}

??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

If the error is

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

Step1: stop the server

Step2: run commands are npm uninstall node-sass

Step3: check node-sass in package.json if node-sass is available in the file then again run Step2.

Step4: npm install [email protected] <=== run command

Step5: wait until the command successfully runs.

Step6: start-server using npm start

How to get the focused element with jQuery?

$(':focus')[0] will give you the actual element.

$(':focus') will give you an array of elements, usually only one element is focused at a time so this is only better if you somehow have multiple elements focused.

Check if a value is an object in JavaScript

I have a code snippet that works. I find it confusing when the whole piece of code is not given, so I just created it myself:

    <!DOCTYPE html>
    <html>
    <body>
    <button onclick="myFunc()">Try it</button>

    <script>
    var abc = new Number();
    // var abc = 4;
    //this is a code variation which will give a diff alert

    function myFunc()
    {
    if(abc && typeof abc === "object")
    alert('abc is an object and does not return null value');
    else
    alert('abc is not an object');
    }
    </script>

    </body>
    </html>

Define global constants

The best way to create application wide constants in Angular 2 is by using environment.ts files. The advantage of declaring such constants is that you can vary them according to the environment as there can be a different environment file for each environment.

How can I specify a [DllImport] path at runtime?

If you need a .dll file that is not on the path or on the application's location, then I don't think you can do just that, because DllImport is an attribute, and attributes are only metadata that is set on types, members and other language elements.

An alternative that can help you accomplish what I think you're trying, is to use the native LoadLibrary through P/Invoke, in order to load a .dll from the path you need, and then use GetProcAddress to get a reference to the function you need from that .dll. Then use these to create a delegate that you can invoke.

To make it easier to use, you can then set this delegate to a field in your class, so that using it looks like calling a member method.

EDIT

Here is a code snippet that works, and shows what I meant.

class Program
{
    static void Main(string[] args)
    {
        var a = new MyClass();
        var result = a.ShowMessage();
    }
}

class FunctionLoader
{
    [DllImport("Kernel32.dll")]
    private static extern IntPtr LoadLibrary(string path);

    [DllImport("Kernel32.dll")]
    private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    public static Delegate LoadFunction<T>(string dllPath, string functionName)
    {
        var hModule = LoadLibrary(dllPath);
        var functionAddress = GetProcAddress(hModule, functionName);
        return Marshal.GetDelegateForFunctionPointer(functionAddress, typeof (T));
    }
}

public class MyClass
{
    static MyClass()
    {
        // Load functions and set them up as delegates
        // This is just an example - you could load the .dll from any path,
        // and you could even determine the file location at runtime.
        MessageBox = (MessageBoxDelegate) 
            FunctionLoader.LoadFunction<MessageBoxDelegate>(
                @"c:\windows\system32\user32.dll", "MessageBoxA");
    }

    private delegate int MessageBoxDelegate(
        IntPtr hwnd, string title, string message, int buttons); 

    /// <summary>
    /// This is the dynamic P/Invoke alternative
    /// </summary>
    static private MessageBoxDelegate MessageBox;

    /// <summary>
    /// Example for a method that uses the "dynamic P/Invoke"
    /// </summary>
    public int ShowMessage()
    {
        // 3 means "yes/no/cancel" buttons, just to show that it works...
        return MessageBox(IntPtr.Zero, "Hello world", "Loaded dynamically", 3);
    }
}

Note: I did not bother to use FreeLibrary, so this code is not complete. In a real application, you should take care to release the loaded modules to avoid a memory leak.

grep exclude multiple strings

Two examples of filtering out multiple lines with grep:

Put this in filename.txt:

abc
def
ghi
jkl

grep command using -E option with a pipe between tokens in a string:

grep -Ev 'def|jkl' filename.txt

prints:

abc
ghi

Command using -v option with pipe between tokens surrounded by parens:

egrep -v '(def|jkl)' filename.txt

prints:

abc
ghi

Getting an odd error, SQL Server query using `WITH` clause

always use with statement like ;WITH then you'll never get this error. The WITH command required a ; between it and any previous command, by always using ;WITH you'll never have to remember to do this.

see WITH common_table_expression (Transact-SQL), from the section Guidelines for Creating and Using Common Table Expressions:

When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon.

how to insert datetime into the SQL Database table?

You will need to have a datetime column in a table. Then you can do an insert like the following to insert the current date:

INSERT INTO MyTable (MyDate) Values (GetDate())

If it is not today's date then you should be able to use a string and specify the date format:

INSERT INTO MyTable (MyDate) Values (Convert(DateTime,'19820626',112)) --6/26/1982

You do not always need to convert the string either, often you can just do something like:

INSERT INTO MyTable (MyDate) Values ('06/26/1982') 

And SQL Server will figure it out for you.

start MySQL server from command line on Mac OS Lion

On mac Big Sur and MySQL 5.7, I needed to stop/start with:

sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

and

sudo launchctl unload -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

This answer came from https://coolestguidesontheplanet.com/start-stop-mysql-from-the-command-line-terminal-osx-linux/

How can I detect the encoding/codepage of a text file

Thanks @Erik Aronesty for mentioning uchardet.

Meanwhile the (same?) tool exists for linux: chardet.
Or, on cygwin you may want to use: chardetect.

See: chardet man page: https://www.commandlinux.com/man-page/man1/chardetect.1.html

This will heuristically detect (guess) the character encoding for each given file and will report the name and confidence level for each file's detected character encoding.

Add element to a JSON file?

One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:

test_json = { "a": 1, "b": 2}

Once you do this, adding a json element only involves the following line:

test_json["c"] = 3

This will result in:

{'a': 1, 'b': 2, 'c': 3}

Afterwards, you can add that json back into an array or a list of that is desired.

Change image onmouseover

Thy to put a dot or two before the /

('src','./ico/view.hover.png')"

'profile name is not valid' error when executing the sp_send_dbmail command

You need to grant the user or group rights to use the profile. They need to be added to the msdb database and then you will see them available in the mail wizard when you are maintaining security for mail.

Read up the security here: http://msdn.microsoft.com/en-us/library/ms175887.aspx

See a listing of mail procedures here: http://msdn.microsoft.com/en-us/library/ms177580.aspx

Example script for 'TestUser' to use the profile named 'General Admin Mail'.


USE [msdb]
GO
CREATE USER [TestUser] FOR LOGIN [testuser]
GO
USE [msdb]
GO
EXEC sp_addrolemember N'DatabaseMailUserRole', N'TestUser'
GO

EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
    @profile_name = 'General Admin Mail',
    @principal_name = 'TestUser',
    @is_default = 1 ;

What value could I insert into a bit type column?

If you're using SQL Server, you can set the value of bit fields with 0 and 1

or

'true' and 'false' (yes, using strings)

...your_bit_field='false'... => equivalent to 0

How to get height and width of device display in angular2 using typescript?

You may use the typescript getter method for this scenario. Like this

public get height() {
  return window.innerHeight;
}

public get width() {
  return window.innerWidth;
}

And use that in template like this:

<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768 
}"></section>

Print the value

console.log(this.height, this.width);

You won't need any event handler to check for resizing of window, this method will check for size every time automatically.

/usr/bin/codesign failed with exit code 1

Open the project path in terminal and enter the below commands in terminal

1) find . | xargs -0 xattr -c

2) xattr -rc .

This works for me.

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two reasons for this error

1) In the array of import if you imported HttpModule twice

enter image description here

2) If you haven't import:

import { HttpModule, JsonpModule } from '@angular/http'; 

If you want then run:

npm install @angular/http

Running shell command and capturing the output

Splitting the initial command for the subprocess might be tricky and cumbersome.

Use shlex.split() to help yourself out.

Sample command

git log -n 5 --since "5 years ago" --until "2 year ago"

The code

from subprocess import check_output
from shlex import split

res = check_output(split('git log -n 5 --since "5 years ago" --until "2 year ago"'))
print(res)
>>> b'commit 7696ab087a163e084d6870bb4e5e4d4198bdc61a\nAuthor: Artur Barseghyan...'

Without shlex.split() the code would look as follows

res = check_output([
    'git', 
    'log', 
    '-n', 
    '5', 
    '--since', 
    '5 years ago', 
    '--until', 
    '2 year ago'
])
print(res)
>>> b'commit 7696ab087a163e084d6870bb4e5e4d4198bdc61a\nAuthor: Artur Barseghyan...'

Simplest way to read json from a URL in java

It's very easy, using jersey-client, just include this maven dependency:

<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-client</artifactId>
  <version>2.25.1</version>
</dependency>

Then invoke it using this example:

String json = ClientBuilder.newClient().target("http://api.coindesk.com/v1/bpi/currentprice.json").request().accept(MediaType.APPLICATION_JSON).get(String.class);

Then use Google's Gson to parse the JSON:

Gson gson = new Gson();
Type gm = new TypeToken<CoinDeskMessage>() {}.getType();
CoinDeskMessage cdm = gson.fromJson(json, gm);

Can functions be passed as parameters?

You can pass function as parameter to a Go function. Here is an example of passing function as parameter to another Go function:

package main

import "fmt"

type fn func(int) 

func myfn1(i int) {
    fmt.Printf("\ni is %v", i)
}
func myfn2(i int) {
    fmt.Printf("\ni is %v", i)
}
func test(f fn, val int) {
    f(val)
}
func main() {
    test(myfn1, 123)
    test(myfn2, 321)
}

You can try this out at: https://play.golang.org/p/9mAOUWGp0k

Change windows hostname from command line

Use below command to change computer hostname remotely , Require system reboot after change..

psexec.exe -h -e \\\IPADDRESS -u USERNAME -p PASSWORD netdom renamecomputer CurrentComputerName /newname:NewComputerName /force

EF Core add-migration Build Failed

Try these steps:

  1. Clean the solution.

  2. Build every project separately.

  3. Resolve any errors if found (sometimes, VS is not showing errors until you build it separately).

  4. Then try to run migration again.

What's the scope of a variable initialized in an if statement?

Yes. It is also true for for scope. But not functions of course.

In your example: if the condition in the if statement is false, x will not be defined though.

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

FileNotFoundException while getting the InputStream object from HttpURLConnection

Please change

con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection();

To

con = (HttpURLConnection) new URL("http://YOUR_IP:8080/myapp/service/generate").openConnection();

Is there a difference between /\s/g and /\s+/g?

\s means "one space", and \s+ means "one or more spaces".

But, because you're using the /g flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect.

How to change the color of a CheckBox?

100% robust approach.

In my case, I didn't have access to the XML layout source file, since I get Checkbox from a 3-rd party MaterialDialog lib. So I have to solve this programmatically.

  1. Create a ColorStateList in xml:

res/color/checkbox_tinit_dark_theme.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/white"
        android:state_checked="false"/>
    <item android:color="@color/positiveButtonBg"
        android:state_checked="true"/>
</selector>
  1. Then apply it to the checkbox:

    ColorStateList darkStateList = ContextCompat.getColorStateList(getContext(), R.color.checkbox_tint_dark_theme);
    CompoundButtonCompat.setButtonTintList(checkbox, darkStateList);
    

P.S. In addition if someone is interested, here is how you can get your checkbox from MaterialDialog dialog (if you set it with .checkBoxPromptRes(...)):

CheckBox checkbox = (CheckBox) dialog.getView().findViewById(R.id.md_promptCheckbox);

Hope this helps.

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

If "0" then leave the cell blank

=iferror(1/ (1/ H15+G16-F16 ), "")

this way avoids repeating the central calculation (which can often be much longer or more processor hungry than the one you have here...

enjoy

Converting string format to datetime in mm/dd/yyyy

You need an uppercase M for the month part.

string strDate = DateTime.Now.ToString("MM/dd/yyyy");

Lowercase m is for outputting (and parsing) a minute (such as h:mm).

e.g. a full date time string might look like this:

string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");

Notice the uppercase/lowercase mM difference.


Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.

public static class DateTimeMyFormatExtensions
{
  public static string ToMyFormatString(this DateTime dt)
  {
    return dt.ToString("MM/dd/yyyy");
  }
}

public static class StringMyDateTimeFormatExtension
{
  public static DateTime ParseMyFormatDateTime(this string s)
  {
    var culture = System.Globalization.CultureInfo.CurrentCulture;
    return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
  }
}

EXAMPLE: Translating between DateTime/string

DateTime now = DateTime.Now;

string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();

Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.

System.Globalization.CultureInfo.CurrentCulture.

The only easy way you can do is to roll a custom extension method.

Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.

Maximum number of records in a MySQL database table

mysql int types can do quite a few rows: http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html

unsigned int largest value is 4,294,967,295
unsigned bigint largest value is 18,446,744,073,709,551,615

How to compare only date components from DateTime in EF?

//Note for Linq Users/Coders

This should give you the exact comparison for checking if a date falls within range when working with input from a user - date picker for example:

((DateTime)ri.RequestX.DateSatisfied).Date >= startdate.Date &&
        ((DateTime)ri.RequestX.DateSatisfied).Date <= enddate.Date

where startdate and enddate are values from a date picker.

nginx: [emerg] "server" directive is not allowed here

Example valid nginx.conf for reverse proxy; In case someone is stuck like me. where 10.x.x.x is the server where you are running the nginx proxy server and to which you are connecting to with the browser, and 10.y.y.y is where your real web server is running

events {
  worker_connections  4096;  ## Default: 1024
}
http {
 server {
   listen 80;
   listen [::]:80;

   server_name 10.x.x.x;
 
   location / {
       proxy_pass http://10.y.y.y:80/;
       proxy_set_header Host $host;
   }
 }
}

Here is the snippet if you want to do SSL pass through. That is if 10.y.y.y is running a HTTPS webserver. Here 10.x.x.x, or where the nignx runs is listening to port 443, and all traffic to 443 is directed to your target web server

events {
  worker_connections  4096;  ## Default: 1024
}

stream {
  server {
    listen     443;
    proxy_pass 10.y.y.y:443;
  }
}

and you can serve it up in docker too

 docker run --name nginx-container --rm --net=host   -v /home/core/nginx/nginx.conf:/etc/nginx/nginx.conf nginx

How can I add a column that doesn't allow nulls in a Postgresql database?

Specifying a default value would also work, assuming a default value is appropriate.

How can I determine installed SQL Server instances and their versions?

If your within SSMS you might find it easier to use:

SELECT @@Version

How to remove a Gitlab project?

As of October 2017:
1. In the list of your projects, click on the project you want to delete;
2. In the left sidebar, click on the 'Setting' button;
3. Locate the 'Advanced settings' section and click on the related 'Expand' button;
4. At the bottom you'll find the 'Remove Project' button, click it;
5. Type the name of the project inside the text input and Confirm.

Install a Windows service using a Windows command prompt?

Install Service:-

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe" 
"C:\Services\myservice.exe"

UnInstall Sevice:-

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe" -u "C:\Services\myservice.Service.exe"

Turn off textarea resizing

CSS3 can solve this problem. Unfortunately it's only supported on 60% of used browsers nowadays.

For IE and iOS you can't turn off resizing but you can limit the textarea dimension by setting its width and height.

/* One can also turn on/off specific axis. Defaults to both on. */
textarea { resize:vertical; } /* none|horizontal|vertical|both */

See Demo

Installing Oracle Instant Client

The directions state:

  1. Download the appropriate Instant Client packages for your platform. All installations REQUIRE the Basic package.
  2. Unzip the packages into a single directory such as "instantclient".
  3. Set the library loading path in your environment to the directory in Step 2 ("instantclient"). On many UNIX platforms, LD_LIBRARY_PATH is the appropriate environment variable. On Windows, PATH should be used.
  4. Start your application and enjoy.

Suggest extracting/unzipping into a new directory. They've suggested instantclient, but you can name the directory anything you like. Name it C:\OracleInstantClient\ if you choose.

Then in Step 3, open a Windows Command Prompt. Type:

PATH C:\OracleInstantClient; %PATH%`

That's all there is to it!

Server Discovery And Monitoring engine is deprecated

If your code includes createConnetion for some reason (In my case I'm using GridFsStorage), try adding the following to your code:

    options: {
        useUnifiedTopology: true,
    }

just after file, like this:

    const storage = new GridFsStorage({
    url: mongodbUrl,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
                if (err) {
                    return reject(err);
                }
                const filename = buf.toString('hex') + path.extname(file.originalname);
                const fileInfo = {
                    filename: filename,
                    bucketName: 'uploads'
                };
                resolve(fileInfo);
            });
        });
    },
    options: {
        useUnifiedTopology: true,
    }
})

If your case looks like mine, this will surely solve your issue. Regards

Transpose/Unzip Function (inverse of zip)?

If you have lists that are not the same length, you may not want to use zip as per Patricks answer. This works:

>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]

But with different length lists, zip truncates each item to the length of the shortest list:

>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])
[('a', 'b', 'c', 'd', 'e')]

You can use map with no function to fill empty results with None:

>>> map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])
[('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)]

zip() is marginally faster though.

How to create nonexistent subdirectories recursively using Bash?

You can use the -p parameter, which is documented as:

-p, --parents

no error if existing, make parent directories as needed

So:

mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

C - casting int to char and append char to char

int myInt = 65;

char myChar = (char)myInt;  // myChar should now be the letter A

char[20] myString = {0}; // make an empty string.

myString[0] = myChar;
myString[1] = myChar; // Now myString is "AA"

This should all be found in any intro to C book, or by some basic online searching.

Why does the JFrame setSize() method not set the size correctly?

I know that this question is about 6+ years old, but the answer by @Kyle doesn't work.

Using this

setSize(width - (getInsets().left + getInsets().right), height - (getInsets().top + getInsets().bottom));

But this always work in any size:

setSize(width + 14, height + 7);

If you don't want the border to border, and only want the white area, here:

setSize(width + 16, height + 39);

Also this only works on Windows 10, for MacOS users, use @ben's answer.

How to check cordova android version of a cordova/phonegap project?

Try

cordova platform version

It will give you the following output

Installed platforms: android 3.5.1, ios 3.5.0
Available platforms: amazon-fireos, blackberry10, browser, firefoxos

Also to know the version of cordodva cli try

cordova -v 

Start an activity from a fragment

You may have to replace getActivity() with MainActivity.this for those that are having issues with this.

Access XAMPP Localhost from Internet

I guess you can do this in 5 minute without any further IP/port forwarding, for presenting your local websites temporary.

All you need to do it, go to http://ngrok.com Download small tool extract and run that tool as administrator enter image description here

Enter command
ngrok http 80

You will see it will connect to server and will create a temporary URL for you which you can share to your friend and let him browse localhost or any of its folder.

You can see detailed process here.
How do I access/share xampp or localhost website from another computer

How to get the cell value by column name not by index in GridView in asp.net

It is possible to use the data field name, if not the title so easily, which solved the problem for me. For ASP.NET & VB:

e.g. For a string:

Dim Encoding = e.Row.DataItem("Encoding").ToString().Trim()

e.g. For an integer:

Dim MsgParts = Convert.ToInt32(e.Row.DataItem("CalculatedMessageParts").ToString())

Angular2 equivalent of $document.ready()

You can fire an event yourself in ngOnInit() of your Angular root component and then listen for this event outside of Angular.

This is Dart code (I don't know TypeScript) but should't be to hard to translate

@Component(selector: 'app-element')
@View(
    templateUrl: 'app_element.html',
)
class AppElement implements OnInit {
  ElementRef elementRef;
  AppElement(this.elementRef);

  void ngOnInit() {
    DOM.dispatchEvent(elementRef.nativeElement, new CustomEvent('angular-ready'));
  }
}

PHP mkdir: Permission denied problem

I know this is an old thread, but it needs a better answer. You shouldn't need to set the permissions to 777, that is a security problem as it gives read and write access to the world. It may be that your apache user does not have read/write permissions on the directory.

Here's what you do in Ubuntu

  1. Make sure all files are owned by the Apache group and user. In Ubuntu it is the www-data group and user

    chown -R www-data:www-data /path/to/webserver/www

  2. Next enabled all members of the www-data group to read and write files

    chmod -R g+rw /path/to/webserver/www

The php mkdir() function should now work without returning errors

Jenkins Host key verification failed

  • Make sure we are not editing any of the default sshd_config properties to skip the error

  • Host Verification Failed - Definitely a missing entry of hostname in known_hosts file

  • Login to the server where the process is failing and do the following:

    1. Sudo to the user running the process

    2. ssh-copy-id destinationuser@destinationhostname

    3. It will prompt like this for the first time, say yes and it will also ask password for the first time:

      The authenticity of host 'sample.org (205.214.640.91)' can't be established.
      RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
      Are you sure you want to continue connecting (yes/no)? *yes*
      

      Password prompt ? give password

    4. Now from the server where process is running, do ssh destinationuser@destinationhostname. It should login without a password.

      Note: Do not change the default permissions of files in the user's .ssh directory, you will end up with different issues

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The solution to change the encoding to Latin1 / ISO-8859-1 solves an issue I observed with html2text.py as invoked on an output of tex4ht. I use that for an automated word count on LaTeX documents: tex4ht converts them to HTML, and then html2text.py strips them down to pure text for further counting through wc -w. Now, if, for example, a German "Umlaut" comes in through a literature database entry, that process would fail as html2text.py would complain e.g.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 32243-32245: invalid data

Now these errors would then subsequently be particularly hard to track down, and essentially you want to have the Umlaut in your references section. A simple change inside html2text.py from

data = data.decode(encoding)

to

data = data.decode("ISO-8859-1")

solves that issue; if you're calling the script using the HTML file as first parameter, you can also pass the encoding as second parameter and spare the modification.

How do I find the MySQL my.cnf location

for me it was that i had "ENGINE=MyISAM" kind of tables , once i changed it to "ENGINE=InnoDB" it worked:) in PhpMyAdmin on Azure App Service :)

How to Clear Console in Java?

You need to instruct the console to clear.

For serial terminals this was typically done through so called "escape sequences", where notably the vt100 set has become very commonly supported (and its close ANSI-cousin).

Windows has traditionally not supported such sequences "out-of-the-box" but relied on API-calls to do these things. For DOS-based versions of Windows, however, the ANSI.SYS driver could be installed to provide such support.

So if you are under Windows, you need to interact with the appropriate Windows API. I do not believe the standard Java runtime library contains code to do so.