Programs & Examples On #Google nativeclient

Native Client (NaCl) and Portable Native Client (PNaCl) are open-source technologies for executing compiled code in a browser sandbox. PNaCl is portable and preferred but has a few limitations. Questions about the tool chain and SDK for Native Client as well as questions concerning behaviors of the resulting applications should use this tag. Questions involving HTML and JavaScript components used with Native Client may need those tags as well or instead.

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

Is there a way to create interfaces in ES6 / Node 4?

This is my solution for the problem. You can 'implement' multiple interfaces by overriding one Interface with another.

class MyInterface {
    // Declare your JS doc in the Interface to make it acceable while writing the Class and for later inheritance
    /**
     * Gives the sum of the given Numbers
     * @param {Number} a The first Number
     * @param {Number} b The second Number
     * @return {Number} The sum of the Numbers
     */
    sum(a, b) { this._WARNING('sum(a, b)'); }


    // delcare a warning generator to notice if a method of the interface is not overridden
    // Needs the function name of the Interface method or any String that gives you a hint ;)
    _WARNING(fName='unknown method') {
        console.warn('WARNING! Function "'+fName+'" is not overridden in '+this.constructor.name);
    }
}

class MultipleInterfaces extends MyInterface {
    // this is used for "implement" multiple Interfaces at once
    /**
     * Gives the square of the given Number
     * @param {Number} a The Number
     * @return {Number} The square of the Numbers
     */
    square(a) { this._WARNING('square(a)'); }
}

class MyCorrectUsedClass extends MyInterface {
    // You can easy use the JS doc declared in the interface
    /** @inheritdoc */
    sum(a, b) {
        return a+b;
    }
}
class MyIncorrectUsedClass extends MyInterface {
    // not overriding the method sum(a, b)
}

class MyMultipleInterfacesClass extends MultipleInterfaces {
    // nothing overriden to show, that it still works
}


let working = new MyCorrectUsedClass();

let notWorking = new MyIncorrectUsedClass();

let multipleInterfacesInstance = new MyMultipleInterfacesClass();

// TEST IT

console.log('working.sum(1, 2) =', working.sum(1, 2));
// output: 'working.sum(1, 2) = 3'

console.log('notWorking.sum(1, 2) =', notWorking.sum(1, 2));
// output: 'notWorking.sum(1, 2) = undefined'
// but also sends a warn to the console with 'WARNING! Function "sum(a, b)" is not overridden in MyIncorrectUsedClass'

console.log('multipleInterfacesInstance.sum(1, 2) =', multipleInterfacesInstance.sum(1, 2));
// output: 'multipleInterfacesInstance.sum(1, 2) = undefined'
// console warn: 'WARNING! Function "sum(a, b)" is not overridden in MyMultipleInterfacesClass'

console.log('multipleInterfacesInstance.square(2) =', multipleInterfacesInstance.square(2));
// output: 'multipleInterfacesInstance.square(2) = undefined'
// console warn: 'WARNING! Function "square(a)" is not overridden in MyMultipleInterfacesClass'

EDIT:

I improved the code so you now can simply use implement(baseClass, interface1, interface2, ...) in the extend.

/**
* Implements any number of interfaces to a given class.
* @param cls The class you want to use
* @param interfaces Any amount of interfaces separated by comma
* @return The class cls exteded with all methods of all implemented interfaces
*/
function implement(cls, ...interfaces) {
    let clsPrototype = Object.getPrototypeOf(cls).prototype;
    for (let i = 0; i < interfaces.length; i++) {
        let proto = interfaces[i].prototype;
        for (let methodName of Object.getOwnPropertyNames(proto)) {
            if (methodName!== 'constructor')
                if (typeof proto[methodName] === 'function')
                    if (!clsPrototype[methodName]) {
                        console.warn('WARNING! "'+methodName+'" of Interface "'+interfaces[i].name+'" is not declared in class "'+cls.name+'"');
                        clsPrototype[methodName] = proto[methodName];
                    }
        }
    }
    return cls;
}

// Basic Interface to warn, whenever an not overridden method is used
class MyBaseInterface {
    // declare a warning generator to notice if a method of the interface is not overridden
    // Needs the function name of the Interface method or any String that gives you a hint ;)
    _WARNING(fName='unknown method') {
        console.warn('WARNING! Function "'+fName+'" is not overridden in '+this.constructor.name);
    }
}


// create a custom class
/* This is the simplest example but you could also use
*
*   class MyCustomClass1 extends implement(MyBaseInterface) {
*       foo() {return 66;}
*   }
*
*/
class MyCustomClass1 extends MyBaseInterface {
    foo() {return 66;}
}

// create a custom interface
class MyCustomInterface1 {
     // Declare your JS doc in the Interface to make it acceable while writing the Class and for later inheritance

    /**
     * Gives the sum of the given Numbers
     * @param {Number} a The first Number
     * @param {Number} b The second Number
     * @return {Number} The sum of the Numbers
     */
    sum(a, b) { this._WARNING('sum(a, b)'); }
}

// and another custom interface
class MyCustomInterface2 {
    /**
     * Gives the square of the given Number
     * @param {Number} a The Number
     * @return {Number} The square of the Numbers
     */
    square(a) { this._WARNING('square(a)'); }
}

// Extend your custom class even more and implement the custom interfaces
class AllInterfacesImplemented extends implement(MyCustomClass1, MyCustomInterface1, MyCustomInterface2) {
    /**
    * @inheritdoc
    */
    sum(a, b) { return a+b; }

    /**
    * Multiplies two Numbers
    * @param {Number} a The first Number
    * @param {Number} b The second Number
    * @return {Number}
    */
    multiply(a, b) {return a*b;}
}


// TEST IT

let x = new AllInterfacesImplemented();

console.log("x.foo() =", x.foo());
//output: 'x.foo() = 66'

console.log("x.square(2) =", x.square(2));
// output: 'x.square(2) = undefined
// console warn: 'WARNING! Function "square(a)" is not overridden in AllInterfacesImplemented'

console.log("x.sum(1, 2) =", x.sum(1, 2));
// output: 'x.sum(1, 2) = 3'

console.log("x.multiply(4, 5) =", x.multiply(4, 5));
// output: 'x.multiply(4, 5) = 20'

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

How do I kill the process currently using a port on localhost in Windows?

In case you want to do it using Python: check Is it possible in python to kill process that is listening on specific port, for example 8080?

The answer from Smunk works nicely. I repeat his code here:

from psutil import process_iter
from signal import SIGTERM # or SIGKILL

for proc in process_iter():
    for conns in proc.connections(kind='inet'):
        if conns.laddr.port == 8080:
            proc.send_signal(SIGTERM) # or SIGKILL
            continue

Creating an array from a text file in Bash

mapfile and readarray (which are synonymous) are available in Bash version 4 and above. If you have an older version of Bash, you can use a loop to read the file into an array:

arr=()
while IFS= read -r line; do
  arr+=("$line")
done < file

In case the file has an incomplete (missing newline) last line, you could use this alternative:

arr=()
while IFS= read -r line || [[ "$line" ]]; do
  arr+=("$line")
done < file

Related:

iPhone UILabel text soft shadow

Subclass UILabel, and override -drawInRect:

How can I convert JSON to CSV?

I might be late to the party, but I think, I have dealt with the similar problem. I had a json file which looked like this

JSON File Structure

I only wanted to extract few keys/values from these json file. So, I wrote the following code to extract the same.

    """json_to_csv.py
    This script reads n numbers of json files present in a folder and then extract certain data from each file and write in a csv file.
    The folder contains the python script i.e. json_to_csv.py, output.csv and another folder descriptions containing all the json files.
"""

import os
import json
import csv


def get_list_of_json_files():
    """Returns the list of filenames of all the Json files present in the folder
    Parameter
    ---------
    directory : str
        'descriptions' in this case
    Returns
    -------
    list_of_files: list
        List of the filenames of all the json files
    """

    list_of_files = os.listdir('descriptions')  # creates list of all the files in the folder

    return list_of_files


def create_list_from_json(jsonfile):
    """Returns a list of the extracted items from json file in the same order we need it.
    Parameter
    _________
    jsonfile : json
        The json file containing the data
    Returns
    -------
    one_sample_list : list
        The list of the extracted items needed for the final csv
    """

    with open(jsonfile) as f:
        data = json.load(f)

    data_list = []  # create an empty list

    # append the items to the list in the same order.
    data_list.append(data['_id'])
    data_list.append(data['_modelType'])
    data_list.append(data['creator']['_id'])
    data_list.append(data['creator']['name'])
    data_list.append(data['dataset']['_accessLevel'])
    data_list.append(data['dataset']['_id'])
    data_list.append(data['dataset']['description'])
    data_list.append(data['dataset']['name'])
    data_list.append(data['meta']['acquisition']['image_type'])
    data_list.append(data['meta']['acquisition']['pixelsX'])
    data_list.append(data['meta']['acquisition']['pixelsY'])
    data_list.append(data['meta']['clinical']['age_approx'])
    data_list.append(data['meta']['clinical']['benign_malignant'])
    data_list.append(data['meta']['clinical']['diagnosis'])
    data_list.append(data['meta']['clinical']['diagnosis_confirm_type'])
    data_list.append(data['meta']['clinical']['melanocytic'])
    data_list.append(data['meta']['clinical']['sex'])
    data_list.append(data['meta']['unstructured']['diagnosis'])
    # In few json files, the race was not there so using KeyError exception to add '' at the place
    try:
        data_list.append(data['meta']['unstructured']['race'])
    except KeyError:
        data_list.append("")  # will add an empty string in case race is not there.
    data_list.append(data['name'])

    return data_list


def write_csv():
    """Creates the desired csv file
    Parameters
    __________
    list_of_files : file
        The list created by get_list_of_json_files() method
    result.csv : csv
        The csv file containing the header only
    Returns
    _______
    result.csv : csv
        The desired csv file
    """

    list_of_files = get_list_of_json_files()
    for file in list_of_files:
        row = create_list_from_json(f'descriptions/{file}')  # create the row to be added to csv for each file (json-file)
        with open('output.csv', 'a') as c:
            writer = csv.writer(c)
            writer.writerow(row)
        c.close()


if __name__ == '__main__':
    write_csv()

I hope this will help. For details on how this code work you can check here

HTTP Status 404 - The requested resource (/) is not available

I had the same problem with my localhost project using Eclipse Luna, Maven and Tomcat - the Tomcat homepage would appear fine, however my project would get the 404 error.

After trying many suggested solutions (updating spring .jar file, changing properties of the Tomcat server, add/remove project, change JRE from 1.6 to 7 etc) which did not fix the issue, what worked for me was to just Refresh my project. It seems Eclipse does not automatically refresh the project after a (Maven) build. In Eclipse 3.3.1 there was a 'Refresh Automatically' option under Preferences > General > Workspace however that option doesn't look to be in Luna.

  1. Maven clean-install on the project.
  2. ** Right-click the project and select 'Refresh'. **
  3. Right-click the Eclipse Tomcat server and select 'Clean'.
  4. Right-click > Publish and then start the Tomcat server.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Another reason of the above error is corrupted jar file. I got the same error but for Junit when running unit tests. Removing jar and downloading it again fixed the issue.

Asynchronous Process inside a javascript for loop

JavaScript code runs on a single thread, so you cannot principally block to wait for the first loop iteration to complete before beginning the next without seriously impacting page usability.

The solution depends on what you really need. If the example is close to exactly what you need, @Simon's suggestion to pass i to your async process is a good one.

ParseError: not well-formed (invalid token) using cElementTree

It seems to complain about \x08 you will need to escape that.

Edit:

Or you can have the parser ignore the errors using recover

from lxml import etree
parser = etree.XMLParser(recover=True)
etree.fromstring(xmlstring, parser=parser)

Getting all selected checkboxes in an array

Pure JavaScript with no need for temporary variables:

Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked")).map(e => e.value)

How to convert string to boolean php

I do it in a way that will cast any case insensitive version of the string "false" to the boolean FALSE, but will behave using the normal php casting rules for all other strings. I think this is the best way to prevent unexpected behavior.

$test_var = 'False';
$test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
$result = (boolean) $test_var;

Or as a function:

function safeBool($test_var){
    $test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
    return (boolean) $test_var;
}

Print all but the first three columns

The correct way to do this is with an RE interval because it lets you simply state how many fields to skip, and retains inter-field spacing for the remaining fields.

e.g. to skip the first 3 fields without affecting spacing between remaining fields given the format of input we seem to be discussing in this question is simply:

$ echo '1   2 3 4   5    6' |
awk '{sub(/([^ ]+ +){3}/,"")}1'
4   5    6

If you want to accommodate leading spaces and non-blank spaces, but again with the default FS, then it's:

$ echo '  1   2 3 4   5    6' |
awk '{sub(/[[:space:]]*([^[:space:]]+[[:space:]]+){3}/,"")}1'
4   5    6

If you have an FS that's an RE you can't negate in a character set, you can convert it to a single char first (RS is ideal if it's a single char since an RS CANNOT appear within a field, otherwise consider SUBSEP), then apply the RE interval subsitution, then convert to the OFS. e.g. if chains of "."s separated the fields:

$ echo '1...2.3.4...5....6' |
awk -F'[.]+' '{gsub(FS,RS);sub("([^"RS"]+["RS"]+){3}","");gsub(RS,OFS)}1'
4 5 6

Obviously if OFS is a single char AND it can't appear in the input fields you can reduce that to:

$ echo '1...2.3.4...5....6' |
awk -F'[.]+' '{gsub(FS,OFS); sub("([^"OFS"]+["OFS"]+){3}","")}1'
4 5 6

Then you have the same issue as with all the loop-based solutions that reassign the fields - the FSs are converted to OFSs. If that's an issue, you need to look into GNU awks' patsplit() function.

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

You're trying to access a JSON, not JSONP.

Notice the difference between your source:

https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?

And actual JSONP (a wrapping function):

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json

Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

We have now posted an official response to the bug opened on Connect. The workarounds we recommend are as follows:

This error is due to Entity Framework creating an implicit transaction during the SaveChanges() call. The best way to work around the error is to use a different pattern (i.e., not saving while in the midst of reading) or by explicitly declaring a transaction. Here are three possible solutions:

// 1: Save after iteration (recommended approach in most cases)
using (var context = new MyContext())
{
    foreach (var person in context.People)
    {
        // Change to person
    }
    context.SaveChanges();
}

// 2: Declare an explicit transaction
using (var transaction = new TransactionScope())
{
    using (var context = new MyContext())
    {
        foreach (var person in context.People)
        {
            // Change to person
            context.SaveChanges();
        }
    }
    transaction.Complete();
}

// 3: Read rows ahead (Dangerous!)
using (var context = new MyContext())
{
    var people = context.People.ToList(); // Note that this forces the database
                                          // to evaluate the query immediately
                                          // and could be very bad for large tables.

    foreach (var person in people)
    {
        // Change to person
        context.SaveChanges();
    }
} 

Android Studio Stuck at Gradle Download on create new project

It is not stuck, it will take some time normally 5-7 mins , it also depends upon internet connection, so wait for some time. It will take time only for first launch.

Update: Check the latest log file in your C:\Users\<User>\.gradle\daemon\x.y folder to see what it's downloading.

How to find the php.ini file used by the command line?

From what I remember when I used to use EasyPHP, the php.ini file is either in C:\Windows\ or C:\Windows\System32

How to fix: Error device not found with ADB.exe

Try changing USB port. Try restarting adb server.

CSS Disabled scrolling

overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.

overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.

overflow: hidden;
would remove both scrollbars

JPA Query.getResultList() - use in a generic way

Here is the sample on what worked for me. I think that put method is needed in entity class to map sql columns to java class attributes.

    //simpleExample
    Query query = em.createNativeQuery(
"SELECT u.name,s.something FROM user u,  someTable s WHERE s.user_id = u.id", 
NameSomething.class);
    List list = (List<NameSomething.class>) query.getResultList();

Entity class:

    @Entity
    public class NameSomething {

        @Id
        private String name;

        private String something;

        // getters/setters



        /**
         * Generic put method to map JPA native Query to this object.
         *
         * @param column
         * @param value
         */
        public void put(Object column, Object value) {
            if (((String) column).equals("name")) {
                setName(String) value);
            } else if (((String) column).equals("something")) {
                setSomething((String) value);
            }
        }
    }

Changing the default icon in a Windows Forms application

The Icon displayed in the Taskbar and Windowtitle is that of the main Form. By changing its Icon you also set the Icon shown in the Taskbar, when already included in your *.resx:

System.ComponentModel.ComponentResourceManager resources = 
    new System.ComponentModel.ComponentResourceManager(typeof(MyForm));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("statusnormal.Icon")));

or, by directly reading from your Resources:

this.Icon = new Icon("Resources/statusnormal.ico");

If you cannot immediately find the code of the Form, search your whole project (CTRL+SHIFT+F) for the shown Window-Title (presuming that the text is static)

How to refresh app upon shaking the device?

You should subscribe as a SensorEventListener, and get the accelerometer data. Once you have it, you should monitor for sudden change in direction (sign) of acceleration on a certain axis. It would be a good indication for the 'shake' movement of device.

Markdown `native` text alignment

The div element has its own alignment attribute, align.

<div align="center">
  my text here.
</div>

What do I use on linux to make a python program executable

You can use PyInstaller. It generates a build dist so you can execute it as a single "binary" file.

http://pythonhosted.org/PyInstaller/#using-pyinstaller

Python 3 has the native option of create a build dist also:

https://docs.python.org/3/distutils/builtdist.html

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

IntelliJ IDEA vs WebStorm features

IntelliJ IDEA remains JetBrains' flagship product and IntelliJ IDEA provides full JavaScript support along with all other features of WebStorm via bundled or downloadable plugins. The only thing missing is the simplified project setup.

Taken from : https://confluence.jetbrains.com/display/WI/WebStorm+FAQ#WebStormFAQ-IntelliJIDEAvsWebStormfeatures

How to interpolate variables in strings in JavaScript, without concatenation?

You can use this javascript function to do this sort of templating. No need to include an entire library.

function createStringFromTemplate(template, variables) {
    return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
        return variables[varName];
    });
}

createStringFromTemplate(
    "I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
    {
        list_name : "this store",
        var1      : "FOO",
        var2      : "BAR",
        var3      : "BAZ"
    }
);

Output: "I would like to receive email updates from this store FOO BAR BAZ."

Using a function as an argument to the String.replace() function was part of the ECMAScript v3 spec. See this SO answer for more details.

How to declare a global variable in php?

You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.

Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.

How to extract numbers from a string in Python?

This is more than a bit late, but you can extend the regex expression to account for scientific notation too.

import re

# Format is [(<string>, <expected output>), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
       ['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
      ('hello X42 I\'m a Y-32.35 string Z30',
       ['42', '-32.35', '30']),
      ('he33llo 42 I\'m a 32 string -30', 
       ['33', '42', '32', '-30']),
      ('h3110 23 cat 444.4 rabbit 11 2 dog', 
       ['3110', '23', '444.4', '11', '2']),
      ('hello 12 hi 89', 
       ['12', '89']),
      ('4', 
       ['4']),
      ('I like 74,600 commas not,500', 
       ['74,600', '500']),
      ('I like bad math 1+2=.001', 
       ['1', '+2', '.001'])]

for s, r in ss:
    rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
    if rr == r:
        print('GOOD')
    else:
        print('WRONG', rr, 'should be', r)

Gives all good!

Additionally, you can look at the AWS Glue built-in regex

Android: How to get a custom View's height and width?

Just got a solution to get height and width of a custom view:

@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
    super.onSizeChanged(xNew, yNew, xOld, yOld);

    viewWidth = xNew;
    viewHeight = yNew;
}

Its working in my case.

Using Tkinter in python to edit the title bar

Having just done this myself you can do it this way:

from tkinter import Tk, Button, Frame, Entry, END

class ABC(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.parent = parent
        self.pack()
        ABC.make_widgets(self)

    def make_widgets(self):
        self.parent.title("Simple Prog")

You will see the title change, and you won't get two windows. I've left my parent as master as in the Tkinter reference stuff in the python library documentation.

How to center text vertically with a large font-awesome icon?

I just had to do this myself, you need to do it the other way around.

  • do not play with the vertical-align of your text
  • play with the vertical align of the font-awesome icon
<div>
  <span class="icon icon-2x icon-camera" style=" vertical-align: middle;"></span>
  <span class="my-text">hello world</span>
</div>

Of course you could not use inline styles and target it with your own css class. But this works in a copy paste fashion.

See here: Vertical alignment of text and icon in button

If it were up to me however, I would not use the icon-2x. And simply specify the font-size myself, as in the following

<div class='my-fancy-container'>
    <span class='my-icon icon-file-text'></span>
    <span class='my-text'>Hello World</span>
</div>
.my-icon {
    vertical-align: middle;
    font-size: 40px;
}

.my-text {
    font-family: "Courier-new";
}

.my-fancy-container {
    border: 1px solid #ccc;
    border-radius: 6px;
    display: inline-block;
    margin: 60px;
    padding: 10px;
}

for a working example, please see JsFiddle

Python Function to test ping

Here is a simplified function that returns a boolean and has no output pushed to stdout:

import subprocess, platform
def pingOk(sHost):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)

    except Exception, e:
        return False

    return True

Variables not showing while debugging in Eclipse

I ended up trying something easy by resetting the Debug perspective, which seemed to work:

Window => Perspective => Reset Perspective...

Thanks for the comments.

How to embed a YouTube channel into a webpage

In order to embed your channel, all you need to do is copy then paste the following code in another web-page.

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=YourChannelName&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Make sure to replace the YourChannelName with your actual channel name.

For example: if your channel name were CaliChick94066 your channel embed code would be:

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=CaliChick94066&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Please look at the following links:

YouTube on your site

Embed YouTube Channel

You just have to name the URL to your channel name. Also you can play with the height and the border color and size. Hope it helps

Is there a concise way to iterate over a stream with indices in Java 8?

One possible way is to index each element on the flow:

AtomicInteger index = new AtomicInteger();
Stream.of(names)
  .map(e->new Object() { String n=e; public i=index.getAndIncrement(); })
  .filter(o->o.n.length()<=o.i) // or do whatever you want with pairs...
  .forEach(o->System.out.println("idx:"+o.i+" nam:"+o.n));

Using an anonymous class along a stream is not well-used while being very useful.

Set space between divs

You need a gutter between two div gutter can be made as following

margin(gutter) = width - gutter size E.g margin = calc(70% - 2em)

<body bgcolor="gray">
<section id="main">
        <div id="left">
            Something here     
        </div>
        <div id="right">
                Someone there
        </div>
</section>
</body>
<style>
body{
    font-size: 10px;
}

#main div{
    float: left;
    background-color:#ffffff;
    width: calc(50% - 1.5em);
    margin-left: 1.5em;
}
</style>

Dynamically changing font size of UILabel

Based on @Eyal Ben Dov's answer you may want to create a category to make it flexible to use within another apps of yours.

Obs.: I've updated his code to make compatible with iOS 7

-Header file

#import <UIKit/UIKit.h>

@interface UILabel (DynamicFontSize)

-(void) adjustFontSizeToFillItsContents;

@end

-Implementation file

#import "UILabel+DynamicFontSize.h"

@implementation UILabel (DynamicFontSize)

#define CATEGORY_DYNAMIC_FONT_SIZE_MAXIMUM_VALUE 35
#define CATEGORY_DYNAMIC_FONT_SIZE_MINIMUM_VALUE 3

-(void) adjustFontSizeToFillItsContents
{
    NSString* text = self.text;

    for (int i = CATEGORY_DYNAMIC_FONT_SIZE_MAXIMUM_VALUE; i>CATEGORY_DYNAMIC_FONT_SIZE_MINIMUM_VALUE; i--) {

        UIFont *font = [UIFont fontWithName:self.font.fontName size:(CGFloat)i];
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];

        CGRect rectSize = [attributedText boundingRectWithSize:CGSizeMake(self.frame.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];

        if (rectSize.size.height <= self.frame.size.height) {
            self.font = [UIFont fontWithName:self.font.fontName size:(CGFloat)i];
            break;
        }
    }

}

@end

-Usage

#import "UILabel+DynamicFontSize.h"

[myUILabel adjustFontSizeToFillItsContents];

Cheers

How to redirect a url in NGINX

Best way to do what you want is to add another server block:

server {
        #implemented by default, change if you need different ip or port
        #listen *:80 | *:8000;
        server_name test.com;
        return 301 $scheme://www.test.com$request_uri;
}

And edit your main server block server_name variable as following:

server_name  www.test.com;

Important: New server block is the right way to do this, if is evil. You must use locations and servers instead of if if it's possible. Rewrite is sometimes evil too, so replaced it with return.

Is there a simple way to increment a datetime object one month in Python?

>>> now
datetime.datetime(2016, 1, 28, 18, 26, 12, 980861)
>>> later = now.replace(month=now.month+1)
>>> later
datetime.datetime(2016, 2, 28, 18, 26, 12, 980861)

EDIT: Fails on

y = datetime.date(2016, 1, 31); y.replace(month=2) results in ValueError: day is out of range for month

Ther is no simple way to do it, but you can use your own function like answered below.

Margin between items in recycler view Android

If you want to do it in XML, jus set paddingTopand paddingLeft to your RecyclerView and equal amount of layoutMarginBottom and layoutMarginRight to the item you inflate into your RecyclerView(or vice versa).

How do you run a SQL Server query from PowerShell?

You can use the Invoke-Sqlcmd cmdlet

Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "MyComputer\MyInstance"

http://technet.microsoft.com/en-us/library/cc281720.aspx

How to convert LINQ query result to List?

You need to somehow convert each tbcourse object to an instance of course. For instance course could have a constructor that takes a tbcourse. You could then write the query like this:

var qry = from c in obj.tbCourses
          select new course(c);

List<course> lst = qry.ToList();

Raw SQL Query without DbSet - Entity Framework Core

You can use this (from https://github.com/aspnet/EntityFrameworkCore/issues/1862#issuecomment-451671168 ) :

public static class SqlQueryExtensions
{
    public static IList<T> SqlQuery<T>(this DbContext db, string sql, params object[] parameters) where T : class
    {
        using (var db2 = new ContextForQueryType<T>(db.Database.GetDbConnection()))
        {
            return db2.Query<T>().FromSql(sql, parameters).ToList();
        }
    }

    private class ContextForQueryType<T> : DbContext where T : class
    {
        private readonly DbConnection connection;

        public ContextForQueryType(DbConnection connection)
        {
            this.connection = connection;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // switch on the connection type name to enable support multiple providers
            // var name = con.GetType().Name;
            optionsBuilder.UseSqlServer(connection, options => options.EnableRetryOnFailure());

            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<T>().HasNoKey();
            base.OnModelCreating(modelBuilder);
        }
    }
}

And the usage:

    using (var db = new Db())
    {
        var results = db.SqlQuery<ArbitraryType>("select 1 id, 'joe' name");
        //or with an anonymous type like this
        var results2 = db.SqlQuery(() => new { id =1, name=""},"select 1 id, 'joe' name");
    }

How to echo xml file in php

This worked for me:

echo(header('content-type: text/xml'));

How to apply an XSLT Stylesheet in C#

Here is a tutorial about how to do XSL Transformations in C# on MSDN:

http://support.microsoft.com/kb/307322/en-us/

and here how to write files:

http://support.microsoft.com/kb/816149/en-us

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

http://support.microsoft.com/kb/307379/en-us/

i added this just to provide some more information.

How do I exit from a function?

Yo can simply google for "exit sub in c#".

Also why would you check every text box if it is empty. You can place requiredfieldvalidator for these text boxes if this is an asp.net app and check if(Page.IsValid)

Or another solution is to get not of these conditions:

private void button1_Click(object sender, EventArgs e)
{
    if (!(textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == ""))
    {
        //do events
    }
}

And better use String.IsNullOrEmpty:

private void button1_Click(object sender, EventArgs e)
{
    if (!(String.IsNullOrEmpty(textBox1.Text)
    || String.IsNullOrEmpty(textBox2.Text)
    || String.IsNullOrEmpty(textBox3.Text)))
    {
        //do events
    }
}

JavaScript - Use variable in string match

Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:

var re = new RegExp(yyy, 'g');
xxx.match(re);

Any flags you need (such as /g) can go into the second parameter.

How to index characters in a Golang string?

How about this?

fmt.Printf("%c","HELLO"[1])

As Peter points out, to allow for more than just ASCII:

fmt.Printf("%c", []rune("HELLO")[1])

How to convert a string to utf-8 in Python

  • First, str in Python is represented in Unicode.
  • Second, UTF-8 is an encoding standard to encode Unicode string to bytes. There are many encoding standards out there (e.g. UTF-16, ASCII, SHIFT-JIS, etc.).

When the client sends data to your server and they are using UTF-8, they are sending a bunch of bytes not str.

You received a str because the "library" or "framework" that you are using, has implicitly converted some random bytes to str.

Under the hood, there is just a bunch of bytes. You just need ask the "library" to give you the request content in bytes and you will handle the decoding yourself (if library can't give you then it is trying to do black magic then you shouldn't use it).

  • Decode UTF-8 encoded bytes to str: bs.decode('utf-8')
  • Encode str to UTF-8 bytes: s.encode('utf-8')

Trying to start a service on boot on Android

If you're using Android Studio and you're very fond of auto-complete then I must inform you, I'm using Android Studio v 1.1.0 and I used auto-complete for the following permission

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

And Android Studio Auto-completedRECEIVE_BOOT_COMPLETED all in lower-case like receive_boot_completed and I kept pulling my hair out because I'd already ticked out my checklist for things to do to start service at boot. I just confirmed again

Android Studio DOES auto-complete this permission in lower-case.

HTML5 video won't play in Chrome only

Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?

Browsers might use the canPlayType method internally to check if a <source> is candidate to playback.

In Chrome, I have these results:

document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"

How to change indentation mode in Atom?

Go to File -> Settings

There are 3 different options here.

  1. Soft Tabs
  2. Tab Length
  3. Tab Type

I did some testing and have come to these conclusions about what each one does.

Soft Tabs - Enabling this means it will use spaces by default (i.e. for new files).

Tab Length - How wide the tab character displays, or how many spaces are inserted for a tab if soft tabs is enabled.

Tab Type - This determines the indentation mode to use for existing files. If you set it to auto it will use the existing indentation (tabs or spaces). If you set it to soft or hard, it will force spaces or tabs regardless of the existing indentation. Best to leave this on auto.

Note: Soft = spaces, hard = tab

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

You can also compare with wildcards:

if [[ "$LIST" == *"$SOURCE"* ]]

How to scale down a range of numbers with a known min and max value

For convenience, here is Irritate's algorithm in a Java form. Add error checking, exception handling and tweak as necessary.

public class Algorithms { 
    public static double scale(final double valueIn, final double baseMin, final double baseMax, final double limitMin, final double limitMax) {
        return ((limitMax - limitMin) * (valueIn - baseMin) / (baseMax - baseMin)) + limitMin;
    }
}

Tester:

final double baseMin = 0.0;
final double baseMax = 360.0;
final double limitMin = 90.0;
final double limitMax = 270.0;
double valueIn = 0;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));
valueIn = 360;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));
valueIn = 180;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));

90.0
270.0
180.0

div inside table

It is allow as TD can contain inline- AND block-elements.

Here you can find it in the reference: http://xhtml.com/en/xhtml/reference/td/#td-contains

How to stop an animation (cancel() does not work)

You must use .clearAnimation(); method in UI thread:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        v.clearAnimation();
    }
});

Converting a string to a date in a cell

Have you tried the =DateValue() function?

To include time value, just add the functions together:

=DateValue(A1)+TimeValue(A1)

ReactJs: What should the PropTypes be for this.props.children?

The answers here don't seem to quite cover checking the children exactly. node and object are too permissive, I wanted to check the exact element. Here is what I ended up using:

  • Use oneOfType([]) to allow for single or array of children
  • Use shape and arrayOf(shape({})) for single and array of children, respectively
  • Use oneOf for the child element itself

In the end, something like this:

import PropTypes from 'prop-types'
import MyComponent from './MyComponent'

children: PropTypes.oneOfType([
  PropTypes.shape({
    type: PropTypes.oneOf([MyComponent]),
  }),
  PropTypes.arrayOf(
    PropTypes.shape({
      type: PropTypes.oneOf([MyComponent]),
    })
  ),
]).isRequired

This issue helped me figure this out more clearly: https://github.com/facebook/react/issues/2979

Firestore Getting documents id from collection

I've finally found the solution. Victor was close with the doc data.

const racesCollection: AngularFirestoreCollection<Race>;
return racesCollection.snapshotChanges().map(actions => {       
  return actions.map(a => {
    const data = a.payload.doc.data() as Race;
    data.id = a.payload.doc.id;
    return data;
  });
});

ValueChanges() doesn't include metadata, therefor we must use SnapshotChanges() when we require the document id and then map it properly as stated here https://github.com/angular/angularfire2/blob/master/docs/firestore/collections.md

Append key/value pair to hash with << in Ruby

Perhaps you want Hash#merge ?

1.9.3p194 :015 > h={}
 => {} 
1.9.3p194 :016 > h.merge(:key => 'bar')
 => {:key=>"bar"} 
1.9.3p194 :017 > 

If you want to change the array in place use merge!

1.9.3p194 :016 > h.merge!(:key => 'bar')
 => {:key=>"bar"} 

Eclipse: Frustration with Java 1.7 (unbound library)

To set JDK you can watch this video : how to set JDK . Then when you'll have JDK:

  1. Right click on build path and select "Build Path"
  2. Choose "Configure Build Path"
  3. Click on "JRE System Library [JavaSE-1.7] (unbound)"
  4. Edit it
  5. Choose "Alternate JRE"
  6. Click on "Installed JREs.." button
  7. Press Add
  8. Choose to add "Standard VM"
  9. Choose JRE Home directory - usually it is locates in "C:\Program Files\Java\jre7" directory
  10. Press "Finish"
  11. Re-check newly appeared "Jre7": Verify that now when you edit "JRE System Library [JavaSE-1.7]" "Alternate JRE" is chosen for jre7.

Can I change the scroll speed using css or jQuery?

Just use this js file. (I mentioned 2 examples with different js files. hope the second one is what you need) You can simply change the scroll amount, speed etc by changing the parameters.

https://github.com/nathco/jQuery.scrollSpeed

Here's a Demo

You can also try this. Here's a demo

how to open .mat file without using MATLAB?

.mat files contain binary data, so you will not be able to open them easily with a word processor. There are some options for opening them outside of MATLAB:

If all you need to do is look at the files, you could obtain Octave, which is a free, but somewhat slower implementation of MATLAB. You can refer to How do you open .mat files in Octave? for more information on the subject. You can get octave from http://www.gnu.org/software/octave/download.html. The interface is very similar to MATLAB's.

As NKN and Ergodicity mentioned, there are python libaries available for this as well.

The most hardcore solution would be to write your own processor from scratch. The MAT file specification is available from MathWorks at http://www.mathworks.com/help/pdf_doc/matlab/matfile_format.pdf.

Convert array to JSON

Script for backward-compatibility: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

And call:

var myJsonString = JSON.stringify(yourArray);

Note: The JSON object is now part of most modern web browsers (IE 8 & above). See caniuse for full listing. Credit goes to: @Spudley for his comment below

Fixed positioned div within a relative parent div

here is a more generic solution, that don't depends on the Menu/Header height. its fully responsive, Pure CSS solution, Works great on IE8+, Firefox, Chrome, Safari, opera. supports Content scrolling without affecting the Menu/Header.

Test it with that Working Fiddle

The Html:

<div class="Container">
    <div class="First">
        <p>The First div height is not fixed</p>
        <p>This Layout has been tested on: IE10, IE9, IE8, FireFox, Chrome, Safari, using Pure CSS 2.1 only</p>
    </div>
    <div class="Second">
        <div class="Wrapper">
            <div class="Centered">
                <p>The Second div should always span the available Container space.</p>
                <p>This content is vertically Centered.</p>
            </div>
        </div>
    </div>
</div>

The CSS:

*
{
    margin: 0;
    padding: 0;
}

html, body, .Container
{
    height: 100%;
}

    .Container:before
    {
        content: '';
        height: 100%;
        float: left;
    }

.First
{
    /*for demonstration only*/
    background-color: #bf5b5b;
}

.Second
{
    position: relative;
    z-index: 1;
    /*for demonstration only*/
    background-color: #6ea364;
}

    .Second:after
    {
        content: '';
        clear: both;
        display: block;
    }

/*This part his relevant only for Vertically centering*/
.Wrapper
{
    position: absolute;
    width: 100%;
    height: 100%;
    overflow: auto;
}
    .Wrapper:before
    {
        content: '';
        display: inline-block;
        vertical-align: middle;
        height: 100%;
    }

.Centered
{
    display: inline-block;
    vertical-align: middle;
}

How to open a web page from my application?

Here is my complete code how to open.

there are 2 options:

  1. open using default browser (behavior is like opened inside the browser window)

  2. open through default command options (behavior is like you use "RUN.EXE" command)

  3. open through 'explorer' (behavior is like you wrote url inside your folder window url)

[optional suggestion] 4. use iexplore process location to open the required url

CODE:

internal static bool TryOpenUrl(string p_url)
    {
        // try use default browser [registry: HKEY_CURRENT_USER\Software\Classes\http\shell\open\command]
        try
        {
            string keyValue = Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Software\Classes\http\shell\open\command", "", null) as string;
            if (string.IsNullOrEmpty(keyValue) == false)
            {
                string browserPath = keyValue.Replace("%1", p_url);
                System.Diagnostics.Process.Start(browserPath);
                return true;
            }
        }
        catch { }

        // try open browser as default command
        try
        {
            System.Diagnostics.Process.Start(p_url); //browserPath, argUrl);
            return true;
        }
        catch { }

        // try open through 'explorer.exe'
        try
        {
            string browserPath = GetWindowsPath("explorer.exe");
            string argUrl = "\"" + p_url + "\"";

            System.Diagnostics.Process.Start(browserPath, argUrl);
            return true;
        }
        catch { }

        // return false, all failed
        return false;
    }

and the Helper function:

internal static string GetWindowsPath(string p_fileName)
    {
        string path = null;
        string sysdir;

        for (int i = 0; i < 3; i++)
        {
            try
            {
                if (i == 0)
                {
                    path = Environment.GetEnvironmentVariable("SystemRoot");
                }
                else if (i == 1)
                {
                    path = Environment.GetEnvironmentVariable("windir");
                }
                else if (i == 2)
                {
                    sysdir = Environment.GetFolderPath(Environment.SpecialFolder.System);
                    path = System.IO.Directory.GetParent(sysdir).FullName;
                }

                if (path != null)
                {
                    path = System.IO.Path.Combine(path, p_fileName);
                    if (System.IO.File.Exists(path) == true)
                    {
                        return path;
                    }
                }
            }
            catch { }
        }

        // not found
        return null;
    }

Hope i helped.

"Debug certificate expired" error in Eclipse Android plugins

The Android SDK generates a "debug" signing certificate for you in a keystore called debug.keystore.The Eclipse plug-in uses this certificate to sign each application build that is generated.

Unfortunately a debug certificate is only valid for 365 days. To generate a new one, you must delete the existing debug.keystore file. Its location is platform dependent - you can find it in Preferences -> Android -> Build -> *Default debug keystore.

If you are using Windows, follow the steps below.

DOS: del c:\user\dad.android\debug.keystore

Eclipse: In Project, Clean the project. Close Eclipse. Re-open Eclipse.

Eclipse: Start the Emulator. Remove the Application from the emulator.

If you are using Linux or Mac, follow the steps below.

Manually delete debug.keystore from the .android folder.

You can find the .android folder like this: home/username/.android

Note: the default .android file will be hidden.

So click on the places menu. Under select home folder. Under click on view, under click show hidden files and then the .android folder will be visible.

Delete debug.keystore from the .android folder.

Then clean your project. Now Android will generate a new .android folder file.

What are WSDL, SOAP and REST?

A WSDL is an XML document that describes a web service. It actually stands for Web Services Description Language.

SOAP is an XML-based protocol that lets you exchange info over a particular protocol (can be HTTP or SMTP, for example) between applications. It stands for Simple Object Access Protocol and uses XML for its messaging format to relay the information.

REST is an architectural style of networked systems and stands for Representational State Transfer. It's not a standard itself, but does use standards such as HTTP, URL, XML, etc.

java.util.Date vs java.sql.Date

I had the same issue, the easiest way i found to insert the current date into a prepared statement is this one:

preparedStatement.setDate(1, new java.sql.Date(new java.util.Date().getTime()));

Python: Find a substring in a string and returning the index of the substring

Ideally you would use str.find or str.index like demented hedgehog said. But you said you can't ...

Your problem is your code searches only for the first character of your search string which(the first one) is at index 2.

You are basically saying if char[0] is in s, increment index until ch == char[0] which returned 3 when I tested it but it was still wrong. Here's a way to do it.

def find_str(s, char):
    index = 0

    if char in s:
        c = char[0]
        for ch in s:
            if ch == c:
                if s[index:index+len(char)] == char:
                    return index

            index += 1

    return -1

print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))

It produced the following output:

3
8
-1

How to get a pixel's x,y coordinate color from an image?

Building on Jeff's answer, your first step would be to create a canvas representation of your PNG. The following creates an off-screen canvas that is the same width and height as your image and has the image drawn on it.

var img = document.getElementById('my-image');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

After that, when a user clicks, use event.offsetX and event.offsetY to get the position. This can then be used to acquire the pixel:

var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;

Because you are only grabbing one pixel, pixelData is a four entry array containing the pixel's R, G, B, and A values. For alpha, anything less than 255 represents some level of transparency with 0 being fully transparent.

Here is a jsFiddle example: http://jsfiddle.net/thirtydot/9SEMf/869/ I used jQuery for convenience in all of this, but it is by no means required.

Note: getImageData falls under the browser's same-origin policy to prevent data leaks, meaning this technique will fail if you dirty the canvas with an image from another domain or (I believe, but some browsers may have solved this) SVG from any domain. This protects against cases where a site serves up a custom image asset for a logged in user and an attacker wants to read the image to get information. You can solve the problem by either serving the image from the same server or implementing Cross-origin resource sharing.

Installing J2EE into existing eclipse IDE

http://download.eclipse.org/webtools/updates/ - This is an old URL and doesn't work any more. If you want to install WTP (i.e. J2EE plugins) use the following URLs depending upon the version of the eclipse you are using:

More information can be found here.

How to run Maven from another directory (without cd to project dir)?

I don't think maven supports this. If you're on Unix, and don't want to leave your current directory, you could use a small shell script, a shell function, or just a sub-shell:

user@host ~/project$ (cd ~/some/location; mvn install)
[ ... mvn build ... ]
user@host ~/project$

As a bash function (which you could add to your ~/.bashrc):

function mvn-there() {
  DIR="$1"
  shift
  (cd $DIR; mvn "$@")     
} 

user@host ~/project$ mvn-there ~/some/location install)
[ ... mvn build ... ]
user@host ~/project$

I realize this doesn't answer the specific question, but may provide you with what you're after. I'm not familiar with the Windows shell, though you should be able to reach a similar solution there as well.

Regards

Installing and Running MongoDB on OSX

Download MongoDB and install it on your local machine. Link https://www.mongodb.com/try/download/enterprise

Extract the file and put it on the desktop. Create another folder where you want to store the data. I have created mongodb-data folder. Then run the below command.

Desktop/mongodb/bin/mongod --dbpath=/Users/yourname/Desktop/mongodb-data/

Before the hyphen is the executable path of your mongoDB and after hyphen is your data store.

Linq code to select one item

I'll tell you what worked for me:

int id = int.Parse(insertItem.OwnerTableView.DataKeyValues[insertItem.ItemIndex]["id_usuario"].ToString());

var query = user.First(x => x.id_usuario == id);
tbUsername.Text = query.username;
tbEmail.Text = query.email;
tbPassword.Text = query.password;

My id is the row I want to query, in this case I got it from a radGrid, then I used it to query, but this query returns a row, then you can assign the values you got from the query to textbox, or anything, I had to assign those to textbox.

Setting onSubmit in React.js

In your doSomething() function, pass in the event e and use e.preventDefault().

doSomething = function (e) {
    alert('it works!');
    e.preventDefault();
}

How to allow only numbers in textbox in mvc4 razor

@Html.TextBoxFor(x => x.MobileNo, new { @class = "digit" , @maxlength = "10"})

@section Scripts 
{
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/cssjqryUi")

    <script type="text/javascript">
         $(".digit").keypress(function (e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) 
            {
                $("#errormsg").html("Digits Only").show().fadeOut("slow");
                return false;
            }
         });
    </script>
}

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

  • In HTML 4, <foo / (yes, with no > at all) means <foo> (which leads to <br /> meaning <br>> (i.e. <br>&gt;) and <title/hello/ meaning <title>hello</title>). This is an SGML rule that browsers did a very poor job of supporting, and the spec advises authors to avoid the syntax.

  • In XHTML, <foo /> means <foo></foo>. This is an XML rule that applies to all XML documents. That said, XHTML is often served as text/html which (historically at least) gets processed by browsers using a different parser than documents served as application/xhtml+xml. The W3C provides compatibility guidelines to follow for XHTML as text/html. (Essentially: Only use self-closing tag syntax when the element is defined as EMPTY (and the end tag was forbidden in the HTML spec)).

  • In HTML5, the meaning of <foo /> depends on the type of element.

    • On HTML elements that are designated as void elements (essentially "An element that existed before HTML5 and which was forbidden to have any content"), end tags are simply forbidden. The slash at the end of the start tag is allowed, but has no meaning. It is just syntactic sugar for people (and syntax highlighters) that are addicted to XML.
    • On other HTML elements, the slash is an error, but error recovery will cause browsers to ignore it and treat the tag as a regular start tag. This will usually end up with a missing end tag causing subsequent elements to be children instead of siblings.
    • Foreign elements (imported from XML applications such as SVG) treat it as self-closing syntax.

The server principal is not able to access the database under the current security context in SQL Server MS 2012

SQL Logins are defined at the server level, and must be mapped to Users in specific databases.

In SSMS object explorer, under the server you want to modify, expand Security > Logins, then double-click the appropriate user which will bring up the "Login Properties" dialog.

Select User Mapping, which will show all databases on the server, with the ones having an existing mapping selected. From here you can select additional databases (and be sure to select which roles in each database that user should belong to), then click OK to add the mappings.

enter image description here

These mappings can become disconnected after a restore or similar operation. In this case, the user may still exist in the database but is not actually mapped to a login. If that happens, you can run the following to restore the login:

USE {database};
ALTER USER {user} WITH login = {login}

You can also delete the DB user and recreate it from the Login Properties dialog, but any role memberships or other settings would need to be recreated.

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

I got this error after my computer froze and rebooted on its own. The solution for me was not found on this page, rather on another very highly rated SO question with the same error psql: could not connect to server: No such file or directory (Mac OS X). The answer: just delete this file /usr/local/var/postgres/postmaster.pid, then brew services restart postgresql did the trick. Heed the warning on the linked answer about killing postgres processes before doing this else you could corrupt your db permanently.

Using G++ to compile multiple .cpp and .h files

As rebenvp said I used:

g++ *.cpp -o output

And then do this for output:

./output

But a better solution is to use make file. Read here to know more about make files.

Also make sure that you have added the required .h files in the .cpp files.

docker mounting volumes on host

The VOLUME command will mount a directory inside your container and store any files created or edited inside that directory on your hosts disk outside the container file structure, bypassing the union file system.

The idea is that your volumes can be shared between your docker containers and they will stay around as long as there's a container (running or stopped) that references them.

You can have other containers mount existing volumes (effectively sharing them between containers) by using the --volumes-from command when you run a container.

The fundamental difference between VOLUME and -v is this: -v will mount existing files from your operating system inside your docker container and VOLUME will create a new, empty volume on your host and mount it inside your container.

Example:

  1. You have a Dockerfile that defines a VOLUME /var/lib/mysql.
  2. You build the docker image and tag it some-volume
  3. You run the container

And then,

  1. You have another docker image that you want to use this volume
  2. You run the docker container with the following: docker run --volumes-from some-volume docker-image-name:tag
  3. Now you have a docker container running that will have the volume from some-volume mounted in /var/lib/mysql

Note: Using --volumes-from will mount the volume over whatever exists in the location of the volume. I.e., if you had stuff in /var/lib/mysql, it will be replaced with the contents of the volume.

What is the difference between attribute and property?

What is the difference between Attribute and Property?
What is the difference between Feature and Function? What is the difference between Characteristic and Character? What is the difference between Act and Behavior?

Its just a change in context.

Object,Product,Personality,Person

A Person Acts in a Behavior. A Personality has Characteristics of a given Character. A Product has Feature that derive Functionality. An Object had Attributes that give it Properties.

Oracle listener not running and won't start

1.Check the Environment variables (must be set for System and not for user):

ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server
ORACLE_SID = XE

2.Check if you have the right definition in listener.ora

XE =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
  )

DEFAULT_SERVICE_LISTENER = (XE)

3.Restart the service (Services > OracleServiceXE)

After that you may see a new service called OracleXETNSListenerXE.
There is already an old OracleXETNSListener.

I started both and then I was able to make a successful connection.

Edit:

If everything is running but you still can't connect, check if there is no error: ORA-12557: TNS:protocol adapter not loadable.

To correct the error go back to the Environment variables and this time edit the one called: Path. Be sure that C:\oraclexe\app\oracle\product\11.2.0\server\bin is somewhere at the beginning, definitely before any other path pointing to a different version of the Oracle DB.

How To limit the number of characters in JTextField?

Just Try This :

textfield.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
        if(textfield.getText().length()>=5&&!(evt.getKeyChar()==KeyEvent.VK_DELETE||evt.getKeyChar()==KeyEvent.VK_BACK_SPACE)) {
            getToolkit().beep();
            evt.consume();
         }
     }
});

Sorting data based on second column of a file

You can use the sort command:

sort -k2 -n yourfile

-n, --numeric-sort compare according to string numerical value

For example:

$ cat ages.txt 
Bob 12
Jane 48
Mark 3
Tashi 54

$ sort -k2 -n ages.txt 
Mark 3
Bob 12
Jane 48
Tashi 54

setHintTextColor() in EditText

You could call editText.invalidate() after you reset the hint color. That could resolve your issue. Actually the SDK update the color in the same way.

How can I add a vertical scrollbar to my div automatically?

You need to assign some height to make the overflow: auto; property work.
For testing purpose, add height: 100px; and check.
and also it will be better if you give overflow-y:auto; instead of overflow: auto;, because this makes the element to scroll only vertical but not horizontal.

float:left;
width:1000px;
overflow-y: auto;
height: 100px;

If you don't know the height of the container and you want to show vertical scrollbar when the container reaches a fixed height say 100px, use max-height instead of height property.

For more information, read this MDN article.

How to embed a .mov file in HTML?

Well, if you don't want to do the work yourself (object elements aren't really all that hard), you could always use Mike Alsup's Media plugin: http://jquery.malsup.com/media/

How to while loop until the end of a file in Python without checking for empty line?

I discovered while following the above suggestions that for line in f: does not work for a pandas dataframe (not that anyone said it would) because the end of file in a dataframe is the last column, not the last row. for example if you have a data frame with 3 fields (columns) and 9 records (rows), the for loop will stop after the 3rd iteration, not after the 9th iteration. Teresa

Displaying a vector of strings in C++

vector.size() returns the size of a vector. You didn't put any string in the vector before the loop , so the size of the vector is 0. It will never enter the loop. First put some data in the vector and then try to add them. You can take input from the user for the number of string user wants to enter.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
    vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        userString.push_back(word);
        sentence += userString[i] + " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

another thing, actually you don't have to use a vector to do this.Two strings can do the job for you.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

and if you want to enter string until the user wish , code will be like this:

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    //int SIZE;
    //cin>>SIZE;    //what will be the size of the vector
    while(cin>>word)
    {
        //cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
  //  system("PAUSE");
    return 0;
}

How to set default Checked in checkbox ReactJS?

I tried to accomplish this using Class component: you can view the message for the same

.....

class Checkbox extends React.Component{
constructor(props){
    super(props)
    this.state={
        checked:true
    }
    this.handleCheck=this.handleCheck.bind(this)
}

handleCheck(){
    this.setState({
        checked:!this.state.checked
    })
}

render(){
    var msg=" "
    if(this.state.checked){
        msg="checked!"
    }else{
        msg="not checked!"
    }
    return(
        <div>
            <input type="checkbox" 
            onChange={this.handleCheck}
            defaultChecked={this.state.checked}
            />
            <p>this box is {msg}</p>
        </div>
    )
}

}

Start an Activity with a parameter

Put an int which is your id into the new Intent.

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("key", 1); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent);
finish();

Then grab the id in your new Activity:

Bundle b = getIntent().getExtras();
int value = -1; // or other values
if(b != null)
    value = b.getInt("key");

Random alpha-numeric string in JavaScript?

When I saw this question I thought of when I had to generate UUIDs. I can't take credit for the code, as I am sure I found it here on stackoverflow. If you dont want the dashes in your string then take out the dashes. Here is the function:

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uuid.toUpperCase();
}

Fiddle: http://jsfiddle.net/nlviands/fNPvf/11227/

Advantages of std::for_each over for loop

I find for_each to be bad for readability. The concept is a good one but c++ makes it very hard to write readable, at least for me. c++0x lamda expressions will help. I really like the idea of lamdas. However on first glance I think the syntax is very ugly and I'm not 100% sure I'll ever get used to it. Maybe in 5 years I'll have got used to it and not give it a second thought, but maybe not. Time will tell :)

I prefer to use

vector<thing>::iterator istart = container.begin();
vector<thing>::iterator iend = container.end();
for(vector<thing>::iterator i = istart; i != iend; ++i) {
  // Do stuff
}

I find an explicit for loop clearer to read and explicity using named variables for the start and end iterators reduces the clutter in the for loop.

Of course cases vary, this is just what I usually find best.

How do I type a TAB character in PowerShell?

TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.

Pass a PHP array to a JavaScript function

Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.

drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))

This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here

$employee = array(
 "employee_id" => 10011,
   "Name" => "Nathan",
   "Skills" =>
    array(
           "analyzing",
           "documentation" =>
            array(
              "desktop",
                "mobile"
             )
        )
);

Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.

{
    "employee_id": 10011,
    "Name": "Nathan",
    "Skills": {
        "0": "analyzing",
        "documentation": [
            "desktop",
            "mobile"
        ]
    }
}

On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.

$.ajax({
        type: 'POST',
        headers: {
            "cache-control": "no-cache"
        },
        url: "employee.php",
        async: false,
        cache: false,
        data: {
            employee_id: 10011
        },
        success: function (jsonString) {
            var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
    });

What exactly is the function of Application.CutCopyMode property in Excel

There is a good explanation at https://stackoverflow.com/a/33833319/903783

The values expected seem to be xlCopy and xlCut according to xlCutCopyMode enumeration (https://msdn.microsoft.com/en-us/VBA/Excel-VBA/articles/xlcutcopymode-enumeration-excel), but the 0 value (this is what False equals to in VBA) seems to be useful to clear Excel data put on the Clipboard.

Create an ArrayList with multiple object types?

You don't know the type is Integer or String then you no need Generic. Go With old style.

List list= new ArrayList ();

list.add(1);
list.add("myname");

for(Object o = list){

} 

Reset local repository branch to be just like remote repository HEAD

The answer

git clean -d -f

was underrated (-d to remove directories). Thanks!

Traverse all the Nodes of a JSON Object Tree with JavaScript

There's a new library for traversing JSON data with JavaScript that supports many different use cases.

https://npmjs.org/package/traverse

https://github.com/substack/js-traverse

It works with all kinds of JavaScript objects. It even detects cycles.

It provides the path of each node, too.

PostgreSQL Autoincrement

This way will work for sure, I hope it helps:

CREATE TABLE fruits(
   id SERIAL PRIMARY KEY,
   name VARCHAR NOT NULL
);

INSERT INTO fruits(id,name) VALUES(DEFAULT,'apple');

or

INSERT INTO fruits VALUES(DEFAULT,'apple');

You can check this the details in the next link: http://www.postgresqltutorial.com/postgresql-serial/

Byte Array and Int conversion in Java

Instead of allocating space, et al, an approach using ByteBuffer from java.nio....

byte[] arr = { 0x01, 0x00, 0x00, 0x00, 0x48, 0x01};

// say we want to consider indices 1, 2, 3, 4 {0x00, 0x00, 0x00, 0x48};
ByteBuffer bf = ByteBuffer.wrap(arr, 1, 4); // big endian by default
int num = bf.getInt();    // 72

Now, to go the other way.

ByteBuffer newBuf = ByteBuffer.allocate(4);
newBuf.putInt(num);
byte[] bytes = newBuf.array();  // [0, 0, 0, 72] {0x48 = 72}

Get full path of the files in PowerShell

Why has nobody used the foreach loop yet? A pro here is that you can easily name your variable:

# Note that I'm pretty explicit here. This would work as well as the line after:
# Get-ChildItem -Recurse C:\windows\System32\*.txt
$fileList = Get-ChildItem -Recurse -Path C:\windows\System32 -Include *.txt
foreach ($textfile in $fileList) {
    # This includes the filename ;)
    $filePath = $textfile.fullname
    # You can replace the next line with whatever you want to.
    Write-Output $filePath
}

In a bootstrap responsive page how to center a div

You don't need to change anything in CSS you can directly write this in class and you will get the result.

<div class="col-lg-4 col-md-4 col-sm-4 container justify-content-center">
  <div class="col" style="background:red">
    TEXT
  </div>
</div>

enter image description here

C# Public Enums in Classes

Just declare the enum outside the bounds of the class. Like this:

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
    ...
}

Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)

How do I get the last four characters from a string in C#?

I would like to extend the existing answer mentioning using new ranges in C# 8 or higher: To make the code usable for all possible strings. If you want to copy code, I suggest example 5 or 6.

string mystring ="C# 8.0 finally makes slicing possible";

1: Slicing taking the end part- by specifying how many characters to omit from the beginning- this is, what VS 2019 suggests:

string example1 = mystring[Math.Max(0, mystring.Length - 4)..] ;

2: Slicing taking the end part- by specifying how many characters to take from the end:

string example2 = mystring[^Math.Min(mystring.Length, 4)..] ;

3: Slicing taking the end part- by replacing Max/Min with the ?: operator:

string example3 = (mystring.length > 4)? mystring[^4..] : mystring); 

Personally, I like the second and third variant more than the first.

MS doc reference for Indices and ranges:

Null? But we are not done yet concerning universality. Every example so far will throw an exception for null strings. To consider null (if you don´t use non-nullable strings with C# 8 or higher), and to do it without 'if' (classic example 'with if' already given in another answer) we need:

4: Slicing considering null- by specifying how many characters to omit:

string example4 = mystring?[Math.Max(0, mystring.Length - 4)..] ?? string.Empty;

5: Slicing considering null- by specifying how many characters to take:

string example5 = mystring?[^Math.Min(mystring.Length, 4)..] ?? string.Empty;

6: Slicing considering null with the ?: operator (and two other '?' operators ;-) :
(You cannot put that in a whole in a string interpolation e.g. for WriteLine.)

string example6 = (mystring?.Length > 4) ? filePath[^4..] : mystring ?? string.Empty;

7: Equivalent variant with good old Substring() for C# 6 or 7.x:
(You cannot put that in a whole in a string interpolation e.g. for WriteLine.)

string example7 = (mystring?.Length > 4) ? mystring.Substring(mystring.Length- 4) : mystring ?? string.Empty;

Graceful degradation? I like the new features of C#. Putting them on one line like in the last examples maybe looks a bit excessive. We ended up a little perl´ish didn´t we? But it´s a good example for learning and ok for me to use it once in a tested library method. Even better that we can get rid of null in modern C# if we want and avoid all this null-specific handling.

Such a library/extension method as a shortcut is really useful. Despite the advances in C# you have to write your own to get something easier to use than repeating the code above for every small string manipulation need.

I am one of those who began with BASIC, and 40 years ago there was already Right$(,). Funny, that it is possible to use Strings.Right(,) from VB with C# still too as was shown in another answer.

C# has chosen precision over graceful degradation (in opposite to old BASIC). So copy any appropriate variant you like in these answers and define a graceful shortcut function for yourself, mine is an extension function called RightChars(int).

Android OnClickListener - identify a button

You will learn the way to do it, in an easy way, is:

public class Mtest extends Activity {
  Button b1;
  Button b2;
  public void onCreate(Bundle savedInstanceState) {
    ...
    b1 = (Button) findViewById(R.id.b1);
    b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(myhandler1);
    b2.setOnClickListener(myhandler2);
    ...
  }
  View.OnClickListener myhandler1 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 1st button
    }
  };
  View.OnClickListener myhandler2 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 2nd button
    }
  };
}

Or, if you are working with just one clicklistener, you can do:

View.OnClickListener myOnlyhandler = new View.OnClickListener() {
  public void onClick(View v) {
      switch(v.getId()) {
        case R.id.b1:
          // it was the first button
          break;
        case R.id.b2:
          // it was the second button
          break;
      }
  }
}

Though, I don't recommend doing it that way since you will have to add an if for each button you use. That's hard to maintain.

Save byte array to file

You can use:

File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

If you have an enumerable and not an array, you can use:

File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq

Open Source Alternatives to Reflector?

2 options I know of.

  • CCI
  • Mono Cecil

These wont give you C# though.

Include an SVG (hosted on GitHub) in MarkDown

This will work. Link to your SVG using the following pattern:

https://cdn.rawgit.com/<repo-owner>/<repo>/<branch>/path/to.svg

The downside is hardcoding the owner and repo in the path, meaning the svg will break if either of those are renamed.

Comments in Android Layout xml

From Federico Culloca's note:

Also you cannot use them inside tags

Means; you have to put the comment at the top or bottom of the file - all the places you really want to add comments are at least inside the top level layout tag

Initialization of all elements of an array to one default value in C++?

The page you linked states

If an explicit array size is specified, but an shorter initiliazation list is specified, the unspecified elements are set to zero.

Speed issue: Any differences would be negligible for arrays this small. If you work with large arrays and speed is much more important than size, you can have a const array of the default values (initialized at compile time) and then memcpy them to the modifiable array.

How to plot two histograms together in R?

Here's the version like the ggplot2 one I gave only in base R. I copied some from @nullglob.

generate the data

carrots <- rnorm(100000,5,2)
cukes <- rnorm(50000,7,2.5)

You don't need to put it into a data frame like with ggplot2. The drawback of this method is that you have to write out a lot more of the details of the plot. The advantage is that you have control over more details of the plot.

## calculate the density - don't plot yet
densCarrot <- density(carrots)
densCuke <- density(cukes)
## calculate the range of the graph
xlim <- range(densCuke$x,densCarrot$x)
ylim <- range(0,densCuke$y, densCarrot$y)
#pick the colours
carrotCol <- rgb(1,0,0,0.2)
cukeCol <- rgb(0,0,1,0.2)
## plot the carrots and set up most of the plot parameters
plot(densCarrot, xlim = xlim, ylim = ylim, xlab = 'Lengths',
     main = 'Distribution of carrots and cucumbers', 
     panel.first = grid())
#put our density plots in
polygon(densCarrot, density = -1, col = carrotCol)
polygon(densCuke, density = -1, col = cukeCol)
## add a legend in the corner
legend('topleft',c('Carrots','Cucumbers'),
       fill = c(carrotCol, cukeCol), bty = 'n',
       border = NA)

enter image description here

How can I view the allocation unit size of a NTFS partition in Vista?

The value for BYTES PER CLUSTER - 65536 = 64K

C:\temp>fsutil fsinfo drives

Drives: C:\ D:\ E:\ F:\ G:\ I:\ J:\ N:\ O:\ P:\ S:\

C:\temp>fsutil fsinfo ntfsInfo N:
NTFS Volume Serial Number :       0xfe5a90935a9049f3
NTFS Version   :                  3.1
LFS Version    :                  2.0
Number Sectors :                  0x00000002e15befff
Total Clusters :                  0x000000005c2b7dff
Free Clusters  :                  0x000000005c2a15f0
Total Reserved :                  0x0000000000000000
Bytes Per Sector  :               512
Bytes Per Physical Sector :       512
Bytes Per Cluster :               4096
Bytes Per FileRecord Segment    : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length :           0x0000000000040000
Mft Start Lcn  :                  0x00000000000c0000
Mft2 Start Lcn :                  0x0000000000000002
Mft Zone Start :                  0x00000000000c0000
Mft Zone End   :                  0x00000000000cc820
Resource Manager Identifier :     560F51B2-CEFA-11E5-80C9-98BE94F91273

C:\temp>fsutil fsinfo ntfsInfo N:
NTFS Volume Serial Number :       0x36acd4b1acd46d3d
NTFS Version   :                  3.1
LFS Version    :                  2.0
Number Sectors :                  0x00000002e15befff
Total Clusters :                  0x0000000005c2b7df
Free Clusters  :                  0x0000000005c2ac28
Total Reserved :                  0x0000000000000000
Bytes Per Sector  :               512
Bytes Per Physical Sector :       512
Bytes Per Cluster :               65536
Bytes Per FileRecord Segment    : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length :           0x0000000000010000
Mft Start Lcn  :                  0x000000000000c000
Mft2 Start Lcn :                  0x0000000000000001
Mft Zone Start :                  0x000000000000c000
Mft Zone End   :                  0x000000000000cca0
Resource Manager Identifier :     560F51C3-CEFA-11E5-80C9-98BE94F91273

How to skip "are you sure Y/N" when deleting files in batch files

Use del /F /Q to force deletion of read-only files (/F) and directories and not ask to confirm (/Q) when deleting via wildcard.

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

I got around the issue by using a convert on the "?", so my code looks like convert(char(50),?) and that got rid of the truncation error.

Save Screen (program) output to a file

Ctrl+A then Shift+H works for me. You can view the file screenlog.0 while the program is still running.

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

check if tun/tap enabled:

cat /dev/net/tun

if ok will see something :

cat: /dev/net/tun: File descriptor in bad state

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

How to use passive FTP mode in Windows command prompt?

According to this Egnyte article, Passive FTP is supported from Windows 8.1 onwards.

The Registry key:

"HKEY_CURRENT_USER\Software\Microsoft\FTP\Use PASV"

should be set with the value: yes

If you don't like poking around in the Registry, do the following:

  1. Press WinKey+R to open the Run dialog.
  2. Type inetcpl.cpl and press Enter. The Internet Options dialog will open.
  3. Click on the Advanced tab.
  4. Make your way down to the Browsing secction of the tree view, and ensure the Use Passive FTP item is set to on.
  5. Click on the OK button.

Every time you use ftp.exe, remember to pass the

quote pasv

command immediately after logging in to a remote host.

PS: Grant ftp.exe access to private networks if your Firewall complains.

Git fast forward VS no fast forward merge

The --no-ff option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff.

If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.

For example, the author of this article thinks that --no-ff option should be default and his reasoning is close to that I outlined above:

Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff is not used], whereas it is easily done if the --no-ff flag was used [because it's just one commit]."

Graphic showing how --no-ff groups together all commits from feature branch into one commit on master branch

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Is PowerShell ready to replace my Cygwin shell on Windows?

PowerShell is very powerful, more powerful than the standard built-ins of the Unix shells (but only because it includes much of the functionality usually shelled out to subprograms). Also, consider that you can write applets in any .NET language, including IronPython, IronRuby, PerlNet, etc.. or you can simply call your Cygwin commands from PowerShell, ignoring all the extra functionality and it will work similarly to Bash, KornShell, or whatever...

Can I override and overload static methods in Java?

As any static method is part of class not instance so it is not possible to override static method

Convert InputStream to BufferedReader

InputStream is;
InputStreamReader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);

Converting stream of int's to char's in java

    int i = 7;
    char number = Integer.toString(i).charAt(0);
    System.out.println(number);

Rebuild Docker container on file changes

Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build . So that images get rebuild and refreshed

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Vim: insert the same characters across multiple lines

  1. Ctrl + v to go to visual block mode
  2. Select the lines using the up and down arrow
  3. Enter lowercase 3i (press lowercase I three times)
  4. I (press capital I. That will take you into insert mode.)
  5. Write the text you want to add
  6. Esc
  7. Press the down arrow

How to fix SSL certificate error when running Npm on Windows?

I am having the same issue, I overcome using

npm config set proxy http://my-proxy.com:1080
npm config set https-proxy http://my-proxy.com:1080

Additionally info at node-doc

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

This problem is commonly related to compiler errors in the Java code. Sometimes Android Studio does not show these errors in the Project explorer. However, when a problematic .java file is opened, errors are shown. Try to resolve errors and rebuild the project.

Pandas dataframe fillna() only some columns in place

For some odd reason this DID NOT work (using Pandas: '0.25.1')

df[['col1', 'col2']].fillna(value=0, inplace=True)

Another solution:

subset_cols = ['col1','col2']
[df[col].fillna(0, inplace=True) for col in subset_cols]

Example:

df = pd.DataFrame(data={'col1':[1,2,np.nan,], 'col2':[1,np.nan,3], 'col3':[np.nan,2,3]})

output:

   col1  col2  col3
0  1.00  1.00   nan
1  2.00   nan  2.00
2   nan  3.00  3.00

Apply list comp. to fillna values:

subset_cols = ['col1','col2']
[df[col].fillna(0, inplace=True) for col in subset_cols]

Output:

   col1  col2  col3
0  1.00  1.00   nan
1  2.00  0.00  2.00
2  0.00  3.00  3.00

denied: requested access to the resource is denied : docker

all previous answer were correct, I wanna just add an information I saw was not mentioned;

If the project is a private project to correctly push the image have to be configured a personal access token or deploy token with read_registry key enabled.

source: https://gitlab.com/help/user/project/container_registry#using-with-private-projects

hope this is helpful (also if the question is posted so far in the time)

How can I get the file name from request.FILES?

file = request.FILES['filename']
file.name           # Gives name
file.content_type   # Gives Content type text/html etc
file.size           # Gives file's size in byte
file.read()         # Reads file

how to change background image of button when clicked/focused?

You can also create shapes directly inside the item tag, in case you want to add some more details to your view, like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="#81ba73" />
            <corners android:radius="6dp" />
        </shape>
        <ripple android:color="#c62828"/>
    </item>
    <item android:state_enabled="false">
        <shape>
            <solid android:color="#788e73" />
            <corners android:radius="6dp" />
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="#add8a3" />
            <corners android:radius="6dp" />
        </shape>
    </item>
</selector>

Beware that Android will cycle through the items from top to bottom, therefore, you must place the item without condition on the bottom of the list (so it acts like a default/fallback).

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

Python Pandas Replacing Header with Top Row

The dataframe can be changed by just doing

df.columns = df.iloc[0]
df = df[1:]

Then

df.to_csv(path, index=False) 

Should do the trick.

How to use the command update-alternatives --config java

There are many other binaries that need to be linked so I think it's much better to try something like sudo update-alternatives --all and choosing the right alternatives for everything else besides java and javac.

How to convert a string into double and vice versa?

from this example here, you can see the the conversions both ways:

NSString *str=@"5678901234567890";

long long verylong;
NSRange range;
range.length = 15;
range.location = 0;

[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];

NSLog(@"long long value %lld",verylong);

How to completely remove a dialog on close

$(dialogElement).empty();

$(dialogElement).remove();

this fixes it for real

How to load assemblies in PowerShell?

LoadWithPartialName has been deprecated. The recommended solution for PowerShell V3 is to use the Add-Type cmdlet e.g.:

Add-Type -Path 'C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll'

There are multiple different versions and you may want to pick a particular version. :-)

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I experienced the same problem on my repository. I'm the master of the repository, but I had such an error.

I've unprotected my project and then re-protected again, and the error is gone.

We had upgraded the gitlab version between my previous push and the problematic one. I suppose that this upgrade has created the bug.

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

C++ wait for user input

You can try

#include <iostream>
#include <conio.h>

int main() {

    //some codes

    getch();
    return 0;
}

How to filter a RecyclerView with a SearchView

In Adapter:

public void setFilter(List<Channel> newList){
        mChannels = new ArrayList<>();
        mChannels.addAll(newList);
        notifyDataSetChanged();
    }

In Activity:

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                newText = newText.toLowerCase();
                ArrayList<Channel> newList = new ArrayList<>();
                for (Channel channel: channels){
                    String channelName = channel.getmChannelName().toLowerCase();
                    if (channelName.contains(newText)){
                        newList.add(channel);
                    }
                }
                mAdapter.setFilter(newList);
                return true;
            }
        });

Callback after all asynchronous forEach callbacks are completed

If you encounter asynchronous functions, and you want to make sure that before executing the code it finishes its task, we can always use the callback capability.

For example:

var ctr = 0;
posts.forEach(function(element, index, array){
    asynchronous(function(data){
         ctr++; 
         if (ctr === array.length) {
             functionAfterForEach();
         }
    })
});

Note: functionAfterForEach is the function to be executed after foreach tasks are finished. asynchronous is the asynchronous function executed inside foreach.

SQL Server find and replace specific word in all rows of specific column

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'

or simply this if you are sure that you have no values like this CKIT002

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')

How do I append one string to another in Python?

If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place.

The end result is that the operation is amortized O(n).

e.g.

s = ""
for i in range(n):
    s+=str(i)

used to be O(n^2), but now it is O(n).

From the source (bytesobject.c):

void
PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w)
{
    PyBytes_Concat(pv, w);
    Py_XDECREF(w);
}


/* The following function breaks the notion that strings are immutable:
   it changes the size of a string.  We get away with this only if there
   is only one module referencing the object.  You can also think of it
   as creating a new string object and destroying the old one, only
   more efficiently.  In any case, don't use this if the string may
   already be known to some other part of the code...
   Note that if there's not enough memory to resize the string, the original
   string object at *pv is deallocated, *pv is set to NULL, an "out of
   memory" exception is set, and -1 is returned.  Else (on success) 0 is
   returned, and the value in *pv may or may not be the same as on input.
   As always, an extra byte is allocated for a trailing \0 byte (newsize
   does *not* include that), and a trailing \0 byte is stored.
*/

int
_PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
{
    register PyObject *v;
    register PyBytesObject *sv;
    v = *pv;
    if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
        *pv = 0;
        Py_DECREF(v);
        PyErr_BadInternalCall();
        return -1;
    }
    /* XXX UNREF/NEWREF interface should be more symmetrical */
    _Py_DEC_REFTOTAL;
    _Py_ForgetReference(v);
    *pv = (PyObject *)
        PyObject_REALLOC((char *)v, PyBytesObject_SIZE + newsize);
    if (*pv == NULL) {
        PyObject_Del(v);
        PyErr_NoMemory();
        return -1;
    }
    _Py_NewReference(*pv);
    sv = (PyBytesObject *) *pv;
    Py_SIZE(sv) = newsize;
    sv->ob_sval[newsize] = '\0';
    sv->ob_shash = -1;          /* invalidate cached hash value */
    return 0;
}

It's easy enough to verify empirically.

$ python -m timeit -s"s=''" "for i in xrange(10):s+='a'"
1000000 loops, best of 3: 1.85 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(100):s+='a'"
10000 loops, best of 3: 16.8 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(1000):s+='a'"
10000 loops, best of 3: 158 usec per loop
$ python -m timeit -s"s=''" "for i in xrange(10000):s+='a'"
1000 loops, best of 3: 1.71 msec per loop
$ python -m timeit -s"s=''" "for i in xrange(100000):s+='a'"
10 loops, best of 3: 14.6 msec per loop
$ python -m timeit -s"s=''" "for i in xrange(1000000):s+='a'"
10 loops, best of 3: 173 msec per loop

It's important however to note that this optimisation isn't part of the Python spec. It's only in the cPython implementation as far as I know. The same empirical testing on pypy or jython for example might show the older O(n**2) performance .

$ pypy -m timeit -s"s=''" "for i in xrange(10):s+='a'"
10000 loops, best of 3: 90.8 usec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(100):s+='a'"
1000 loops, best of 3: 896 usec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(1000):s+='a'"
100 loops, best of 3: 9.03 msec per loop
$ pypy -m timeit -s"s=''" "for i in xrange(10000):s+='a'"
10 loops, best of 3: 89.5 msec per loop

So far so good, but then,

$ pypy -m timeit -s"s=''" "for i in xrange(100000):s+='a'"
10 loops, best of 3: 12.8 sec per loop

ouch even worse than quadratic. So pypy is doing something that works well with short strings, but performs poorly for larger strings.

Web API optional parameters

I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.

In case anyone else needs it, in order to have optional parameters in a query string such as:

  • ~/api/products/filter?apc=AA&xpc=BB
  • ~/api/products/filter?sku=7199123

you would use:

[Route("products/filter/{apc?}/{xpc?}/{sku?}")]
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

It seems odd to have to define default values for the method parameters when these types already have a default.

how to properly display an iFrame in mobile safari

Yeah, you can't constrain the iframe itself with height and width. You should put a div around it. If you control the content in the iframe, you can put some JS within the iframe content that will tell the parent to scroll the div when the touch event is received.

like this:

The JS:

setTimeout(function () {
var startY = 0;
var startX = 0;
var b = document.body;
b.addEventListener('touchstart', function (event) {
    parent.window.scrollTo(0, 1);
    startY = event.targetTouches[0].pageY;
    startX = event.targetTouches[0].pageX;
});
b.addEventListener('touchmove', function (event) {
    event.preventDefault();
    var posy = event.targetTouches[0].pageY;
    var h = parent.document.getElementById("scroller");
    var sty = h.scrollTop;

    var posx = event.targetTouches[0].pageX;
    var stx = h.scrollLeft;
    h.scrollTop = sty - (posy - startY);
    h.scrollLeft = stx - (posx - startX);
    startY = posy;
    startX = posx;
});
}, 1000);

The HTML:

<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" id="iframe" src="url" />
</div>

If you don't control the iframe content, you can use an overlay over the iframe in a similar manner, but then you can't interact with the iframe contents other than to scroll it - so you can't, for example, click links in the iframe.

It used to be that you could use two fingers to scroll within an iframe, but that doesn't work anymore.

Update: iOS 6 broke this solution for us. I've been attempting to get a new fix for it, but nothing has worked yet. In addition, it is no longer possible to debug javascript on the device since they introduced Remote Web Inspector, which requires a Mac to use.

Simple logical operators in Bash

A very portable version (even to legacy bourne shell):

if [ "$varA" = 1 -a \( "$varB" = "t1" -o "$varB" = "t2" \) ]
then    do-something
fi

This has the additional quality of running only one subprocess at most (which is the process [), whatever the shell flavor.

Replace = with -eq if variables contain numeric values, e.g.

  • 3 -eq 03 is true, but
  • 3 = 03 is false. (string comparison)

How to get UTC+0 date in Java 8?

I did this in my project and it works like a charm

Date now = new Date();
System.out.println(now);
TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // The magic is here
System.out.println(now);

Counting inversions in an array

The primary purpose of this answer is to compare the speeds of the various Python versions found here, but I also have a few contributions of my own. (FWIW, I just discovered this question while performing a duplicate search).

The relative execution speeds of algorithms implemented in CPython may be different to what one would expect from a simple analysis of the algorithms, and from experience with other languages. That's because Python provides many powerful functions and methods implemented in C that can operate on lists and other collections at close to the speed one would get in a fully-compiled language, so those operations run much faster than equivalent algorithms implemented "manually" with Python code.

Code that takes advantage of these tools can often outperform theoretically superior algorithms that try to do everything with Python operations on individual items of the collection. Of course the actual quantity of data being processed has an impact on this too. But for moderate amounts of data, code that uses an O(n²) algorithm running at C speed can easily beat an O(n log n) algorithm that does the bulk of its work with individual Python operations.

Many of the posted answers to this inversion counting question use an algorithm based on mergesort. Theoretically, this is a good approach, unless the array size is very small. But Python's built-in TimSort (a hybrid stable sorting algorithm, derived from merge sort and insertion sort) runs at C speed, and a mergesort coded by hand in Python cannot hope to compete with it for speed.

One of the more intriguing solutions here, in the answer posted by Niklas B, uses the built-in sort to determine the ranking of array items, and a Binary Indexed Tree (aka Fenwick tree) to store the cumulative sums required to calculate the inversion count. In the process of trying to understand this data structure and Niklas's algorithm I wrote a few variations of my own (posted below). But I also discovered that for moderate list sizes it's actually faster to use Python's built-in sum function than the lovely Fenwick tree.

def count_inversions(a):
    total = 0
    counts = [0] * len(a)
    rank = {v: i for i, v in enumerate(sorted(a))}
    for u in reversed(a):
        i = rank[u]
        total += sum(counts[:i])
        counts[i] += 1
    return total

Eventually, when the list size gets around 500, the O(n²) aspect of calling sum inside that for loop rears its ugly head, and the performance starts to plummet.

Mergesort isn't the only O(nlogn) sort, and several others may be utilized to perform inversion counting. prasadvk's answer uses a binary tree sort, however his code appears to be in C++ or one of its derivatives. So I've added a Python version. I originally used a class to implement the tree nodes, but discovered that a dict is noticeably faster. I eventually used list, which is even faster, although it does make the code a little less readable.

One bonus of treesort is that it's a lot easier to implement iteratively than mergesort is. Python doesn't optimize recursion and it has a recursion depth limit (although that can be increased if you really need it). And of course Python function calls are relatively slow, so when you're trying to optimize for speed it's good to avoid function calls, when practical.

Another O(nlogn) sort is the venerable radix sort. It's big advantage is that it doesn't compare keys to each other. It's disadvantage is that it works best on contiguous sequences of integers, ideally a permutation of integers in range(b**m) where b is usually 2. I added a few versions based on radix sort after attempting to read Counting Inversions, Offline Orthogonal Range Counting, and Related Problems which is linked in calculating the number of “inversions” in a permutation.

To use radix sort effectively to count inversions in a general sequence seq of length n we can create a permutation of range(n) that has the same number of inversions as seq. We can do that in (at worst) O(nlogn) time via TimSort. The trick is to permute the indices of seq by sorting seq. It's easier to explain this with a small example.

seq = [15, 14, 11, 12, 10, 13]
b = [t[::-1] for t in enumerate(seq)]
print(b)
b.sort()
print(b)

output

[(15, 0), (14, 1), (11, 2), (12, 3), (10, 4), (13, 5)]
[(10, 4), (11, 2), (12, 3), (13, 5), (14, 1), (15, 0)]

By sorting the (value, index) pairs of seq we have permuted the indices of seq with the same number of swaps that are required to put seq into its original order from its sorted order. We can create that permutation by sorting range(n) with a suitable key function:

print(sorted(range(len(seq)), key=lambda k: seq[k]))

output

[4, 2, 3, 5, 1, 0]

We can avoid that lambda by using seq's .__getitem__ method:

sorted(range(len(seq)), key=seq.__getitem__)

This is only slightly faster, but we're looking for all the speed enhancements we can get. ;)


The code below performs timeit tests on all of the existing Python algorithms on this page, plus a few of my own: a couple of brute-force O(n²) versions, a few variations on Niklas B's algorithm, and of course one based on mergesort (which I wrote without referring to the existing answers). It also has my list-based treesort code roughly derived from prasadvk's code, and various functions based on radix sort, some using a similar strategy to the mergesort approaches, and some using sum or a Fenwick tree.

This program measures the execution time of each function on a series of random lists of integers; it can also verify that each function gives the same results as the others, and that it doesn't modify the input list.

Each timeit call gives a vector containing 3 results, which I sort. The main value to look at here is the minimum one, the other values merely give an indication of how reliable that minimum value is, as discussed in the Note in the timeit module docs.

Unfortunately, the output from this program is too large to include in this answer, so I'm posting it in its own (community wiki) answer.

The output is from 3 runs on my ancient 32 bit single core 2GHz machine running Python 3.6.0 on an old Debian-derivative distro. YMMV. During the tests I shut down my Web browser and disconnected from my router to minimize the impact of other tasks on the CPU.

The first run tests all the functions with list sizes from 5 to 320, with loop sizes from 4096 to 64 (as the list size doubles, the loop size is halved). The random pool used to construct each list is half the size of the list itself, so we are likely to get lots of duplicates. Some of the inversion counting algorithms are more sensitive to duplicates than others.

The second run uses larger lists: 640 to 10240, and a fixed loop size of 8. To save time it eliminates several of the slowest functions from the tests. My brute-force O(n²) functions are just way too slow at these sizes, and as mentioned earlier, my code that uses sum, which does so well on small to moderate lists, just can't keep up on big lists.

The final run covers list sizes from 20480 to 655360, and a fixed loop size of 4, with the 8 fastest functions. For list sizes under 40,000 or so Tim Babych's code is the clear winner. Well done Tim! Niklas B's code is a good all-round performer too, although it gets beaten on the smaller lists. The bisection-based code of "python" also does rather well, although it appears to be a little slower with huge lists with lots of duplicates, probably due to that linear while loop it uses to step over dupes.

However, for the very large list sizes, the bisection-based algorithms can't compete with the true O(nlogn) algorithms.

#!/usr/bin/env python3

''' Test speeds of various ways of counting inversions in a list

    The inversion count is a measure of how sorted an array is.
    A pair of items in a are inverted if i < j but a[j] > a[i]

    See https://stackoverflow.com/questions/337664/counting-inversions-in-an-array

    This program contains code by the following authors:
    mkso
    Niklas B
    B. M.
    Tim Babych
    python
    Zhe Hu
    prasadvk
    noman pouigt
    PM 2Ring

    Timing and verification code by PM 2Ring
    Collated 2017.12.16
    Updated 2017.12.21
'''

from timeit import Timer
from random import seed, randrange
from bisect import bisect, insort_left

seed('A random seed string')

# Merge sort version by mkso
def count_inversion_mkso(lst):
    return merge_count_inversion(lst)[1]

def merge_count_inversion(lst):
    if len(lst) <= 1:
        return lst, 0
    middle = len(lst) // 2
    left, a = merge_count_inversion(lst[:middle])
    right, b = merge_count_inversion(lst[middle:])
    result, c = merge_count_split_inversion(left, right)
    return result, (a + b + c)

def merge_count_split_inversion(left, right):
    result = []
    count = 0
    i, j = 0, 0
    left_len = len(left)
    while i < left_len and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            count += left_len - i
            j += 1
    result += left[i:]
    result += right[j:]
    return result, count

# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# Using a Binary Indexed Tree, aka a Fenwick tree, by Niklas B.
def count_inversions_NiklasB(a):
    res = 0
    counts = [0] * (len(a) + 1)
    rank = {v: i for i, v in enumerate(sorted(a), 1)}
    for x in reversed(a):
        i = rank[x] - 1
        while i:
            res += counts[i]
            i -= i & -i
        i = rank[x]
        while i <= len(a):
            counts[i] += 1
            i += i & -i
    return res

# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# Merge sort version by B.M
# Modified by PM 2Ring to deal with the global counter
bm_count = 0

def merge_count_BM(seq):
    global bm_count
    bm_count = 0
    sort_bm(seq)
    return bm_count

def merge_bm(l1,l2):
    global bm_count
    l = []
    while l1 and l2:
        if l1[-1] <= l2[-1]:
            l.append(l2.pop())
        else:
            l.append(l1.pop())
            bm_count += len(l2)
    l.reverse()
    return l1 + l2 + l

def sort_bm(l):
    t = len(l) // 2
    return merge_bm(sort_bm(l[:t]), sort_bm(l[t:])) if t > 0 else l

# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# Bisection based method by Tim Babych
def solution_TimBabych(A):
    sorted_left = []
    res = 0
    for i in range(1, len(A)):
        insort_left(sorted_left, A[i-1])
        # i is also the length of sorted_left
        res += (i - bisect(sorted_left, A[i]))
    return res

# Slightly faster, except for very small lists
def solutionE_TimBabych(A):
    res = 0
    sorted_left = []
    for i, u in enumerate(A):
        # i is also the length of sorted_left
        res += (i - bisect(sorted_left, u))
        insort_left(sorted_left, u)
    return res

# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# Bisection based method by "python"
def solution_python(A):
    B = list(A)
    B.sort()
    inversion_count = 0
    for i in range(len(A)):
        j = binarySearch_python(B, A[i])
        while B[j] == B[j - 1]:
            if j < 1:
                break
            j -= 1
        inversion_count += j
        B.pop(j)
    return inversion_count

def binarySearch_python(alist, item):
    first = 0
    last = len(alist) - 1
    found = False
    while first <= last and not found:
        midpoint = (first + last) // 2
        if alist[midpoint] == item:
            return midpoint
        else:
            if item < alist[midpoint]:
                last = midpoint - 1
            else:
                first = midpoint + 1

# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# Merge sort version by Zhe Hu
def inv_cnt_ZheHu(a):
    _, count = inv_cnt(a.copy())
    return count

def inv_cnt(a):
    n = len(a)
    if n==1:
        return a, 0
    left = a[0:n//2] # should be smaller
    left, cnt1 = inv_cnt(left)
    right = a[n//2:] # should be larger
    right, cnt2 = inv_cnt(right)

    cnt = 0
    i_left = i_right = i_a = 0
    while i_a < n:
        if (i_right>=len(right)) or (i_left < len(left)
            and left[i_left] <= right[i_right]):
            a[i_a] = left[i_left]
            i_left += 1
        else:
            a[i_a] = right[i_right]
            i_right += 1
            if i_left < len(left):
                cnt += len(left) - i_left
        i_a += 1
    return (a, cnt1 + cnt2 + cnt)

# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# Merge sort version by noman pouigt
# From https://stackoverflow.com/q/47830098
def reversePairs_nomanpouigt(nums):
    def merge(left, right):
        if not left or not right:
            return (0, left + right)
        #if everything in left is less than right
        if left[len(left)-1] < right[0]:
            return (0, left + right)
        else:
            left_idx, right_idx, count = 0, 0, 0
            merged_output = []

            # check for condition before we merge it
            while left_idx < len(left) and right_idx < len(right):
                #if left[left_idx] > 2 * right[right_idx]:
                if left[left_idx] > right[right_idx]:
                    count += len(left) - left_idx
                    right_idx += 1
                else:
                    left_idx += 1

            #merging the sorted list
            left_idx, right_idx = 0, 0
            while left_idx < len(left) and right_idx < len(right):
                if left[left_idx] > right[right_idx]:
                    merged_output += [right[right_idx]]
                    right_idx += 1
                else:
                    merged_output += [left[left_idx]]
                    left_idx += 1
            if left_idx == len(left):
                merged_output += right[right_idx:]
            else:
                merged_output += left[left_idx:]
        return (count, merged_output)

    def partition(nums):
        count = 0
        if len(nums) == 1 or not nums:
            return (0, nums)
        pivot = len(nums)//2
        left_count, l = partition(nums[:pivot])
        right_count, r = partition(nums[pivot:])
        temp_count, temp_list = merge(l, r)
        return (temp_count + left_count + right_count, temp_list)
    return partition(nums)[0]

# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# PM 2Ring
def merge_PM2R(seq):
    seq, count = merge_sort_count_PM2R(seq)
    return count

def merge_sort_count_PM2R(seq):
    mid = len(seq) // 2
    if mid == 0:
        return seq, 0
    left, left_total = merge_sort_count_PM2R(seq[:mid])
    right, right_total = merge_sort_count_PM2R(seq[mid:])
    total = left_total + right_total
    result = []
    i = j = 0
    left_len, right_len = len(left), len(right)
    while i < left_len and j < right_len:
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
            total += left_len - i
    result.extend(left[i:])
    result.extend(right[j:])
    return result, total

def rank_sum_PM2R(a):
    total = 0
    counts = [0] * len(a)
    rank = {v: i for i, v in enumerate(sorted(a))}
    for u in reversed(a):
        i = rank[u]
        total += sum(counts[:i])
        counts[i] += 1
    return total

# Fenwick tree functions adapted from C code on Wikipedia
def fen_sum(tree, i):
    ''' Return the sum of the first i elements, 0 through i-1 '''
    total = 0
    while i:
        total += tree[i-1]
        i -= i & -i
    return total

def fen_add(tree, delta, i):
    ''' Add delta to element i and thus 
        to fen_sum(tree, j) for all j > i 
    '''
    size = len(tree)
    while i < size:
        tree[i] += delta
        i += (i+1) & -(i+1)

def fenwick_PM2R(a):
    total = 0
    counts = [0] * len(a)
    rank = {v: i for i, v in enumerate(sorted(a))}
    for u in reversed(a):
        i = rank[u]
        total += fen_sum(counts, i)
        fen_add(counts, 1, i)
    return total

def fenwick_inline_PM2R(a):
    total = 0
    size = len(a)
    counts = [0] * size
    rank = {v: i for i, v in enumerate(sorted(a))}
    for u in reversed(a):
        i = rank[u]
        j = i + 1
        while i:
            total += counts[i]
            i -= i & -i
        while j < size:
            counts[j] += 1
            j += j & -j
    return total

def bruteforce_loops_PM2R(a):
    total = 0
    for i in range(1, len(a)):
        u = a[i]
        for j in range(i):
            if a[j] > u:
                total += 1
    return total

def bruteforce_sum_PM2R(a):
    return sum(1 for i in range(1, len(a)) for j in range(i) if a[j] > a[i])

# Using binary tree counting, derived from C++ code (?) by prasadvk
# https://stackoverflow.com/a/16056139
def ltree_count_PM2R(a):
    total, root = 0, None
    for u in a:
        # Store data in a list-based tree structure
        # [data, count, left_child, right_child]
        p = [u, 0, None, None]
        if root is None:
            root = p
            continue
        q = root
        while True:
            if p[0] < q[0]:
                total += 1 + q[1]
                child = 2
            else:
                q[1] += 1
                child = 3
            if q[child]:
                q = q[child]
            else:
                q[child] = p
                break
    return total

# Counting based on radix sort, recursive version
def radix_partition_rec(a, L):
    if len(a) < 2:
        return 0
    if len(a) == 2:
        return a[1] < a[0]
    left, right = [], []
    count = 0
    for u in a:
        if u & L:
            right.append(u)
        else:
            count += len(right)
            left.append(u)
    L >>= 1
    if L:
        count += radix_partition_rec(left, L) + radix_partition_rec(right, L)
    return count

# The following functions determine swaps using a permutation of 
# range(len(a)) that has the same inversion count as `a`. We can create
# this permutation with `sorted(range(len(a)), key=lambda k: a[k])`
# but `sorted(range(len(a)), key=a.__getitem__)` is a little faster.

# Counting based on radix sort, iterative version
def radix_partition_iter(seq, L):
    count = 0
    parts = [seq]
    while L and parts:
        newparts = []
        for a in parts:
            if len(a) < 2:
                continue
            if len(a) == 2:
                count += a[1] < a[0]
                continue
            left, right = [], []
            for u in a:
                if u & L:
                    right.append(u)
                else:
                    count += len(right)
                    left.append(u)
            if left:
                newparts.append(left)
            if right:
                newparts.append(right)
        parts = newparts
        L >>= 1
    return count

def perm_radixR_PM2R(a):
    size = len(a)
    b = sorted(range(size), key=a.__getitem__)
    n = size.bit_length() - 1
    return radix_partition_rec(b, 1 << n)

def perm_radixI_PM2R(a):
    size = len(a)
    b = sorted(range(size), key=a.__getitem__)
    n = size.bit_length() - 1
    return radix_partition_iter(b, 1 << n)

# Plain sum of the counts of the permutation
def perm_sum_PM2R(a):
    total = 0
    size = len(a)
    counts = [0] * size
    for i in reversed(sorted(range(size), key=a.__getitem__)):
        total += sum(counts[:i])
        counts[i] = 1
    return total

# Fenwick sum of the counts of the permutation
def perm_fenwick_PM2R(a):
    total = 0
    size = len(a)
    counts = [0] * size
    for i in reversed(sorted(range(size), key=a.__getitem__)):
        j = i + 1
        while i:
            total += counts[i]
            i -= i & -i
        while j < size:
            counts[j] += 1
            j += j & -j
    return total

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# All the inversion-counting functions
funcs = (
    solution_TimBabych,
    solutionE_TimBabych,
    solution_python,
    count_inversion_mkso,
    count_inversions_NiklasB,
    merge_count_BM,
    inv_cnt_ZheHu,
    reversePairs_nomanpouigt,
    fenwick_PM2R,
    fenwick_inline_PM2R,
    merge_PM2R,
    rank_sum_PM2R,
    bruteforce_loops_PM2R,
    bruteforce_sum_PM2R,
    ltree_count_PM2R,
    perm_radixR_PM2R,
    perm_radixI_PM2R,
    perm_sum_PM2R,
    perm_fenwick_PM2R,
)

def time_test(seq, loops, verify=False):
    orig = seq
    timings = []
    for func in funcs:
        seq = orig.copy()
        value = func(seq) if verify else None
        t = Timer(lambda: func(seq))
        result = sorted(t.repeat(3, loops))
        timings.append((result, func.__name__, value))
        assert seq==orig, 'Sequence altered by {}!'.format(func.__name__)
    first = timings[0][-1]
    timings.sort()
    for result, name, value in timings:
        result = ', '.join([format(u, '.5f') for u in result])
        print('{:24} : {}'.format(name, result))

    if verify:
        # Check that all results are identical
        bad = ['%s: %d' % (name, value)
            for _, name, value in timings if value != first]
        if bad:
            print('ERROR. Value: {}, bad: {}'.format(first, ', '.join(bad)))
        else:
            print('Value: {}'.format(first))
    print()

#Run the tests
size, loops = 5, 1 << 12
verify = True
for _ in range(7):
    hi = size // 2
    print('Size = {}, hi = {}, {} loops'.format(size, hi, loops))
    seq = [randrange(hi) for _ in range(size)]
    time_test(seq, loops, verify)
    loops >>= 1
    size <<= 1

#size, loops = 640, 8
#verify = False
#for _ in range(5):
    #hi = size // 2
    #print('Size = {}, hi = {}, {} loops'.format(size, hi, loops))
    #seq = [randrange(hi) for _ in range(size)]
    #time_test(seq, loops, verify)
    #size <<= 1

#size, loops = 163840, 4
#verify = False
#for _ in range(3):
    #hi = size // 2
    #print('Size = {}, hi = {}, {} loops'.format(size, hi, loops))
    #seq = [randrange(hi) for _ in range(size)]
    #time_test(seq, loops, verify)
    #size <<= 1

Please see here for the output

Extend contigency table with proportions (percentages)

Your code doesn't seem so ugly to me...
however, an alternative (not much better) could be e.g. :

df <- data.frame(table(yn))
colnames(df) <- c('Smoker','Freq')
df$Perc <- df$Freq / sum(df$Freq) * 100

------------------
  Smoker Freq Perc
1     No   19 47.5
2    Yes   21 52.5

Apply formula to the entire column

This is for those who want to overwrite the column cells quickly (without cutting and copying). This is the same as double-clicking the cell box but unlike double-clicking, it still works after the first try.

  1. Select the column cell you would like to copy downwards
  2. Press Ctrl+Shift+ to select the cells below
  3. Press Ctrl+Enter to copy the contents of the first cell into the cells below

BONUS:

The shortcut for going to the bottom-most content (to double-check the copy) is Ctrl+. To go back up you can use Ctrl+ but if your top rows are frozen you'll also have to press Enter a few times.

how do I insert a column at a specific column index in pandas?

see docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html

using loc = 0 will insert at the beginning

df.insert(loc, column, value)

df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})

df
Out: 
   B  C
0  1  4
1  2  5
2  3  6

idx = 0
new_col = [7, 8, 9]  # can be a list, a Series, an array or a scalar   
df.insert(loc=idx, column='A', value=new_col)

df
Out: 
   A  B  C
0  7  1  4
1  8  2  5
2  9  3  6

T-SQL: Deleting all duplicate rows but keeping one

Example query:

DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)

Here fields are column on which you want to group the duplicate rows.

Repeat command automatically in Linux

"watch" does not allow fractions of a second in Busybox, while "sleep" does. If that matters to you, try this:

while true; do ls -l; sleep .5; done

ImportError: No module named MySQLdb

While @Edward van Kuik's answer is correct, it doesn't take into account an issue with virtualenv v1.7 and above.

In particular installing python-mysqldb via apt on Ubuntu put it under /usr/lib/pythonX.Y/dist-packages, but this path isn't included by default in the virtualenv's sys.path.

So to resolve this, you should create your virtualenv with system packages by running something like:

virtualenv --system-site-packages .venv

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I think you can change the "Automatically detect settings" via the registry key name "AutoConfigURL". here is the code that I check in c#. Wish you luck.

    RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                    if(registry.GetValue("AutoConfigURL") != null)
                    {
                        //Proxy Server disabled (Untick Proxy Server)
                        registry.DeleteValue("AutoConfigURL");
                    }

How can I fill a column with random numbers in SQL? I get the same value in every row

Instead of rand(), use newid(), which is recalculated for each row in the result. The usual way is to use the modulo of the checksum. Note that checksum(newid()) can produce -2,147,483,648 and cause integer overflow on abs(), so we need to use modulo on the checksum return value before converting it to absolute value.

UPDATE CattleProds
SET    SheepTherapy = abs(checksum(NewId()) % 10000)
WHERE  SheepTherapy IS NULL

This generates a random number between 0 and 9999.

Inserting HTML into a div

And many lines may look like this. The html here is sample only.

var div = document.createElement("div");

div.innerHTML =
    '<div class="slideshow-container">\n' +
    '<div class="mySlides fade">\n' +
    '<div class="numbertext">1 / 3</div>\n' +
    '<img src="image1.jpg" style="width:100%">\n' +
    '<div class="text">Caption Text</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">2 / 3</div>\n' +
    '<img src="image2.jpg" style="width:100%">\n' +
    '<div class="text">Caption Two</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">3 / 3</div>\n' +
    '<img src="image3.jpg" style="width:100%">\n' +
    '<div class="text">Caption Three</div>\n' +
    '</div>\n' +

    '<a class="prev" onclick="plusSlides(-1)">&#10094;</a>\n' +
    '<a class="next" onclick="plusSlides(1)">&#10095;</a>\n' +
    '</div>\n' +
    '<br>\n' +

    '<div style="text-align:center">\n' +
    '<span class="dot" onclick="currentSlide(1)"></span> \n' +
    '<span class="dot" onclick="currentSlide(2)"></span> \n' +
    '<span class="dot" onclick="currentSlide(3)"></span> \n' +
    '</div>\n';

document.body.appendChild(div);

The server encountered an internal error or misconfiguration and was unable to complete your request

Check your servers error log, typically /var/log/apache2/error.log.

SQL Inner join more than two tables

select WucsName as WUCS_Name,Year,Tot_Households,Tot_Households,Tot_Male_Farmers  from tbl_Gender
INNER JOIN tblWUCS
ON tbl_Gender.WUCS_id =tblWUCS .WucsId 
INNER JOIN tblYear
ON tbl_Gender.YearID=tblYear.yearID

There are 3 Tables 1. tbl_Gender 2. tblWUCS 3. tblYear

What is the pythonic way to detect the last element in a 'for' loop?

Use slicing and is to check for the last element:

for data in data_list:
    <code_that_is_done_for_every_element>
    if not data is data_list[-1]:
        <code_that_is_done_between_elements>

Caveat emptor: This only works if all elements in the list are actually different (have different locations in memory). Under the hood, Python may detect equal elements and reuse the same objects for them. For instance, for strings of the same value and common integers.

adb connection over tcp not working now

Step 1 . Go to Androidsdk\platform-tools on PC/Laptop

Step 2 :

Connect your device via USB and run:

adb kill-server

then run

adb tcpip 5555

you will see below message...

daemon not running. starting it now on port 5037 * daemon started successfully * restarting in TCP mode port: 5555

Step3:

Now open new CMD window,

Go to Androidsdk\platform-tools

Now run

adb connect xx.xx.xx.xx:5555 (xx.xx.xx.xx is device IP)

Step4: Disconnect your device from USB and it will work as if connected from your Android studio.

Should black box or white box testing be the emphasis for testers?

Here is my 5 cents:

As a developer, I mostly write tests for methods (in a class) as white box tests, simple because I do not want my test to break just because I change the inner works of my code.

I only want to my tests to break if my method behavior changes (e.g. returns a different result than before).

Over the last 20 years of development, I simple got tired of doing up-to double work just because my unit tests was strongly tied to the code and I need to maintain both application code and test code.

I think making decoupling code (also when you code tests) is a very good practice.

Another 5 cents: I hardly never use mocking frameworks, because when I find it necessarily to mock something I prefer to decouple my code instead - and yes in many cases that is very possible (especially if you are not working in legacy code) :-)

Pretty-Print JSON Data to a File using Python

You could redirect a file to python and open using the tool and to read it use more.

The sample code will be,

cat filename.json | python -m json.tool | more

How to decode a Base64 string?

I had issues with spaces showing in between my output and there was no answer online at all to fix this issue. I literally spend many hours trying to find a solution and found one from playing around with the code to the point that I almost did not even know what I typed in at the time that I got it to work. Here is my fix for the issue: [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String($base64string)|?{$_}))

find filenames NOT ending in specific extensions on Unix?

You could do something using the grep command:

find . | grep -v '(dll|exe)$'

The -v flag on grep specifically means "find things that don't match this expression."

MySQL Select all columns from one table and some from another table

Just use the table name:

SELECT myTable.*, otherTable.foo, otherTable.bar...

That would select all columns from myTable and columns foo and bar from otherTable.

How to add new line in Markdown presentation?

MarkDown file in three way to Break a Line

<br /> Tag Using

paragraph First Line <br /> Second Line

\ Using

First Line sentence \
Second Line sentence 

space keypress two times Using

First Line sentence??
Second Line sentence

Paragraphs in use <br /> tag.

Multiple sentences in using \ or two times press space key then Enter and write a new sentence.

Difference between UTF-8 and UTF-16?

Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.

Other than sharing same unicode number for given character, each one is their own format.

UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...

UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.

Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.

Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.

Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )

So, people use UTF-8 where ever possible.

How to change Angular CLI favicon

Following steps worked for me.

  1. Remove default "favicon.ico" file with a new one with different name i.e. "_favicon.ico" in my case.

    Note :: Don't keep the default name, as it's get's cached in your browser and difficult to overwrite with new icon.

  2. Update index.html with new link tag i.e.

     <link rel="icon" type="image/x-icon" href="_favicon.ico" /> 
    
  3. Update .angular-cli.json with new icon name i.e. "_favicon.ico".

  4. Build & launch your app, and do a hard refresh Ctrl+F5.

Case statement in MySQL

Yes, something like this:

SELECT
    id,
    action_heading,
    CASE
        WHEN action_type = 'Income' THEN action_amount
        ELSE NULL
    END AS income_amt,
    CASE
        WHEN action_type = 'Expense' THEN action_amount
        ELSE NULL
    END AS expense_amt

FROM tbl_transaction;

As other answers have pointed out, MySQL also has the IF() function to do this using less verbose syntax. I generally try to avoid this because it is a MySQL-specific extension to SQL that isn't generally supported elsewhere. CASE is standard SQL and is much more portable across different database engines, and I prefer to write portable queries as much as possible, only using engine-specific extensions when the portable alternative is considerably slower or less convenient.

How do I fix "The expression of type List needs unchecked conversion...'?

Since getEntries returns a raw List, it could hold anything.

The warning-free approach is to create a new List<SyndEntry>, then cast each element of the sf.getEntries() result to SyndEntry before adding it to your new list. Collections.checkedList does not do this checking for you—although it would have been possible to implement it to do so.

By doing your own cast up front, you're "complying with the warranty terms" of Java generics: if a ClassCastException is raised, it will be associated with a cast in the source code, not an invisible cast inserted by the compiler.

Understanding __getitem__ method

Cong Ma does a good job of explaining what __getitem__ is used for - but I want to give you an example which might be useful. Imagine a class which models a building. Within the data for the building it includes a number of attributes, including descriptions of the companies that occupy each floor :

Without using __getitem__ we would have a class like this :

class Building(object):
     def __init__(self, floors):
         self._floors = [None]*floors
     def occupy(self, floor_number, data):
          self._floors[floor_number] = data
     def get_floor_data(self, floor_number):
          return self._floors[floor_number]

building1 = Building(4) # Construct a building with 4 floors
building1.occupy(0, 'Reception')
building1.occupy(1, 'ABC Corp')
building1.occupy(2, 'DEF Inc')
print( building1.get_floor_data(2) )

We could however use __getitem__ (and its counterpart __setitem__) to make the usage of the Building class 'nicer'.

class Building(object):
     def __init__(self, floors):
         self._floors = [None]*floors
     def __setitem__(self, floor_number, data):
          self._floors[floor_number] = data
     def __getitem__(self, floor_number):
          return self._floors[floor_number]

building1 = Building(4) # Construct a building with 4 floors
building1[0] = 'Reception'
building1[1] = 'ABC Corp'
building1[2] = 'DEF Inc'
print( building1[2] )

Whether you use __setitem__ like this really depends on how you plan to abstract your data - in this case we have decided to treat a building as a container of floors (and you could also implement an iterator for the Building, and maybe even the ability to slice - i.e. get more than one floor's data at a time - it depends on what you need.

Some dates recognized as dates, some dates not recognized. Why?

I come across this problem when I tried to convert to Australian date format in excel. I split the cell with delimiter and used the following code from split cells then altered the issue areas.

=date(dd,mm,yy)

Python: Generate random number between x and y which is a multiple of 5

>>> import random
>>> random.randrange(5,60,5)

should work in any Python >= 2.

jQuery changing css class to div

You can add and remove classes with jQuery like so:

$(".first").addClass("second")
// remove a class
$(".first").removeClass("second")

By the way you can set multiple classes in your markup right away separated with a whitespace

<div class="second first"></div>

Regex for numbers only

This works with integers and decimal numbers. It doesn't match if the number has the coma thousand separator ,

"^-?\\d*(\\.\\d+)?$"

some strings that matches with this:

894
923.21
76876876
.32
-894
-923.21
-76876876
-.32

some strings that doesn't:

hello
9bye
hello9bye
888,323
5,434.3
-8,336.09
87078.

Fetch frame count with ffmpeg

Calculate it based on time, instead.

That's what I do and it works great for me, and many others. First, find the length of the video in the below snippet:

Seems stream 0 codec frame rate differs from container frame rate: 5994.00 
(5994/1) -> 29.97 (30000/1001)
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/Users/stu/Movies/District9.mov':
  Duration: 00:02:32.20, start: 0.000000, bitrate: 9808 kb/s
    Stream #0.0(eng): Video: h264, yuv420p, 1920x1056, 29.97tbr, 2997tbn, 5994tbc
    Stream #0.1(eng): Audio: aac, 44100 Hz, 2 channels, s16
    Stream #0.2(eng): Data: tmcd / 0x64636D74

You'll should be able to consistently and safely find Duration: hh:mm:ss.nn to determine the source video clip size. Then, for each update line (CR, no LF) you can parse the text for the current time mark it is at:

frame=   84 fps= 18 q=10.0 size=       5kB time=1.68 bitrate=  26.1kbits/s    
frame=   90 fps= 17 q=10.0 size=       6kB time=1.92 bitrate=  23.8kbits/s    
frame=   94 fps= 16 q=10.0 size=     232kB time=2.08 bitrate= 913.0kbits/s    

Just be careful to not always expect perfect output from these status lines. They can include error messages like here:

frame=   24 fps= 24 q=-1.0 size=       0kB time=1.42 bitrate=   0.3kbits/s    
frame=   41 fps= 26 q=-1.0 size=       0kB time=2.41 bitrate=   0.2kbits/s    
[h264 @ 0x1013000]Cannot parallelize deblocking type 1, decoding such frames in
sequential order
frame=   49 fps= 24 q=26.0 size=       4kB time=0.28 bitrate= 118.1kbits/s    
frame=   56 fps= 22 q=23.0 size=       4kB time=0.56 bitrate=  62.9kbits/s    

Once you have the time, it is simple math: time / duration * 100 = % done.

How to calculate an angle from three points?

You mentioned a signed angle (-90). In many applications angles may have signs (positive and negative, see http://en.wikipedia.org/wiki/Angle). If the points are (say) P2(1,0), P1(0,0), P3(0,1) then the angle P3-P1-P2 is conventionally positive (PI/2) whereas the angle P2-P1-P3 is negative. Using the lengths of the sides will not distinguish between + and - so if this matters you will need to use vectors or a function such as Math.atan2(a, b).

Angles can also extend beyond 2*PI and while this is not relevant to the current question it was sufficiently important that I wrote my own Angle class (also to make sure that degrees and radians did not get mixed up). The questions as to whether angle1 is less than angle2 depends critically on how angles are defined. It may also be important to decide whether a line (-1,0)(0,0)(1,0) is represented as Math.PI or -Math.PI

How do I write stderr to a file while using "tee" with a pipe?

Like the accepted answer well explained by lhunath, you can use

command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)

Beware than if you use bash you could have some issue.

Let me take the matthew-wilcoxson exemple.

And for those who "seeing is believing", a quick test:

(echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)

Personally, when I try, I have this result :

user@computer:~$ (echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)
user@computer:~$ Test Out
Test Err

Both message does not appear at the same level. Why Test Out seem to be put like if it is my previous command ?
Prompt is on a blank line, let me think the process is not finished, and when I press Enter this fix it.
When I check the content of the files, it is ok, redirection works.

Let take another test.

function outerr() {
  echo "out"     # stdout
  echo >&2 "err" # stderr
}

user@computer:~$ outerr
out
err

user@computer:~$ outerr >/dev/null
err

user@computer:~$ outerr 2>/dev/null
out

Trying again the redirection, but with this function.

function test_redirect() {
  fout="stdout.log"
  ferr="stderr.log"
  echo "$ outerr"
  (outerr) > >(tee "$fout") 2> >(tee "$ferr" >&2)
  echo "# $fout content :"
  cat "$fout"
  echo "# $ferr content :"
  cat "$ferr"
}

Personally, I have this result :

user@computer:~$ test_redirect
$ outerr
# stdout.log content :
out
out
err
# stderr.log content :
err
user@computer:~$

No prompt on a blank line, but I don't see normal output, stdout.log content seem to be wrong, only stderr.log seem to be ok. If I relaunch it, output can be different...

So, why ?

Because, like explained here :

Beware that in bash, this command returns as soon as [first command] finishes, even if the tee commands are still executed (ksh and zsh do wait for the subprocesses)

So, if you use bash, prefer use the better exemple given in this other answer :

{ { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2

It will fix the previous issues.

Now, the question is, how to retrieve exit status code ?
$? does not works.
I have no found better solution than switch on pipefail with set -o pipefail (set +o pipefail to switch off) and use ${PIPESTATUS[0]} like this

function outerr() {
  echo "out"
  echo >&2 "err"
  return 11
}

function test_outerr() {
  local - # To preserve set option
  ! [[ -o pipefail ]] && set -o pipefail; # Or use second part directly
  local fout="stdout.log"
  local ferr="stderr.log"
  echo "$ outerr"
  { { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2
  # First save the status or it will be lost
  local status="${PIPESTATUS[0]}" # Save first, the second is 0, perhaps tee status code.
  echo "==="
  echo "# $fout content :"
  echo "<==="
  cat "$fout"
  echo "===>"
  echo "# $ferr content :"
  echo "<==="
  cat "$ferr"
  echo "===>"
  if (( status > 0 )); then
    echo "Fail $status > 0"
    return "$status" # or whatever
  fi
}
user@computer:~$ test_outerr
$ outerr
err
out
===
# stdout.log content :
<===
out
===>
# stderr.log content :
<===
err
===>
Fail 11 > 0

sass :first-child not working

While @Andre is correct that there are issues with pseudo elements and their support, especially in older (IE) browsers, that support is improving all the time.

As for your question of, are there any issues, I'd say I've not really seen any, although the syntax for the pseudo-element can be a bit tricky, especially when first sussing it out. So:

div#top-level
  declarations: ...
  div.inside
    declarations: ...
    &:first-child
      declarations: ...

which compiles as one would expect:

div#top-level{
  declarations... }
div#top-level div.inside {
  declarations... }
div#top-level div.inside:first-child {
  declarations... }

I haven't seen any documentation on any of this, save for the statement that "sass can do everything that css can do." As always, with Haml and SASS the indentation is everything.

Understanding inplace=True

Save it to the same variable

data["column01"].where(data["column01"]< 5, inplace=True)

Save it to a separate variable

data["column02"] = data["column01"].where(data["column1"]< 5)

But, you can always overwrite the variable

data["column01"] = data["column01"].where(data["column1"]< 5)

FYI: In default inplace = False

Using underscores in Java variables and method names

it's just your own style,nothing a bad style code,and nothing a good style code,just difference our code with the others.

Basic Ajax send/receive with node.js

Express makes this kind of stuff really intuitive. The syntax looks like below :

var app = require('express').createServer();
app.get("/string", function(req, res) {
    var strings = ["rad", "bla", "ska"]
    var n = Math.floor(Math.random() * strings.length)
    res.send(strings[n])
})
app.listen(8001)

https://expressjs.com

If you're using jQuery on the client side you can do something like this:

$.get("/string", function(string) {
    alert(string)
})

Remove file from SVN repository without deleting local copy

Deleting files and folders

If you want to delete an item from the repository, but keep it locally as an unversioned file/folder, use Extended Context Menu ? Delete (keep local). You have to hold the Shift key while right clicking on the item in the explorer list pane (right pane) in order to see this in the extended context menu.

Delete completely:
right mouse click ? Menu ? Delete

Delete & Keep local:
Shift + right mouse click ? Menu ? Delete

How to set image in circle in swift

If you mean you want to make a UIImageView circular in Swift you can just use this code:

imageView.layer.cornerRadius = imageView.frame.height / 2
imageView.clipsToBounds = true

How do I pass JavaScript values to Scriptlet in JSP?

You cannot do that but you can do the opposite:

In your jsp you can:

String name = "John Allepe";    
request.setAttribute("CustomerName", name);

Access the variable in the js:

var name = "<%= request.getAttribute("CustomerName") %>";
alert(name);