Programs & Examples On #Load testing

Load Testing: A type of performance testing conducted to evaluate the behavior of a component or system with increasing load, e.g. numbers of parallel users and/or numbers of transactions, to determine what load can be handled by the component or system.

Load vs. Stress testing

Wikipedia on load testing (bold is mine):

[...]A load test is usually conducted to understand the behaviour of the system under a specific expected load. This load can be the expected concurrent number of users on the application performing a specific number of transactions within the set duration. This test will give out the response times of all the important business critical transactions.[...]

and on stress testing:

understand the upper limits of capacity within the system. This kind of test is done to determine the system's robustness in terms of extreme load and helps application administrators to determine if the system will perform sufficiently if the current load goes well above the expected maximum.

So the bottom line is: if you are testing normal, expected load (you know the system will be used by up to 100 users at a time), this is load testing. But when you want to determine how the system behaves under extreme load (DoS, Slashdot effect) and when it breaks, this is stress testing.

How do I install jmeter on a Mac?

You have 2 options:

brew update to update homebrew packages

brew install jmeter to install jmeter

Read this blog to know how to map folders from standard jmeter to homebrew installed version.

  • Install using standard version which I would advise you to do. Steps are:

    1. Install Last compatible JDK version (7 or 8 as of JMeter 3.1).

    2. Download JMeter from here

    3. Unzip folder and run from the folder:

bin/jmeter

How can I sanitize user input with PHP?

PHP 5.2 introduced the filter_var function.

It supports a great deal of SANITIZE, VALIDATE filters.

http://php.net/manual/en/function.filter-var.php

How to change content on hover

This little and simple trick I just learnt may help someone trying to avoid :before or :after pseudo elements altogether (for whatever reason) in changing text on hover. You can add both texts in the HTML, but vary the CSS 'display' property based on hover. Assuming the second text 'Add' has a class named 'add-label'; here is a little modification:

span.add-label{
 display:none;
}
.item:hover span.align{
 display:none;
}
.item:hover span.add-label{
 display:block;
}

Here is a demonstration on codepen: https://codepen.io/ifekt/pen/zBaEVJ

add created_at and updated_at fields to mongoose schemas

In your model schema, just add an attribute timestamps and assign value true to it as shown:-

var ItemSchema = new Schema({
   name :  { type: String, required: true, trim: true },
},{timestamps : true}
);

Java IOException "Too many open files"

You're obviously not closing your file descriptors before opening new ones. Are you on windows or linux?

How can I autoformat/indent C code in vim?

Try the following keystrokes:

gg=G

Explanation: gg goes to the top of the file, = is a command to fix the indentation and G tells it to perform the operation to the end of the file.

How can I read the contents of an URL with Python?

# retrieving data from url
# only for python 3

import urllib.request

def main():
  url = "http://docs.python.org"

# retrieving data from URL
  webUrl = urllib.request.urlopen(url)
  print("Result code: " + str(webUrl.getcode()))

# print data from URL 
  print("Returned data: -----------------")
  data = webUrl.read().decode("utf-8")
  print(data)

if __name__ == "__main__":
  main()

How to set default font family for entire Android app

Android does not provide much in the way of support for applying fonts across the whole app (see this issue). You have 4 options to set the font for the entire app:

  • Option1: Apply reflection to change the system font
  • Option2: Create and subclass custom View classes for each View that needs a custom font
  • Option3: Implement a View Crawler which traverses the view hierarchy for the current screen
  • Option4: Use a 3rd party library.

Details of these options can be found here.

When should I use "this" in a class?

There are a lot of good answers, but there is another very minor reason to put this everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this will make it a whole lot clearer to read.

Imagine this:

public class Hello {
    private String foo;

    // Some 10k lines of codes

    private String getStringFromSomewhere() {
        // ....
    }

    // More codes

    public class World {
        private String bar;

        // Another 10k lines of codes

        public void doSomething() {
            // More codes
            foo = "FOO";
            // More codes
            String s = getStringFromSomewhere();
            // More codes
            bar = s;
        }
    }
}

This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.

You will struggle to find out where foo resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere() for the same reason. Lastly, after you have forgotten what s is, that bar = s is going to give you the final blow.

Compare it to this:

public void doSomething() {
    // More codes
    Hello.this.foo = "FOO";
    // More codes
    String s = Hello.this.getStringFromSomewhere();
    // More codes
    this.bar = s;
}
  1. You know foo is a variable declared in outer class Hello.
  2. You know getStringFromSomewhere() is a method declared in outer class as well.
  3. You know that bar belongs to World class, and s is a local variable declared in that method.

Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

In my case the problem that I faced was:

CodeSign error: code signing is required for product type 'Unit Test Bundle' in SDK 'iOS 8.4'

Fortunatelly, the target did not implemented anything, so a quick solution is remove it.

enter image description here

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

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

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

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

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

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

4) To remove white space at both ends:

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

5) To replace white space everywhere

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

6) To replace white space at the beginning:

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

7) To replace white space at the end:

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

8) To replace white space at both ends:

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

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

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

ImportError: numpy.core.multiarray failed to import

The same error came for me. The problem is that you might have created a file called numpy.py. This file might coincide with numpy library. So, delete that numpy.py file and the problem gets solved.

Error handling in C code

What you could do instead of returning your error, and thus forbidding you from returning data with your function, is using a wrapper for your return type:

typedef struct {
    enum {SUCCESS, ERROR} status;
    union {
        int errCode;
        MyType value;
    } ret;
} MyTypeWrapper;

Then, in the called function:

MyTypeWrapper MYAPIFunction(MYAPIHandle h) {
    MyTypeWrapper wrapper;
    // [...]
    // If there is an error somewhere:
    wrapper.status = ERROR;
    wrapper.ret.errCode = MY_ERROR_CODE;

    // Everything went well:
    wrapper.status = SUCCESS;
    wrapper.ret.value = myProcessedData;
    return wrapper;
} 

Please note that with the following method, the wrapper will have the size of MyType plus one byte (on most compilers), which is quite profitable; and you won't have to push another argument on the stack when you call your function (returnedSize or returnedError in both of the methods you presented).

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

Intro: There are the (probably) best solutions. But you have to know it and remember it and sometimes you have to hope that your Python version isn't too old or whatever the issue could be.

Then there are the most 'hacky' solutions. They are great and short but sometimes are hard to understand, to read and to remember.

There is, though, an alternative which is to to try to reinvent the wheel. - Why reinventing the wheel? - Generally because it's a really good way to learn (and sometimes just because the already-existing tool doesn't do exactly what you would like and/or the way you would like it) and the easiest way if you don't know or don't remember the perfect tool for your problem.

So, I propose to reinvent the wheel of the Counter class from the collections module (partially at least):

class MyDict(dict):
    def __add__(self, oth):
        r = self.copy()

        try:
            for key, val in oth.items():
                if key in r:
                    r[key] += val  # You can custom it here
                else:
                    r[key] = val
        except AttributeError:  # In case oth isn't a dict
            return NotImplemented  # The convention when a case isn't handled

        return r

a = MyDict({'a':1, 'b':2, 'c':3})
b = MyDict({'b':3, 'c':4, 'd':5})

print(a+b)  # Output {'a':1, 'b': 5, 'c': 7, 'd': 5}

There would probably others way to implement that and there are already tools to do that but it's always nice to visualize how things would basically works.

ConnectionTimeout versus SocketTimeout

A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.

A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.

By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!

If only the incoming stream stalls for more than a millisecond you are running into a timeout.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

you will get a No mapping found for HTTP request with URI error

if you scanned the wrong package

e.g your controller is in my.package.abc but you mistakenly put

<context:component-scan base-package="my.package.efg*" />

or

@ComponentScan("my.package.efg*")

which in the sense, your controller doesn't get scanned into the web application context, when request comes in not just url, but the entire class is not found!

Changing the color of a clicked table row using jQuery

jQuery :

$("#data td").toggle(function(){
    $(this).css('background-color','blue')
},function(){
    $(this).css('background-color','ur_default_color')
});

AngularJS - Any way for $http.post to send request parameters instead of JSON?

Quick adjustment - for those of you having trouble with the global configuration of the transformRequest function, here's the snippet i'm using to get rid of the Cannot read property 'jquery' of undefined error:

$httpProvider.defaults.transformRequest = function(data) {
        return data != undefined ? $.param(data) : null;
    }

Reset all the items in a form

Do as below create class and call it like this

Check : Reset all Controls (Textbox, ComboBox, CheckBox, ListBox) in a Windows Form using C#

private void button1_Click(object sender, EventArgs e)
{
   Utilities.ResetAllControls(this);
}

public class Utilities
    {
        public static void ResetAllControls(Control form)
        {
            foreach (Control control in form.Controls)
            {
                if (control is TextBox)
                {
                    TextBox textBox = (TextBox)control;
                    textBox.Text = null;
                }

                if (control is ComboBox)
                {
                    ComboBox comboBox = (ComboBox)control;
                    if (comboBox.Items.Count > 0)
                        comboBox.SelectedIndex = 0;
                }

                if (control is CheckBox)
                {
                    CheckBox checkBox = (CheckBox)control;
                    checkBox.Checked = false;
                }

                if (control is ListBox)
                {
                    ListBox listBox = (ListBox)control;
                    listBox.ClearSelected();
                }
            }
        }      
    }

Add newline to VBA or Visual Basic 6

There are actually two ways of doing this:

  1. st = "Line 1" + vbCrLf + "Line 2"

  2. st = "Line 1" + vbNewLine + "Line 2"

These even work for message boxes (and all other places where strings are used).

How to set background color of view transparent in React Native

Here is my solution to a modal that can be rendered on any screen and initialized in App.tsx

ModalComponent.tsx

import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet, Platform } from 'react-native';
import EventEmitter from 'events';
// I keep localization files for strings and device metrics like height and width which are used for styling 
import strings from '../../config/strings';
import metrics from '../../config/metrics';

const emitter = new EventEmitter();
export const _modalEmitter = emitter

export class ModalView extends Component {
    state: {
        modalVisible: boolean,
        text: string, 
        callbackSubmit: any, 
        callbackCancel: any,
        animation: any
    }

    constructor(props) {
        super(props)
        this.state = {
            modalVisible: false,
            text: "", 
            callbackSubmit: (() => {}), 
            callbackCancel: (() => {}),
            animation: new Animated.Value(0)
        } 
    }

    componentDidMount() {
        _modalEmitter.addListener(strings.modalOpen, (event) => {
            var state = {
                modalVisible: true,
                text: event.text, 
                callbackSubmit: event.onSubmit, 
                callbackCancel: event.onClose,
                animation: new Animated.Value(0)
            } 
            this.setState(state)
        })
        _modalEmitter.addListener(strings.modalClose, (event) => {
            var state = {
                modalVisible: false,
                text: "", 
                callbackSubmit: (() => {}), 
                callbackCancel: (() => {}),
                animation: new Animated.Value(0)
            } 
            this.setState(state)
        })
    }

    componentWillUnmount() {
        var state = {
            modalVisible: false,
            text: "", 
            callbackSubmit: (() => {}), 
            callbackCancel: (() => {})
        } 
        this.setState(state)
    }

    closeModal = () => {
        _modalEmitter.emit(strings.modalClose)
    }

    startAnimation=()=>{
        Animated.timing(this.state.animation, {
            toValue : 0.5,
            duration : 500
        }).start()
    }

    body = () => {
        const animatedOpacity ={
            opacity : this.state.animation
        }
        this.startAnimation()
        return (
            <View style={{ height: 0 }}>
                <Modal
                    animationType="fade"
                    transparent={true}
                    visible={this.state.modalVisible}>

                    // render a transparent gray background over the whole screen and animate it to fade in, touchable opacity to close modal on click out

                    <Animated.View style={[styles.modalBackground, animatedOpacity]} > 
                        <TouchableOpacity onPress={() => this.closeModal()} activeOpacity={1} style={[styles.modalBackground, {opacity: 1} ]} > 
                        </TouchableOpacity>
                    </Animated.View>

                    // render an absolutely positioned modal component over that background
                    <View style={styles.modalContent}>

                        <View key="text_container">
                            <Text>{this.state.text}?</Text>
                        </View>
                        <View key="options_container">
                            // keep in mind the content styling is very minimal for this example, you can put in your own component here or style and make it behave as you wish
                            <TouchableOpacity
                                onPress={() => {
                                    this.state.callbackSubmit();
                                }}>
                                <Text>Confirm</Text>
                            </TouchableOpacity>

                            <TouchableOpacity
                                onPress={() => {
                                    this.state.callbackCancel();
                                }}>
                                <Text>Cancel</Text>
                            </TouchableOpacity>

                        </View>
                    </View>
                </Modal>
            </View> 
        );
    }

    render() {
        return this.body()
    }
}

// to center the modal on your screen 
// top: metrics.DEVICE_HEIGHT/2 positions the top of the modal at the center of your screen
// however you wanna consider your modal's height and subtract half of that so that the 
// center of the modal is centered not the top, additionally for 'ios' taking into consideration
// the 20px top bunny ears offset hence - (Platform.OS == 'ios'? 120 : 100)
// where 100 is half of the modal's height of 200
const styles = StyleSheet.create({
    modalBackground: {
        height: '100%', 
        width: '100%', 
        backgroundColor: 'gray', 
        zIndex: -1 
    },
    modalContent: { 
        position: 'absolute', 
        alignSelf: 'center', 
        zIndex: 1, 
        top: metrics.DEVICE_HEIGHT/2 - (Platform.OS == 'ios'? 120 : 100), 
        justifyContent: 'center', 
        alignItems: 'center', 
        display: 'flex', 
        height: 200, 
        width: '80%', 
        borderRadius: 27,
        backgroundColor: 'white', 
        opacity: 1 
    },
})

App.tsx render and import

import { ModalView } from './{your_path}/ModalComponent';

render() {
    return (
        <React.Fragment>
            <StatusBar barStyle={'dark-content'} />
            <AppRouter />
            <ModalView />
        </React.Fragment>
    )
}

and to use it from any component

SomeComponent.tsx

import { _modalEmitter } from './{your_path}/ModalComponent'

// Some functions within your component

showModal(modalText, callbackOnSubmit, callbackOnClose) {
    _modalEmitter.emit(strings.modalOpen, { text: modalText, onSubmit: callbackOnSubmit.bind(this), onClose: callbackOnClose.bind(this) })
}

closeModal() {
    _modalEmitter.emit(strings.modalClose)
}

Hope I was able to help some of you, I used a very similar structure for in-app notifications

Happy coding

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

select to_char(sysdate, 'DD-fmMONTH-YYYY') "Date" from Dual;

The above query result will be as given below.

Date

01-APRIL-2019

Import python package from local directory into interpreter

Inside a package if there is setup.py, then better to install it

pip install -e .

How to change DatePicker dialog color for Android 5.0

The reason why Neil's suggestion results in a fullscreen DatePicker is the choice of parent theme:

<!-- Theme.AppCompat.Light is not a dialog theme -->
<style name="DialogTheme" parent="**Theme.AppCompat.Light**">
    <item name="colorAccent">@color/blue_500</item>
</style>

Moreover, if you go this route, you have to specify the theme while creating the DatePickerDialog:

// R.style.DialogTheme
new DatePickerDialog(MainActivity.this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        //DO SOMETHING
    }
}, 2015, 02, 26).show();

This, in my opinion, is not good. One should try to keep the styling out of java and inside styles.xml/themes.xml.

I do agree that Neil's suggestion, with a bit of change (changing the parent theme to say, Theme.Material.Light.Dialog) will get you the desired result. But, here's the other way:

On first inspection, we come across datePickerStyle which defines things such as: headerBackground(what you are trying to change), dayOfWeekBackground, and a few other text-colors and text-styles.

Overriding this attribute in your app's theme will not work. DatePickerDialog uses a separate theme assignable by the attribute datePickerDialogTheme. So, for our changes to take affect, we must override datePickerStyle inside an overriden datePickerDialogTheme.

Here we go:

Override datePickerDialogTheme inside your app's base theme:

<style name="AppBaseTheme" parent="android:Theme.Material.Light">
    ....
    <item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>
</style>

Define MyDatePickerDialogTheme. The choice of parent theme will depend on what your app's base theme is: it could be either Theme.Material.Dialog or Theme.Material.Light.Dialog:

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
</style>

We have overridden datePickerStyle with the style MyDatePickerStyle. The choice of parent will once again depend on what your app's base theme is: either Widget.Material.DatePicker or Widget.Material.Light.DatePicker. Define it as per your requirements:

<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
    <item name="android:headerBackground">@color/chosen_header_bg_color</item>
</style>

Currently, we are only overriding headerBackground which by default is set to ?attr/colorAccent (this is also why Neil suggestion works in changing the background). But there's quite a lot of customization possible:

dayOfWeekBackground
dayOfWeekTextAppearance
headerMonthTextAppearance
headerDayOfMonthTextAppearance
headerYearTextAppearance
headerSelectedTextColor
yearListItemTextAppearance
yearListSelectorColor
calendarTextColor
calendarSelectedTextColor

If you don't want this much control (customization), you don't need to override datePickerStyle. colorAccent controls most of the DatePicker's colors. So, overriding just colorAccent inside MyDatePickerDialogTheme should work:

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:colorAccent">@color/date_picker_accent</item>

    <!-- No need to override 'datePickerStyle' -->
    <!-- <item name="android:datePickerStyle">@style/MyDatePickerStyle</item> -->
</style>

Overriding colorAccent gives you the added benefit of changing OK & CANCEL text colors as well. Not bad.

This way you don't have to provide any styling information to DatePickerDialog's constructor. Everything has been wired properly:

DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }
 }, 2015, 5, 22);

 dpd.show();

Class is inaccessible due to its protection level

It may also be the case that the library containing the class in question is not properly signed with a strong name.

Simple way to create matrix of random numbers

An answer using map-reduce:-

map(lambda x: map(lambda y: ran(),range(len(inputs[0]))),range(hiden_neurons))

file_get_contents() Breaks Up UTF-8 Characters

I think you simply have a double conversion of the character type there :D

It may be, because you opened an html document within a html document. So you have something that looks like this in the end

<!DOCTYPE html> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<!DOCTYPE html> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test</title>.......

The use of mb_detect_encoding therefore may lead you to other issues.

How to display length of filtered ng-repeat data

Since AngularJS 1.3 you can use aliases:

item in items | filter:x as results

and somewhere:

<span>Total {{results.length}} result(s).</span>

From docs:

You can also provide an optional alias expression which will then store the intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message when a filter is active on the repeater, but the filtered result set is empty.

For example: item in items | filter:x as results will store the fragment of the repeated items as results, but only after the items have been processed through the filter.

how concatenate two variables in batch script?

The way is correct, but can be improved a bit with the extended set-syntax.

set "var=xyz"

Sets the var to the content until the last quotation mark, this ensures that no "hidden" spaces are appended.

Your code would look like

set "var1=A"
set "var2=B"
set "AB=hi"
set "newvar=%var1%%var2%"
echo %newvar% is the concat of var1 and var2
echo !%newvar%! is the indirect content of newvar

Regular expression to find two strings anywhere in input

/^.*?\bcat\b.*?\bmat\b.*?$/m

Using the m modifier (which ensures the beginning/end metacharacters match on line breaks rather than at the very beginning and end of the string):

  • ^ matches the line beginning
  • .*? matches anything on the line before...
  • \b matches a word boundary the first occurrence of a word boundary (as @codaddict discussed)
  • then the string cat and another word boundary; note that underscores are treated as "word" characters, so _cat_ would not match*;
  • .*?: any characters before...
  • boundary, mat, boundary
  • .*?: any remaining characters before...
  • $: the end of the line.

It's important to use \b to ensure the specified words aren't part of longer words, and it's important to use non-greedy wildcards (.*?) versus greedy (.*) because the latter would fail on strings like "There is a cat on top of the mat which is under the cat." (It would match the last occurrence of "cat" rather than the first.)

* If you want to be able to match _cat_, you can use:

/^.*?(?:\b|_)cat(?:\b|_).*?(?:\b|_)mat(?:\b|_).*?$/m

which matches either underscores or word boundaries around the specified words. (?:) indicates a non-capturing group, which can help with performance or avoid conflicted captures.

Edit: A question was raised in the comments about whether the solution would work for phrases rather than just words. The answer is, absolutely yes. The following would match "A line which includes both the first phrase and the second phrase":

/^.*?(?:\b|_)first phrase here(?:\b|_).*?(?:\b|_)second phrase here(?:\b|_).*?$/m

Edit 2: If order doesn't matter you can use:

/^.*?(?:\b|_)(first(?:\b|_).*?(?:\b|_)second|second(?:\b|_).*?(?:\b|_)first)(?:\b|_).*?$/m

And if performance is really an issue here, it's possible lookaround (if your regex engine supports it) might (but probably won't) perform better than the above, but I'll leave both the arguably more complex lookaround version and performance testing as an exercise to the questioner/reader.

Edited per @Alan Moore's comment. I didn't have a chance to test it, but I'll take your word for it.

How can I create an array with key value pairs?

Use the square bracket syntax:

if (!empty($row["title"])) {
    $catList[$row["datasource_id"]] = $row["title"];
}

$row["datasource_id"] is the key for where the value of $row["title"] is stored in.

JavaScript REST client Library

jQuery has JSON-REST plugin with REST style of URI parameter templates. According to its description example of using is the followin: $.Read("/{b}/{a}", { a:'foo', b:'bar', c:3 }) becomes a GET to "/bar/foo?c=3".

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

Try any of the following solutions. I get errors with adb every now and then. And one of the following always works.

Solution 1
Open command prompt as administrator and enter

  1. adb kill-server
  2. adb start-server

Solution 2
Install drivers for your phone if you're not testing on emulator.

Solution 3
Open android sdk manager and install "Google USB Driver" from extras folder. (attached screenshot)

Android SDK Google USB Driver missing

Solution 4
Go to settings > Developer Options > Enable USB Debugging.
(If you don't see Developer Options, Go to Settings > About Phone > Keep tapping "Build number" until it says "You're a developer!"

Enable USB Debugging

Converting Integers to Roman Numerals - Java

Just to keep up with the technology, here's a Java 8 version using streams and a custom Collector, eliminating the need for loops or if statements:

import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.IntStream;

public class RomanNumeral {

    public static void main(String arg[]) {
        IntStream.range(1, 4000).forEach(value -> System.out.println( Arrays.stream(Mark.values()).collect(new MarkCollector<Mark>(value)).toString()));
    }

    enum Mark {
        M(1000), CM(900), D(500), CD(400), C(100), XC(90), L(50), XL(40), X(10), IX(9), V(5), IV(4), I(1);

        private final int value;

        private Mark(int value) { this.value = value; }

        public int value() { return value; }
    }

    static class MarkCollector<T extends Mark> implements Collector<T, StringBuilder, StringBuilder> {

        private final int[] valueholder = new int[1];

        MarkCollector(int value) { valueholder[0] = value; }

        @Override
        public Supplier<StringBuilder> supplier() { return () -> StringBuilder::new; }

        @Override
        public BiConsumer<StringBuilder, T> accumulator() {
            return (builder, mark) -> {
                builder.append(String.join("", Collections.nCopies(valueholder[0] / mark.value(), mark.name())));
                valueholder[0] = valueholder[0] % mark.value();
            };
        }

        @Override
        public BinaryOperator<StringBuilder> combiner() { return null; }

        @Override
        public Function<StringBuilder, StringBuilder> finisher() { return Function.identity(); }

        @Override
        public Set<Characteristics> characteristics() { return Collections.singleton(Characteristics.IDENTITY_FINISH); }
    }
}

MySQL Check if username and password matches in Database

//set vars
$user = $_POST['user'];
$pass = md5($_POST['pass']);

if ($user&&$pass) 
{
//connect to db
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user'");

$numrows = mysql_num_rows($query);


if ($numrows!=0)
{
//while loop
  while ($row = mysql_fetch_assoc($query))
  {
    $dbusername = $row['username'];
    $dbpassword = $row['password'];
  }
  else
      die("incorrect username/password!");
}
else
  echo "user does not exist!";
} 
else
    die("please enter a username and password!");

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

I think that the usage of @Html.LabelForModel() should be explained in more detail.

The LabelForModel Method returns an HTML label element and the property name of the property that is represented by the model.

You could refer to the following code:

Code in model:

using System.ComponentModel;

[DisplayName("MyModel")]
public class MyModel
{
    [DisplayName("A property")]
    public string Test { get; set; }
}

Code in view:

@Html.LabelForModel()
<div class="form-group">

    @Html.LabelFor(model => model.Test, new { @class = "control-label col-md-2" })

    <div class="col-md-10">
        @Html.EditorFor(model => model.Test)
        @Html.ValidationMessageFor(model => model.Test)
    </div>
</div>

The output screenshot:

enter image description here

Reference to answer on the asp.net forum

Print multiple arguments in Python

This is what I do:

print("Total score for " + name + " is " + score)

Remember to put a space after for and before and after is.

How to get Spinner value?

Yes, you can register a listener via setOnItemSelectedListener(), as is demonstrated here.

How to receive JSON as an MVC 5 action method parameter

There are a couple issues here. First, you need to make sure to bind your JSON object back to the model in the controller. This is done by changing

data: JSON.stringify(usersRoles),

to

data: { model: JSON.stringify(usersRoles) },

Secondly, you aren't binding types correctly with your jquery call. If you remove

contentType: "application/json; charset=utf-8",

it will inherently bind back to a string.

All together, use the first ActionResult method and the following jquery ajax call:

    jQuery.ajax({
        type: "POST",
        url: "@Url.Action("AddUser")",
        dataType: "json",
        data: { model: JSON.stringify(usersRoles) },
        success: function (data) { alert(data); },
        failure: function (errMsg) {
        alert(errMsg);
        }
   });

Connection refused on docker container

In Docker Quickstart Terminal run following command: $ docker-machine ip 192.168.99.100

How can I make a .NET Windows Forms application that only runs in the System Tray?

It is very friendly framework for Notification Area Application... it is enough to add NotificationIcon to base form and change auto-generated code to code below:

public partial class Form1 : Form
{
    private bool hidden = false;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.ShowInTaskbar = false;
        //this.WindowState = FormWindowState.Minimized;
        this.Hide();
        hidden = true;
    }

    private void notifyIcon1_Click(object sender, EventArgs e)
    {
        if (hidden) // this.WindowState == FormWindowState.Minimized)
        {
            // this.WindowState = FormWindowState.Normal;
            this.Show();
            hidden = false;
        }
        else
        {
            // this.WindowState = FormWindowState.Minimized;
            this.Hide();
            hidden = true;
        }
    }
}

Keep only date part when using pandas.to_datetime

While I upvoted EdChum's answer, which is the most direct answer to the question the OP posed, it does not really solve the performance problem (it still relies on python datetime objects, and hence any operation on them will be not vectorized - that is, it will be slow).

A better performing alternative is to use df['dates'].dt.floor('d'). Strictly speaking, it does not "keep only date part", since it just sets the time to 00:00:00. But it does work as desired by the OP when, for instance:

  • printing to screen
  • saving to csv
  • using the column to groupby

... and it is much more efficient, since the operation is vectorized.

EDIT: in fact, the answer the OP's would have preferred is probably "recent versions of pandas do not write the time to csv if it is 00:00:00 for all observations".

Plot correlation matrix using pandas

For completeness, the simplest solution i know with seaborn as of late 2019, if one is using Jupyter:

import seaborn as sns
sns.heatmap(dataframe.corr())

Chrome Extension - Get DOM content

For those who tried gkalpak answer and it did not work,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

Is there a date format to display the day of the week in java?

Yep - 'E' does the trick

http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-E");
System.out.println(df.format(date));

React component not re-rendering on state change

I'd like to add to this the enormously simple, but oh so easily made mistake of writing:

this.state.something = 'changed';

... and then not understanding why it's not rendering and Googling and coming on this page, only to realize that you should have written:

this.setState({something: 'changed'});

React only triggers a re-render if you use setState to update the state.

MySQL CONCAT returns NULL if any field contain NULL

you can use if statement like below

select CONCAT(if(affiliate_name is null ,'',affiliate_name),'- ',if(model is null ,'',affiliate_name)) as model from devices

Automatically start a Windows Service on install

After refactoring a little bit, this is an example of a complete windows service installer with automatic start:

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace Example.of.name.space
{
[RunInstaller(true)]
public partial class ServiceInstaller : Installer
{
    private readonly ServiceProcessInstaller processInstaller;
    private readonly System.ServiceProcess.ServiceInstaller serviceInstaller;

    public ServiceInstaller()
    {
        InitializeComponent();
        processInstaller = new ServiceProcessInstaller();
        serviceInstaller = new System.ServiceProcess.ServiceInstaller();

        // Service will run under system account
        processInstaller.Account = ServiceAccount.LocalSystem;

        // Service will have Automatic Start Type
        serviceInstaller.StartType = ServiceStartMode.Automatic;

        serviceInstaller.ServiceName = "Windows Automatic Start Service";

        Installers.Add(serviceInstaller);
        Installers.Add(processInstaller);
        serviceInstaller.AfterInstall += ServiceInstaller_AfterInstall;            
    }
    private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
    {
        ServiceController sc = new ServiceController("Windows Automatic Start Service");
        sc.Start();
    }
}
}

Xampp localhost/dashboard

Wanna a list of folder in xampp?

Just delete or change the file index.php to index.txt. And you will get the list just typing url: localhost.

Browser screenshot

Numbering rows within groups in a data frame

I would like to add a data.table variant using the rank() function which provides the additional possibility to change the ordering and thus makes it a bit more flexible than the seq_len() solution and is pretty similar to row_number functions in RDBMS.

# Variant with ascending ordering
library(data.table)
dt <- data.table(df)
dt[, .( val
   , num = rank(val))
    , by = list(cat)][order(cat, num),]

    cat        val num
 1: aaa 0.05638315   1
 2: aaa 0.25767250   2
 3: aaa 0.30776611   3
 4: aaa 0.46854928   4
 5: aaa 0.55232243   5
 6: bbb 0.17026205   1
 7: bbb 0.37032054   2
 8: bbb 0.48377074   3
 9: bbb 0.54655860   4
10: bbb 0.81240262   5
11: ccc 0.28035384   1
12: ccc 0.39848790   2
13: ccc 0.62499648   3
14: ccc 0.76255108   4

# Variant with descending ordering
dt[, .( val
   , num = rank(-val))
    , by = list(cat)][order(cat, num),]

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

DP size of any device is (actual resolution / density conversion factor).

Density conversion factor for density buckets are as follows:

ldpi: 0.75
mdpi: 1.0 (base density)
hdpi: 1.5
xhdpi: 2.0
xxhdpi: 3.0
xxxhdpi: 4.0

Examples of resolution/density conversion to DP:

  • ldpi device of 240 X 320 px will be of 320 X 426.66 DP. 240 / 0.75 = 320 dp 320 / 0.75 = 426.66 dp

  • xxhdpi device of 1080 x 1920 pixels (Samsung S4, S5) will be of 360 X 640 dp. 1080 / 3 = 360 dp 1920 / 3 = 640 dp

This image show more:

Density

For more details about DIP read here.

ERROR 2006 (HY000): MySQL server has gone away

The solution is increasing the values given the wait_timeout and the connect_timeout parameters in your options file, under the [mysqld] tag.

I had to recover a 400MB mysql backup and this worked for me (the values I've used below are a bit exaggerated, but you get the point):

[mysqld]
port=3306
explicit_defaults_for_timestamp = TRUE
connect_timeout = 1000000
net_write_timeout = 1000000
wait_timeout = 1000000
max_allowed_packet = 1024M
interactive_timeout = 1000000
net_buffer_length = 200M
net_read_timeout = 1000000
set GLOBAL delayed_insert_timeout=100000

Blockquote

Installing Python 3 on RHEL

If you want official RHEL packages you can use RHSCL (Red Hat Software Collections)

More details:

You have to have access to Red Hat Customer Portal to read full articles.

Can you have multiline HTML5 placeholder text in a <textarea>?

Watermark solution in the original post works great. Thanks for it. In case anyone needs it, here is an angular directive for it.

(function () {
  'use strict';

  angular.module('app')
    .directive('placeholder', function () {
      return {
        restrict: 'A',
        link:     function (scope, element, attributes) {
          if (element.prop('nodeName') === 'TEXTAREA') {
            var placeholderText = attributes.placeholder.trim();

            if (placeholderText.length) {
              // support for both '\n' symbol and an actual newline in the placeholder element
              var placeholderLines = Array.prototype.concat
                .apply([], placeholderText.split('\n').map(line => line.split('\\n')))
                .map(line => line.trim());

              if (placeholderLines.length > 1) {
                element.watermark(placeholderLines.join('<br>\n'));
              }
            }
          }
        }
      };
    });
}());

Concatenating multiple text files into a single file in Bash

The Windows shell command type can do this:

type *.txt >outputfile

Type type command also writes file names to stderr, which are not captured by the > redirect operator (but will show up on the console).

How to enable explicit_defaults_for_timestamp?

I'm Using Windows 8.1 and I use this command

c:\wamp\bin\mysql\mysql5.6.12\bin\mysql.exe

instead of

 c:\wamp\bin\mysql\mysql5.6.12\bin\mysqld

and it works fine..

What is "entropy and information gain"?

I assume entropy was mentioned in the context of building decision trees.

To illustrate, imagine the task of learning to classify first-names into male/female groups. That is given a list of names each labeled with either m or f, we want to learn a model that fits the data and can be used to predict the gender of a new unseen first-name.

name       gender
-----------------        Now we want to predict 
Ashley        f              the gender of "Amro" (my name)
Brian         m
Caroline      f
David         m

First step is deciding what features of the data are relevant to the target class we want to predict. Some example features include: first/last letter, length, number of vowels, does it end with a vowel, etc.. So after feature extraction, our data looks like:

# name    ends-vowel  num-vowels   length   gender
# ------------------------------------------------
Ashley        1         3           6        f
Brian         0         2           5        m
Caroline      1         4           8        f
David         0         2           5        m

The goal is to build a decision tree. An example of a tree would be:

length<7
|   num-vowels<3: male
|   num-vowels>=3
|   |   ends-vowel=1: female
|   |   ends-vowel=0: male
length>=7
|   length=5: male

basically each node represent a test performed on a single attribute, and we go left or right depending on the result of the test. We keep traversing the tree until we reach a leaf node which contains the class prediction (m or f)

So if we run the name Amro down this tree, we start by testing "is the length<7?" and the answer is yes, so we go down that branch. Following the branch, the next test "is the number of vowels<3?" again evaluates to true. This leads to a leaf node labeled m, and thus the prediction is male (which I happen to be, so the tree predicted the outcome correctly).

The decision tree is built in a top-down fashion, but the question is how do you choose which attribute to split at each node? The answer is find the feature that best splits the target class into the purest possible children nodes (ie: nodes that don't contain a mix of both male and female, rather pure nodes with only one class).

This measure of purity is called the information. It represents the expected amount of information that would be needed to specify whether a new instance (first-name) should be classified male or female, given the example that reached the node. We calculate it based on the number of male and female classes at the node.

Entropy on the other hand is a measure of impurity (the opposite). It is defined for a binary class with values a/b as:

Entropy = - p(a)*log(p(a)) - p(b)*log(p(b))

This binary entropy function is depicted in the figure below (random variable can take one of two values). It reaches its maximum when the probability is p=1/2, meaning that p(X=a)=0.5 or similarlyp(X=b)=0.5 having a 50%/50% chance of being either a or b (uncertainty is at a maximum). The entropy function is at zero minimum when probability is p=1 or p=0 with complete certainty (p(X=a)=1 or p(X=a)=0 respectively, latter implies p(X=b)=1).

https://en.wikipedia.org/wiki/File:Binary_entropy_plot.svg

Of course the definition of entropy can be generalized for a discrete random variable X with N outcomes (not just two):

entropy

(the log in the formula is usually taken as the logarithm to the base 2)


Back to our task of name classification, lets look at an example. Imagine at some point during the process of constructing the tree, we were considering the following split:

     ends-vowel
      [9m,5f]          <--- the [..,..] notation represents the class
    /          \            distribution of instances that reached a node
   =1          =0
 -------     -------
 [3m,4f]     [6m,1f]

As you can see, before the split we had 9 males and 5 females, i.e. P(m)=9/14 and P(f)=5/14. According to the definition of entropy:

Entropy_before = - (5/14)*log2(5/14) - (9/14)*log2(9/14) = 0.9403

Next we compare it with the entropy computed after considering the split by looking at two child branches. In the left branch of ends-vowel=1, we have:

Entropy_left = - (3/7)*log2(3/7) - (4/7)*log2(4/7) = 0.9852

and the right branch of ends-vowel=0, we have:

Entropy_right = - (6/7)*log2(6/7) - (1/7)*log2(1/7) = 0.5917

We combine the left/right entropies using the number of instances down each branch as weight factor (7 instances went left, and 7 instances went right), and get the final entropy after the split:

Entropy_after = 7/14*Entropy_left + 7/14*Entropy_right = 0.7885

Now by comparing the entropy before and after the split, we obtain a measure of information gain, or how much information we gained by doing the split using that particular feature:

Information_Gain = Entropy_before - Entropy_after = 0.1518

You can interpret the above calculation as following: by doing the split with the end-vowels feature, we were able to reduce uncertainty in the sub-tree prediction outcome by a small amount of 0.1518 (measured in bits as units of information).

At each node of the tree, this calculation is performed for every feature, and the feature with the largest information gain is chosen for the split in a greedy manner (thus favoring features that produce pure splits with low uncertainty/entropy). This process is applied recursively from the root-node down, and stops when a leaf node contains instances all having the same class (no need to split it further).

Note that I skipped over some details which are beyond the scope of this post, including how to handle numeric features, missing values, overfitting and pruning trees, etc..

Why can't I change my input value in React even with the onChange listener

Unlike in the case of Angular, in React.js you need to update the state manually. You can do something like this:

<input
    className="form-control"
    type="text" value={this.state.name}
    id={'todoName' + this.props.id}
    onChange={e => this.onTodoChange(e.target.value)}
/>

And then in the function:

onTodoChange(value){
        this.setState({
             name: value
        });
    }

Also, you can set the initial state in the constructor of the component:

  constructor (props) {
    super(props);
    this.state = {
        updatable: false,
        name: props.name,
        status: props.status
    };
  }

How to delete columns in a CSV file?

It depends on how you store the parsed CSV, but generally you want the del operator.

If you have an array of dicts:

input = [ {'day':01, 'month':04, 'year':2001, ...}, ... ]
for E in input: del E['year']

If you have an array of arrays:

input = [ [01, 04, 2001, ...],
          [...],
          ...
        ]
for E in input: del E[2]

Multiplication on command line terminal

The classical solution is:

 expr 5 \* 5

expr will only work with integer operands. Another nice option is:

 echo 5 5\*p | dc

dc can be made to work with non-integer operands.

How do you Sort a DataTable given column and direction?

If you've only got one DataView, you can sort using that instead:

table.DefaultView.Sort = "columnName asc";

Haven't tried it, but I guess you can do this with any number of DataViews, as long as you reference the right one.

How do I print the content of a .txt file in Python?

It's pretty simple

#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)

Presenting snapshot from my visual studio IDE.

enter image description here

WordPress Get the Page ID outside the loop

If you're using pretty permalinks, get_query_var('page_id') won't work.

Instead, get the queried object ID from the global $wp_query:

// Since 3.1 - recommended!
$page_object = get_queried_object();
$page_id     = get_queried_object_id();


// "Dirty" pre 3.1
global $wp_query;

$page_object = $wp_query->get_queried_object();
$page_id     = $wp_query->get_queried_object_id();

How to sort a list of strings?

Suppose s = "ZWzaAd"

To sort above string the simple solution will be below one.

print ''.join(sorted(s))

Create Log File in Powershell

I believe this is the simplest way of putting all what it is on the screen into a file. It is a native PS CmdLet so you don't have to change anything in yout script

Start-Transcript -Path Computer.log

Write-Host "everything will end up in Computer.log"

Stop-Transcript

$watch an object

Try this:

function MyController($scope) {
    $scope.form = {
        name: 'my name',
        surname: 'surname'
    }

    function track(newValue, oldValue, scope) {
        console.log('changed');
    };

    $scope.$watch('form.name', track);
}

In android app Toolbar.setTitle method has no effect – application name is shown as title

To set the title for each Navbar fragment title

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
    myView = inflater.inflate(R.layout.second_layout, container, false);
    getActivity().setTitle("title");

    return myView;
}

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Here is a simple example that should let you keep going add somethink that would act as a placeholder to your winform can be TableLayoutPanel

and then just add controls to it

   for ( int i = 0; i < COUNT; i++ ) {


    Label lblTitle = new Label();
    lblTitle.Text = i+"Your Text";
    youlayOut.Controls.Add( lblTitle, 0, i );

    TextBox txtValue = new TextBox();
    youlayOut.Controls.Add( txtValue, 2, i );
}

Why doesn't Java allow overriding of static methods?

Here is a simple explanation. A static method is associated with a class while an instance method is associated with a particular object. Overrides allow calling the different implementation of the overridden methods associated with the particular object. So it is counter-intuitive to override static method which is not even associated with objects but the class itself in the first place. So static methods cannot be overridden based on what object is calling it, it will always be associated with the class where it was created.

Logical XOR operator in C++?

I use "xor" (it seems it's a keyword; in Code::Blocks at least it gets bold) just as you can use "and" instead of && and "or" instead of ||.

if (first xor second)...

Yes, it is bitwise. Sorry.

Setting a max character length in CSS

This post is for a CSS solution, but the post is quite old, so just in case others stumble on this and are using a modern JS framework such as Angular 4+, there is a simple way to do this through Angular Pipes without having to mess around with CSS.

There are probably "React" or "Vue" ways of doing this as well. This is just to showcase how it could be done within a framework.

truncate-text.pipe.ts

/**
 * Helper to truncate text using JS in view only.
 *
 * This is pretty difficult to do reliably with CSS, especially when there are
 * multiple lines.
 *
 * Example: {{ value | truncateText:maxLength }} or {{ value | truncateText:45 }}
 *
 * If maxLength is not provided, the value will be returned without any truncating. If the
 * text is shorter than the maxLength, the text will be returned untouched. If the text is greater
 * than the maxLength, the text will be returned with 3 characters less than the max length plus
 * some ellipsis at the end to indicate truncation.
 *
 * For example: some really long text I won't bother writing it all ha...
 */
@Pipe({ name: 'truncateText' })
export class TruncateTextPipe implements PipeTransform {
  transform(value: string, ...args: any[]): any {
    const maxLength = args[0]
    const maxLengthNotProvided = !maxLength
    const isShorterThanMaximumLength = value.length < maxLength
    if (maxLengthNotProvided || isShorterThanMaximumLength) {
      return value
    }
    const shortenedString = value.substr(0, maxLength - 3)
    return `${shortenedString}...`
  }
}

app.component.html

<h1>{{ application.name | truncateText:45 }}</h1>

Wait until an HTML5 video loads

call function on load:

<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">

get video duration

var video = document.getElementById("video");
var duration = video.duration;

Expand and collapse with angular js

You can solve this fully in the html:

<div>
  <input ng-model=collapse type=checkbox>Title
  <div ng-show=collapse>
     Only shown when checkbox is clicked
  </div>
</div>

This also works well with ng-repeat since it will create a local scope for each member.

<table>
  <tbody ng-repeat='m in members'>
    <tr>
       <td><input type=checkbox ng-model=collapse></td>
       <td>{{m.title}}</td>
    </tr>
    <tr ng-show=collapse>
      <td> </td>
      <td>{{ m.content }}</td>
    </tr>
  </tbody>
</table>

Be aware that even though a repeat has its own scope, initially it will inherit the value from collapse from super scopes. This allows you to set the initial value in one place but it can be surprising.

You can of course restyle the checkbox. See http://jsfiddle.net/azD5m/5/

Updated fiddle: http://jsfiddle.net/azD5m/374/ Original fiddle used closing </input> tags to add the HTML text label instead of using <label> tags.

Blur or dim background when Android PopupWindow active

Another trick is to use 2 popup windows instead of one. The 1st popup window will simply be a dummy view with translucent background which provides the dim effect. The 2nd popup window is your intended popup window.

Sequence while creating pop up windows: Show the dummy pop up window 1st and then the intended popup window.

Sequence while destroying: Dismiss the intended pop up window and then the dummy pop up window.

The best way to link these two is to add an OnDismissListener and override the onDismiss() method of the intended to dimiss the dummy popup window from their.

Code for the dummy popup window:

fadepopup.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:id="@+id/fadePopup"
    android:background="#AA000000">
</LinearLayout>

Show fade popup to dim the background

private PopupWindow dimBackground() {

    LayoutInflater inflater = (LayoutInflater) EPGGRIDActivity.this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View layout = inflater.inflate(R.layout.fadepopup,
            (ViewGroup) findViewById(R.id.fadePopup));
    PopupWindow fadePopup = new PopupWindow(layout, windowWidth, windowHeight, false);
    fadePopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
    return fadePopup;
}

What is the difference between MacVim and regular Vim?

unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(

Pandas DataFrame Groupby two columns and get counts

Inserting data into a pandas dataframe and providing column name.

import pandas as pd
df = pd.DataFrame([['A','C','A','B','C','A','B','B','A','A'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['Alphabet','Words']]
print(df)   #printing dataframe.

This is our printed data:

enter image description here

For making a group of dataframe in pandas and counter,
You need to provide one more column which counts the grouping, let's call that column as, "COUNTER" in dataframe.

Like this:

df['COUNTER'] =1       #initially, set that counter to 1.
group_data = df.groupby(['Alphabet','Words'])['COUNTER'].sum() #sum function
print(group_data)

OUTPUT:

enter image description here

TypeError: unsupported operand type(s) for /: 'str' and 'str'

I would have written:

percent = 100
while True:
     try:
        pyc = int(input('enter pyc :'))
        tpy = int(input('enter tpy:'))
        percent = (pyc / tpy) * percent
        break
     except ZeroDivisionError as detail:
        print 'Handling run-time error:', detail

How can I have linebreaks in my long LaTeX equations?

Use eqnarray and \nonumber

example:

\begin{eqnarray}
    sample = R(s,\pi(s),s') + \gamma V^{\pi} (s') \nonumber \\
    \label{eq:temporal-difference}
     V^{\pi}_{k+1}(s) = (1-\alpha)V^{\pi}(s) - \alpha[sample]
\end{eqnarray}

Avoid dropdown menu close on click inside

You can stop click on the dropdown from propagating and then manually reimplement the carousel controls using carousel javascript methods.

$('ul.dropdown-menu.mega-dropdown-menu').on('click', function(event) {
    event.stopPropagation();
});

$('a.left').click(function () {
    $('#carousel').carousel('prev');
});

$('a.right').click(function () {
    $('#carousel').carousel('next');
});

$('ol.carousel-indicators li').click(function (event) {
    var index = $(this).data("slide-to");
    $('#carousel').carousel(index);
});

Here is the jsfiddle.

Checking length of dictionary object

What I do is use Object.keys() to return a list of all the keys and then get the length of that

Object.keys(dictionary).length

How to prevent rm from reporting that a file was not found?

As far as rm -f doing "anything else", it does force (-f is shorthand for --force) silent removal in situations where rm would otherwise ask you for confirmation. For example, when trying to remove a file not writable by you from a directory that is writable by you.

Custom HTTP headers : naming conventions

The recommendation is was to start their name with "X-". E.g. X-Forwarded-For, X-Requested-With. This is also mentioned in a.o. section 5 of RFC 2047.


Update 1: On June 2011, the first IETF draft was posted to deprecate the recommendation of using the "X-" prefix for non-standard headers. The reason is that when non-standard headers prefixed with "X-" become standard, removing the "X-" prefix breaks backwards compatibility, forcing application protocols to support both names (E.g, x-gzip & gzip are now equivalent). So, the official recommendation is to just name them sensibly without the "X-" prefix.


Update 2: On June 2012, the deprecation of recommendation to use the "X-" prefix has become official as RFC 6648. Below are cites of relevance:

3. Recommendations for Creators of New Parameters

...

  1. SHOULD NOT prefix their parameter names with "X-" or similar constructs.

4. Recommendations for Protocol Designers

...

  1. SHOULD NOT prohibit parameters with an "X-" prefix or similar constructs from being registered.

  2. MUST NOT stipulate that a parameter with an "X-" prefix or similar constructs needs to be understood as unstandardized.

  3. MUST NOT stipulate that a parameter without an "X-" prefix or similar constructs needs to be understood as standardized.

Note that "SHOULD NOT" ("discouraged") is not the same as "MUST NOT" ("forbidden"), see also RFC 2119 for another spec on those keywords. In other words, you can keep using "X-" prefixed headers, but it's not officially recommended anymore and you may definitely not document them as if they are public standard.


Summary:

  • the official recommendation is to just name them sensibly without the "X-" prefix
  • you can keep using "X-" prefixed headers, but it's not officially recommended anymore and you may definitely not document them as if they are public standard

Search all the occurrences of a string in the entire project in Android Studio

What you want to reach is that, I believe:

  • cmd + O for classes.
  • cmd + shift + O for files.
  • cmd + alt + O for symbols. "wonderful shortcut!"

Besides shift + cmd + f for find in path && double shift to search anywhere. Play with those and you will know what satisfy your need.

VBA vlookup reference in different sheet

Your code work fine, provided the value in Sheet2!D2 exists in Sheet1!A:A. If it does not then error 1004 is raised.

To handle this case, try

Sub Demo()
    Dim MyStringVar1 As Variant
    On Error Resume Next
    MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
      Worksheets("Sheet1").Range("A:C"), 1, False)
    On Error GoTo 0
    If IsEmpty(MyStringVar1) Then
        MsgBox "Value not found!"
    End If

    Range("E2") = MyStringVar1

End Sub

How to join two JavaScript Objects, without using JQUERY

There are couple of different solutions to achieve this:

1 - Native javascript for-in loop:

const result = {};
let key;

for (key in obj1) {
  if(obj1.hasOwnProperty(key)){
    result[key] = obj1[key];
  }
}

for (key in obj2) {
  if(obj2.hasOwnProperty(key)){
    result[key] = obj2[key];
  }
}

2 - Object.keys():

const result = {};

Object.keys(obj1)
  .forEach(key => result[key] = obj1[key]);

Object.keys(obj2)
  .forEach(key => result[key] = obj2[key]);

3 - Object.assign():
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)

const result = Object.assign({}, obj1, obj2);

4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):

Defined in several sections of the specification: Array Initializer, Argument Lists

Using this new syntax you could join/merge different objects into one object like this:

const result = {
  ...obj1,
  ...obj2,
};

5 - jQuery.extend(target, obj1, obj2):

Merge the contents of two or more objects together into the first object.

const target = {};

$.extend(target, obj1, obj2);

6 - jQuery.extend(true, target, obj1, obj2):

Run a deep merge of the contents of two or more objects together into the target. Passing false for the first argument is not supported.

const target = {};

$.extend(true, target, obj1, obj2);

7 - Lodash _.assignIn(object, [sources]): also named as _.extend:

const result = {};

_.assignIn(result, obj1, obj2);

8 - Lodash _.merge(object, [sources]):

const result = _.merge(obj1, obj2);

There are a couple of important differences between lodash's merge function and Object.assign:

1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign only merges the first level. For instance:

_.isEqual(_.merge({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
}), {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // true

BUT:

const result = Object.assign({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
});
_.isEqual(result, {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // false
// AND
_.isEqual(result, {
  x: {
    y: {
      key2: 'value2',
    },
  },
}); // true

2- Another difference has to do with how Object.assign and _.merge interpret the undefined value:

_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false

BUT:

_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true

Update 1:

When using for in loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype or even Object.prototype. To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key) to mke sure the key is actually part of the object you are iterating over.


Update 2:

I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.


Update 3:
I added the difference between Object.assign and _.merge.

How to generate List<String> from SQL query?

Loop through the Items and Add to the Collection. You can use the Add method

List<string>items=new List<string>();
using (var con= new SqlConnection("yourConnectionStringHere")
{
    string qry="SELECT Column1 FROM Table1";
    var cmd= new SqlCommand(qry, con);
    cmd.CommandType = CommandType.Text;
    con.Open();
    using (SqlDataReader objReader = cmd.ExecuteReader())
    {
        if (objReader.HasRows)
        {              
            while (objReader.Read())
            {
              //I would also check for DB.Null here before reading the value.
               string item= objReader.GetString(objReader.GetOrdinal("Column1"));
               items.Add(item);                  
            }
        }
    }
}

Javascript array sort and unique

The fastest and simpleness way to do this task.

const N = Math.pow(8, 8)
let data = Array.from({length:  N}, () => Math.floor(Math.random() * N))
let newData = {}
let len = data.length

// the magic
while (len--) {
    newData[data[len]] = true
}

ES6 class variable alternatives

You can mimic es6 classes behaviour... and use your class variables :)

Look mum... no classes!

// Helper
const $constructor = Symbol();
const $extends = (parent, child) =>
  Object.assign(Object.create(parent), child);
const $new = (object, ...args) => {
  let instance = Object.create(object);
  instance[$constructor].call(instance, ...args);
  return instance;
}
const $super = (parent, context, ...args) => {
  parent[$constructor].call(context, ...args)
}
// class
var Foo = {
  classVariable: true,

  // constructor
  [$constructor](who){
    this.me = who;
    this.species = 'fufel';
  },

  // methods
  identify(){
    return 'I am ' + this.me;
  }
}

// class extends Foo
var Bar = $extends(Foo, {

  // constructor
  [$constructor](who){
    $super(Foo, this, who);
    this.subtype = 'barashek';
  },

  // methods
  speak(){
    console.log('Hello, ' + this.identify());
  },
  bark(num){
    console.log('Woof');
  }
});

var a1 = $new(Foo, 'a1');
var b1 = $new(Bar, 'b1');
console.log(a1, b1);
console.log('b1.classVariable', b1.classVariable);

I put it on GitHub

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

Question mark characters displaying within text, why is this?

The following articles will be useful

http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html

http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html

After you connect to the database issue the following command:

SET NAMES 'utf8';

Ensure that your web page also uses the UTF-8 encoding:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

PHP also offers several function that will be useful for conversions:

http://us3.php.net/manual/en/function.iconv.php

http://us.php.net/mb_convert_encoding

What's the fastest way to delete a large folder in Windows?

use fastcopy, a free tool. it has a delete option that is a lot faster then the way windows deletes files.

iFrame Height Auto (CSS)

I had this same issue but found the following that works great:

The key to creating a responsive YouTube embed is with padding and a container element, which allows you to give it a fixed aspect ratio. You can also use this technique with most other iframe-based embeds, such as slideshows.

Here is what a typical YouTube embed code looks like, with fixed width and height:

 <iframe width="560" height="315" src="//www.youtube.com/embed/yCOY82UdFrw" 
 frameborder="0" allowfullscreen></iframe>

It would be nice if we could just give it a 100% width, but it won't work as the height remains fixed. What you need to do is wrap it in a container like so (note the class names and removal of the width and height):

 <div class="container">
 <iframe src="//www.youtube.com/embed/yCOY82UdFrw" 
 frameborder="0" allowfullscreen class="video"></iframe>
 </div>

And use the following CSS:

 .container {
    position: relative;
     width: 100%;
     height: 0;
     padding-bottom: 56.25%;
 }
 .video {
     position: absolute;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
 }

Here is the page I found the solution on:

https://www.h3xed.com/web-development/how-to-make-a-responsive-100-width-youtube-iframe-embed

Depending on your aspect ratio, you will probably need to adjust the padding-bottom: 56.25%; to get the height right.

React-Native Button style not work

As the answer by @plaul mentions TouchableOpacity, here is an example of how you can use that;

  <TouchableOpacity
    style={someStyles}
    onPress={doSomething}
  >
    <Text>Press Here</Text>
  </TouchableOpacity>

How to select the comparison of two columns as one column in Oracle

I stopped using DECODE several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN.

However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.

select a, b, decode(a, b, 'true', 'false') as same
  from t;

     A       B  SAME
------  ------  -----
     1       1  true
     1       0  false
     1          false
  null    null  true  

Java int to String - Integer.toString(i) vs new Integer(i).toString()

In terms of performance measurement, if you are considering the time performance then the Integer.toString(i); is expensive if you are calling less than 100 million times. Else if it is more than 100 million calls then the new Integer(10).toString() will perform better.

Below is the code through u can try to measure the performance,

public static void main(String args[]) {
            int MAX_ITERATION = 10000000;
        long starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s = Integer.toString(10);
        }
        long endtime = System.currentTimeMillis();
        System.out.println("diff1: " + (endtime-starttime));

        starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s1 = new Integer(10).toString();
        }
        endtime = System.currentTimeMillis();
        System.out.println("diff2: " + (endtime-starttime));
    }

In terms of memory, the

new Integer(i).toString();

will take more memory as it will create the object each time, so memory fragmentation will happen.

Is there an Eclipse plugin to run system shell in the Console?

You can also use the Termial view to ssh/telnet to your local machine. Doesn't have that funny input box for commands.

String to HtmlDocument

I've adapted Nikhil's answer somewhat to simplify it. Admittedly, I have not run it through a .net compiler and there are likely very good reasons for the lines Nikhil put in which I have omitted. However, at least in my use case (a very simple page) they were unnecessary.

My use case was for a quick powershell script:

$htmlText = $(New-Object 
System.Net.WebClient).DownloadString("<URI HERE>") #Get the HTML document from a webserver
$browser = New-Object System.Windows.Forms.WebBrowser
$browser.DocumentText = $htmlText
$browser.Document.Write($htmlText)
$response = $browser.document

For my case, this returned an HTMLDocument object with HTMLElement objects in it, instead of __ComObject object types (which are a challenge to use in powershell class code) returned by a call to Invoke-WebRequest in PS 5.1.14393.1944

I believe the equivalent C# code is:

public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
{
    WebBrowser browser = new WebBrowser();
    browser.DocumentText = html;
    browser.Document.Write(html);
    return browser.Document;
}

Select where count of one field is greater than one

It should also be mentioned that the "pk" should be a key field. The self-join

SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk 

by Bill Karwin give you all the records that are duplicates which is what I wanted. Because some have more than two, you can get the same record more than once. I wrote all to another table with the same fields to get rid of the same records by key fields suppression. I tried

SELECT * FROM db.table HAVING COUNT(someField) > 1

above first. The data returned from it give only one of the duplicates, less than 1/2 of what this gives you but the count is good if that is all you want.

chart.js load totally new data

According to docs, clear() clears the canvas. Think of it as the Eraser tool in Paint. It has nothing to do with the data currently loaded in the chart instance.

Destroying the instance and creating a new one is wasteful. Instead, use API methods removeData() and addData(). These will add/remove a single segment to/from the chart instance. So if you want to load completely new data, just loop a chart data array, and call removeData(index) (array indexes should correspond to current segment indexes). Then, use addData(index) to fill it with the new data. I suggest wrapping the two methods for looping the data, as they expect a single segment index. I use resetChart and updateChart. Before continuing, make sure you check Chart.js latest version and documentation. They may have added new methods for replacing the data completely.

How to center a Window in Java?

This should work in all versions of Java

public static void centreWindow(Window frame) {
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
    frame.setLocation(x, y);
}

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

Specifying content of an iframe instead of the src attribute to a page

In combination with what Guffa described, you could use the technique described in Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.

'module' object has no attribute 'DataFrame'

Please make sure that your file name should not be panda.py or pd.py. Also, make sure that panda is there in your Lib/site-packages directory, if not that you need to install panda using below command line:

pip install pandas

if you work with proxy then try calling below in command prompt:

python.exe -m pip install pandas --proxy="YOUR_PROXY_IP:PORT"

Android - set TextView TextStyle programmatically?

Search for setTextAppearance or also setTextTypeface. There is similar question on stackoverflow: How to change a TextView's style at runtime

How do I compile jrxml to get jasper?

There are three ways to compile jrxml to jasper.

  1. You can do direct compile via compile button (hammer logo) on iReport designer.

  2. You can use ant to compile as shown in the Ant Compile Sample.

    <target name="compile1"> 
      <mkdir dir="./build/reports"/> 
      <jrc 
        srcdir="./reports"
        destdir="./build/reports"
        tempdir="./build/reports"
        keepjava="true"
        xmlvalidation="true">
       <classpath refid="runClasspath"/>
       <include name="**/*.jrxml"/>
      </jrc>
    </target>
    

    Below is the report compile task on my current project.

    alt text

    addition from Daniel Rikowski :

  3. You can also use the JasperCompileManager class to compile from your java code.

    JasperCompileManager.compileReportToFile(
                    "our_jasper_template.jrxml", // the path to the jrxml file to compile
                    "our_compiled_template.jasper"); // the path and name we want to save the compiled file to
    

Decimal to Hexadecimal Converter in Java

I will use

Long a = Long.parseLong(cadenaFinal, 16 );

since there is some hex that can be larguer than intenger and it will throw an exception

How do I replace part of a string in PHP?

Simply use str_replace:

$text = str_replace(' ', '_', $text);

You would do this after your previous substr and strtolower calls, like so:

$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);

If you want to get fancy, though, you can do it in one line:

$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));

Nested jQuery.each() - continue/break

I've used a "breakout" pattern for this:

$(sentences).each(function() {
    var breakout;
    var s = this;
    alert(s);
    $(words).each(function(i) {
        if (s.indexOf(this) > -1)
        {
            alert('found ' + this);
            return breakout = false;
        }
    });
    return breakout;
});

This works nicely to any nesting depth. breakout is a simple flag. It will stay undefined unless and until you set it to false (as I do in my return statement as illustrated above). All you have to do is:

  1. declare it in your outermost closure: var breakout;
  2. add it to your return false statement(s): return breakout = false
  3. return breakout in your outer closure(s).

Not too inelegant, right? ...works for me anyway.

Attaching click event to a JQuery object not yet added to the DOM

I am really surprised that no one has posted this yet

$(document).on('click','#my-butt', function(){
   console.log('document is always there');
}) 

If you are unsure about what elements are going to be on that page at that time just attach it to document.

Note: this is sub-optimal from performance perspective - to get maximum speed one should try to attach to the nearest parent of element that is going to be inserted.

Displaying the Error Messages in Laravel after being Redirected from controller

@if ($errors->has('category'))
    <span class="error">{{ $errors->first('category') }}</span>
@endif

C# get and set properties for a List Collection

Your setters are strange, which is why you may be seeing a problem.

First, consider whether you even need these setters - if so, they should take a List<string>, not just a string:

set
{
    _subHead = value;
}

These lines:

newSec.subHead.Add("test string");

Are calling the getter and then call Add on the returned List<string> - the setter is not invoked.

What is (x & 1) and (x >>= 1)?

These are Bitwise Operators (reference).

x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.

x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift.

Note: The value of the most significant bit after the shift is zero for values of unsigned type. For values of signed type the most significant bit is copied from the sign bit of the value prior to shifting as part of sign extension, so the loop will never finish if x is a signed type, and the initial value is negative.

Write to Windows Application Event Log

As stated in MSDN (eg. https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog(v=vs.110).aspx ), checking an non existing source and creating a source requires admin privilege.

It is however possible to use the source "Application" without. In my test under Windows 2012 Server r2, I however get the following log entry using "Application" source:

The description for Event ID xxxx from source Application cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer. If the event originated on another computer, the display information had to be saved with the event. The following information was included with the event: {my event entry message} the message resource is present but the message is not found in the string/message table

I defined the following method to create the source:

    private string CreateEventSource(string currentAppName)
    {
        string eventSource = currentAppName;
        bool sourceExists;
        try
        {
            // searching the source throws a security exception ONLY if not exists!
            sourceExists = EventLog.SourceExists(eventSource);
            if (!sourceExists)
            {   // no exception until yet means the user as admin privilege
                EventLog.CreateEventSource(eventSource, "Application");
            }
        }
        catch (SecurityException)
        {
            eventSource = "Application";
        }

        return eventSource;
    }

I am calling it with currentAppName = AppDomain.CurrentDomain.FriendlyName

It might be possible to use the EventLogPermission class instead of this try/catch but not sure we can avoid the catch.

It is also possible to create the source externally, e.g in elevated Powershell:

New-EventLog -LogName Application -Source MyApp

Then, using 'MyApp' in the method above will NOT generate exception and the EventLog can be created with that source.

Unable to make the session state request to the session state server

Not the best answer, but it's an option anyway:

Comment the given line in the web.config.

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

I just thought I'd share that I found the answer to my own question.

Writing out my problem made it even more clear to me, and I further investigated into where I thought my problem lay: the ssh key

Turns out I was right. The issue wasn't with the key itself, but rather that I had not added it to my local Mac's list of known ssh keys. So even though my Heroku account had the correct key uploaded, my Mac could not authenticate with it because it could not find that key on my computer. The solution?

ssh-add ~/.ssh/id_rsa
#and, to confirm it's been added to the known list of keys
ssh-add -l

I would like to give credit to https://help.github.com/articles/error-permission-denied-publickey for being a good reference.

Setting Margin Properties in code

To use Thickness you need to create/change your project .NET framework platform version to 4.5. becaus this method available only in version 4.5. (Also you can just download PresentationFramework.dll and give referense to this dll, without create/change your .NET framework version to 4.5.)

But if you want to do this simple, You can use this code:

MyControl.Margin = new Padding(int left, int top, int right, int bottom);

also

MyControl.Margin = new Padding(int all);

This is simple and no needs any changes to your project

jQuery: Selecting by class and input type

Try this:

$("input:checkbox").hasClass("myClass");

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

<form>
  <label for="company">
    <span>Company Name</span>
    <input type="text" id="company" />
  </label>
  <label for="contact">
    <span>Contact Name</span>
    <input type="text" id="contact" />
  </label>
</form>

label { width: 200px; float: left; margin: 0 20px 0 0; }
span { display: block; margin: 0 0 3px; font-size: 1.2em; font-weight: bold; }
input { width: 200px; border: 1px solid #000; padding: 5px; }

Illustrated at http://jsfiddle.net/H3y8j/

How to break line in JavaScript?

I was facing the same problem. For my solution, I added br enclosed between 2 brackets < > enclosed in double quotation marks, and preceded and followed by the + sign:

+"<br>"+

Try this in your browser and see, it certainly works in my Internet Explorer.

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

To be absolutely correct you should put all the names into the SAN field.

The CN field should contain a Subject Name not a domain name, but when the Netscape found out this SSL thing, they missed to define its greatest market. Simply there was not certificate field defined for the Server URL.

This was solved to put the domain into the CN field, and nowadays usage of the CN field is deprecated, but still widely used. The CN can hold only one domain name.

The general rules for this: CN - put here your main URL (for compatibility) SAN - put all your domain here, repeat the CN because its not in right place there, but its used for that...

If you found a correct implementation, the answers for your questions will be the followings:

  • Has this setup a special meaning, or any [dis]advantages over setting both CNs? You cant set both CNs, because CN can hold only one name. You can make with 2 simple CN certificate instead one CN+SAN certificate, but you need 2 IP addresses for this.

  • What happens on server-side if the other one, host.domain.tld, is being requested? It doesn't matter whats happen on server side.

In short: When a browser client connects to this server, then the browser sends encrypted packages, which are encrypted with the public key of the server. Server decrypts the package, and if server can decrypt, then it was encrypted for the server.

The server doesn't know anything from the client before decrypt, because only the IP address is not encrypted trough the connection. This is why you need 2 IPs for 2 certificates. (Forget SNI, there is too much XP out there still now.)

On client side the browser gets the CN, then the SAN until all of the are checked. If one of the names matches for the site, then the URL verification was done by the browser. (im not talking on the certificate verification, of course a lot of ocsp, crl, aia request and answers travels on the net every time.)

How can I make a thumbnail <img> show a full size image when clicked?

alt is text that is displayed when the image can't be loaded or the user's browser doesn't support images (e.g. readers for blind people).

Try using something like lightbox:

http://www.lokeshdhakar.com/projects/lightbox2/

update: This library maybe better as its based on jQuery which you have said your using http://leandrovieira.com/projects/jquery/lightbox/

Liquibase lock - reasons?

Sometimes truncating or dropping the table DATABASECHANGELOGLOCK doesn't work. I use PostgreSQL database and came across this issue a lot of times. What I do for solving is to rollback the prepared statements running in background for that database. Try to rollback all the prepared statements and try the liquibase changes again.

SQL:

SELECT gid FROM pg_prepared_xacts WHERE database='database_name';

If above statement returns any record, then rollback that prepared statement with following SQL statement.

ROLLBACK PREPARED 'gid_obtained_from_above_SQL';

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

In my case it was a failed import to eclipse. I had to delete the project from eclipse (without deleting form the filesystem of course) and reimport it. After that the error was gone immediately.

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

With Swift 3 and Swift 4, String has a method called data(using:allowLossyConversion:). data(using:allowLossyConversion:) has the following declaration:

func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?

Returns a Data containing a representation of the String encoded using a given encoding.

With Swift 4, String's data(using:allowLossyConversion:) can be used in conjunction with JSONDecoder's decode(_:from:) in order to deserialize a JSON string into a dictionary.

Furthermore, with Swift 3 and Swift 4, String's data(using:allowLossyConversion:) can also be used in conjunction with JSONSerialization's json?Object(with:?options:?) in order to deserialize a JSON string into a dictionary.


#1. Swift 4 solution

With Swift 4, JSONDecoder has a method called decode(_:from:). decode(_:from:) has the following declaration:

func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable

Decodes a top-level value of the given type from the given JSON representation.

The Playground code below shows how to use data(using:allowLossyConversion:) and decode(_:from:) in order to get a Dictionary from a JSON formatted String:

let jsonString = """
{"password" : "1234",  "user" : "andreas"}
"""

if let data = jsonString.data(using: String.Encoding.utf8) {
    do {
        let decoder = JSONDecoder()
        let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
        print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
    } catch {
        // Handle error
        print(error)
    }
}

#2. Swift 3 and Swift 4 solution

With Swift 3 and Swift 4, JSONSerialization has a method called json?Object(with:?options:?). json?Object(with:?options:?) has the following declaration:

class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any

Returns a Foundation object from given JSON data.

The Playground code below shows how to use data(using:allowLossyConversion:) and json?Object(with:?options:?) in order to get a Dictionary from a JSON formatted String:

import Foundation

let jsonString = "{\"password\" : \"1234\",  \"user\" : \"andreas\"}"

if let data = jsonString.data(using: String.Encoding.utf8) {
    do {
        let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
        print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
    } catch {
        // Handle error
        print(error)
    }
}

How to update-alternatives to Python 3 without breaking apt?

As I didn't want to break anything, I did this to be able to use newer versions of Python3 than Python v3.4 :

$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.6 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in auto mode
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.7 2
update-alternatives: using /usr/bin/python3.7 to provide /usr/local/bin/python3 (python3) in auto mode
$ update-alternatives --list python3
/usr/bin/python3.6
/usr/bin/python3.7
$ sudo update-alternatives --config python3
There are 2 choices for the alternative python3 (providing /usr/local/bin/python3).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.7   2         auto mode
  1            /usr/bin/python3.6   1         manual mode
  2            /usr/bin/python3.7   2         manual mode

Press enter to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in manual mode
$ ls -l /usr/local/bin/python3 /etc/alternatives/python3 
lrwxrwxrwx 1 root root 18 2019-05-03 02:59:03 /etc/alternatives/python3 -> /usr/bin/python3.6*
lrwxrwxrwx 1 root root 25 2019-05-03 02:58:53 /usr/local/bin/python3 -> /etc/alternatives/python3*

Convert month name to month number in SQL Server

How about this:

SELECT MONTH('March' + ' 1 2014') 

Would return 3.

How to ALTER multiple columns at once in SQL Server

If you don't want to write the whole thing yourself and change all the columns to the same datatype this can make it easier:

select 'alter table tblcommodityOHLC alter column '+name+ 'NUMERIC(18,0);'
from syscolumns where id = object_id('tblcommodityOHLC ')

You can copy and paste the output as your query

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

Here's a new answer to an old question, based on this Microsoft Research paper and references therein.

Note that from C11 and C++11 onwards, the semantics of div has become truncation towards zero (see [expr.mul]/4). Furthermore, for D divided by d, C++11 guarantees the following about the quotient qT and remainder rT

auto const qT = D / d;
auto const rT = D % d;
assert(D == d * qT + rT);
assert(abs(rT) < abs(d));
assert(signum(rT) == signum(D) || rT == 0);

where signum maps to -1, 0, +1, depending on whether its argument is <, ==, > than 0 (see this Q&A for source code).

With truncated division, the sign of the remainder is equal to the sign of the dividend D, i.e. -1 % 8 == -1. C++11 also provides a std::div function that returns a struct with members quot and rem according to truncated division.

There are other definitions possible, e.g. so-called floored division can be defined in terms of the builtin truncated division

auto const I = signum(rT) == -signum(d) ? 1 : 0;
auto const qF = qT - I;
auto const rF = rT + I * d;
assert(D == d * qF + rF);
assert(abs(rF) < abs(d));
assert(signum(rF) == signum(d));

With floored division, the sign of the remainder is equal to the sign of the divisor d. In languages such as Haskell and Oberon, there are builtin operators for floored division. In C++, you'd need to write a function using the above definitions.

Yet another way is Euclidean division, which can also be defined in terms of the builtin truncated division

auto const I = rT >= 0 ? 0 : (d > 0 ? 1 : -1);
auto const qE = qT - I;
auto const rE = rT + I * d;
assert(D == d * qE + rE);
assert(abs(rE) < abs(d));
assert(signum(rE) >= 0);

With Euclidean division, the sign of the remainder is always non-negative.

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

You might have pressed 0 (also used for insert, shortcut INS) key, which is on the right side of your right scroll button. To solve the problem, just press it again or double click on 'overwrite'.

Clearing all cookies with JavaScript

Functional Approach + ES6

const cookieCleaner = () => {
  return document.cookie.split(";").reduce(function (acc, cookie) {
    const eqPos = cookie.indexOf("=");
    const cleanCookie = `${cookie.substr(0, eqPos)}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;`;
    return `${acc}${cleanCookie}`;
  }, "");
}

Note: Doesn't handle paths

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

As I mentioned in your other question:

The problem to do with that fact, that you invented your own non-standard attributes (which you shouldn't have done in the first place), and now new standardized attributes (or attributes in the process of being standardized) are colliding with them.

The proper solution is to completely remove your invented attributes and replace them with something sensible, for example classes (class="Montantetextfield fieldname-Montante required allow-decimal-values"), or store them in JavaScript:

var validationData = {
  "Montante": {fieldname: "Montante", required: true, allowDecimalValues: true}
}

If the proper solution isn't viable, you'll have to rename them. In that case you should use the prefix data-... because that is reserved by HTML5 for such purposes, and it's less likely to collide with something - but it still could, so you should seriously consider the first solution - even it is more work to change.

Find a value in DataTable

A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter.

Looking at your requirement your filterexpression will have to be somewhat general to make this work.

myDataTable.Select("columnName1 like '%" + value + "%'");

how to automatically scroll down a html page?

here is the example using Pure JavaScript

_x000D_
_x000D_
function scrollpage() {  _x000D_
 function f() _x000D_
 {_x000D_
  window.scrollTo(0,i);_x000D_
  if(status==0) {_x000D_
      i=i+40;_x000D_
   if(i>=Height){ status=1; } _x000D_
  } else {_x000D_
   i=i-40;_x000D_
   if(i<=1){ status=0; }  // if you don't want continue scroll then remove this line_x000D_
  }_x000D_
 setTimeout( f, 0.01 );_x000D_
 }f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
 #top { border: 1px solid black;  height: 20000px; }_x000D_
 #bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
_x000D_
_x000D_

Call a function after previous function is complete

Specify an anonymous callback, and make function1 accept it:

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable, function() {
          function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});


function function1(param, callback) {
  ...do stuff
  callback();
} 

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Great answer and contributions from all! I had to extend this function slightly to include disabling of select elements:

jQuery.fn.extend({
disable: function (state) {
    return this.each(function () {
        var $this = jQuery(this);
        if ($this.is('input, button'))
            this.disabled = state;
        else if ($this.is('select') && state)
            $this.attr('disabled', 'disabled');
        else if ($this.is('select') && !state)
            $this.removeAttr('disabled');
        else
            $this.toggleClass('disabled', state);
    });
}});

Seems to be working for me. Thanks all!

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

Wouldn't you be better off with

<asp:HyperLink ID="HyperLink1" runat="server" 
            NavigateUrl="CMS_1.aspx" 
            Target="_blank">
    Click here
</asp:HyperLink>

Because, to replicate your desired behavior on an asp:Button, you have to call window.open on the OnClientClick event of the button which looks a lot less cleaner than the above solution. Plus asp:HyperLink is there to handle scenarios like this.

If you want to replicate this using an asp:Button, do this.

<asp:Button ID="btn" runat="Server" 
        Text="SUBMIT"
        OnClientClick="javascript:return openRequestedPopup();"/>

JavaScript function.

var windowObjectReference;

function openRequestedPopup() {
    windowObjectReference = window.open("CMS_1.aspx",
              "DescriptiveWindowName",
              "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
}

Difference between long and int data types

You're on a 32-bit machine or a 64-bit Windows machine. On my 64-bit machine (running a Unix-derivative O/S, not Windows), sizeof(int) == 4, but sizeof(long) == 8.

They're different types — sometimes the same size as each other, sometimes not.

(In the really old days, sizeof(int) == 2 and sizeof(long) == 4 — though that might have been the days before C++ existed, come to think of it. Still, technically, it is a legitimate configuration, albeit unusual outside of the embedded space, and quite possibly unusual even in the embedded space.)

Passing variables in remote ssh command

Escape the variable in order to access variables outside of the ssh session: ssh [email protected] "~/tools/myScript.pl \$BUILD_NUMBER"

How can I extract a predetermined range of lines from a text file on Unix?

I wanted to do the same thing from a script using a variable and achieved it by putting quotes around the $variable to separate the variable name from the p:

sed -n "$first","$count"p imagelist.txt >"$imageblock"

I wanted to split a list into separate folders and found the initial question and answer a useful step. (split command not an option on the old os I have to port code to).

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

transparent navigation bar ios

Try this, it works for me if you also need to support ios7, it is based on the transparency of UItoolBar:

[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                                                  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.view.backgroundColor = [UIColor clearColor];
    UIToolbar* blurredView = [[UIToolbar alloc] initWithFrame:self.navigationController.navigationBar.bounds];
    [blurredView setBarStyle:UIBarStyleBlack];
    [blurredView setBarTintColor:[UIColor redColor]];
    [self.navigationController.navigationBar insertSubview:blurredView atIndex:0];

How to get the absolute path to the public_html folder?

This is super old, but I came across it and this worked for me.

<?php
//Get absolute path
$path = getcwd();
//strip the path at your root dir name and everything that follows it
$path = substr($path, 0, strpos($path, "root"));
echo "This Is Your Absolute Path: ";
echo $path; //This will output /home/public_html/
?>

Change background color on mouseover and remove it after mouseout

After lot of struggle finally got it working. ( Perfectly tested)

The below example will also support the fact that color of already clicked button should not be changes

JQuery Code

var flag = 0; // Flag is to check if you are hovering on already clicked item

$("a").click(function() {
    $('a').removeClass("YourColorClass");
    $(this).addClass("YourColorClass");
    flag=1;
}); 

$("a").mouseover(function() {
    if ($(this).hasClass("YourColorClass")) {
        flag=1;
    }
    else{
        $(this).addClass("YourColorClass");
    };
});

$("a").mouseout(function() {
    if (flag == 0) {
        $(this).removeClass("YourColorClass");
    }
    else{
        flag = 0;
    }
});

Why are iframes considered dangerous and a security risk?

"Dangerous" and "Security risk" are not the first things that spring to mind when people mention iframes … but they can be used in clickjacking attacks.

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

How do I do word Stemming or Lemmatization?

The stemmer vs lemmatizer debates goes on. It's a matter of preferring precision over efficiency. You should lemmatize to achieve linguistically meaningful units and stem to use minimal computing juice and still index a word and its variations under the same key.

See Stemmers vs Lemmatizers

Here's an example with python NLTK:

>>> sent = "cats running ran cactus cactuses cacti community communities"
>>> from nltk.stem import PorterStemmer, WordNetLemmatizer
>>>
>>> port = PorterStemmer()
>>> " ".join([port.stem(i) for i in sent.split()])
'cat run ran cactu cactus cacti commun commun'
>>>
>>> wnl = WordNetLemmatizer()
>>> " ".join([wnl.lemmatize(i) for i in sent.split()])
'cat running ran cactus cactus cactus community community'

What is the purpose of Node.js module.exports and how do you use it?

This has already been answered but I wanted to add some clarification...

You can use both exports and module.exports to import code into your application like this:

var mycode = require('./path/to/mycode');

The basic use case you'll see (e.g. in ExpressJS example code) is that you set properties on the exports object in a .js file that you then import using require()

So in a simple counting example, you could have:

(counter.js):

var count = 1;

exports.increment = function() {
    count++;
};

exports.getCount = function() {
    return count;
};

... then in your application (web.js, or really any other .js file):

var counting = require('./counter.js');

console.log(counting.getCount()); // 1
counting.increment();
console.log(counting.getCount()); // 2

In simple terms, you can think of required files as functions that return a single object, and you can add properties (strings, numbers, arrays, functions, anything) to the object that's returned by setting them on exports.

Sometimes you'll want the object returned from a require() call to be a function you can call, rather than just an object with properties. In that case you need to also set module.exports, like this:

(sayhello.js):

module.exports = exports = function() {
    console.log("Hello World!");
};

(app.js):

var sayHello = require('./sayhello.js');
sayHello(); // "Hello World!"

The difference between exports and module.exports is explained better in this answer here.

Excel formula to display ONLY month and year?

First thing first. set the column in which you are working in by clicking on format cells->number-> date and then format e.g Jan-16 representing Jan, 1, 2016. and then apply either of the formulas above.

Delete the 'first' record from a table in SQL Server, without a WHERE condition

depends on your DBMS (people don't seem to know what that is nowadays)

-- MYSql:
DELETE FROM table LIMIT 1;
-- Postgres:
DELETE FROM table LIMIT 1;
-- MSSql:
DELETE TOP(1) FROM table;
-- Oracle:
DELETE FROM table WHERE ROWNUM = 1;

AngularJS - $http.post send data as json

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

Python: Is there an equivalent of mid, right, and left from BASIC?

You can use this method also it will act like that

thadari=[1,2,3,4,5,6]

#Front Two(Left)
print(thadari[:2])
[1,2]

#Last Two(Right)# edited
print(thadari[-2:])
[5,6]

#mid
mid = len(thadari) //2

lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]

Hope it will help

Cell spacing in UICollectionView

Remember, it is minimum line space, not minimum inter item spacing or cell space. Because your collectionView's scroll direction is HORIZONTAL.

If it is vertical then you need to set cell space or inter item space for horizontal space between cells and line spacing for vertical space between cells.

Objective-C version

- (CGFloat)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout*)collectionViewLayout
    minimumLineSpacingForSectionAtIndex:(NSInteger)section
    {
        return 20;
    }

Swift version:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 20
}

Java Date vs Calendar

With Java 8, the new java.time package should be used.

Objects are immutable, time zones and day light saving are taken into account.

You can create a ZonedDateTime object from an old java.util.Date object like this:

    Date date = new Date();
    ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault());

Very simple log4j2 XML configuration file using Console and File appender

Here is my simplistic log4j2.xml that prints to console and writes to a daily rolling file:

// java
private static final Logger LOGGER = LogManager.getLogger(MyClass.class);


// log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="logPath">target/cucumber-logs</Property>
        <Property name="rollingFileName">cucumber</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
        </Console>
        <RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
            <Policies>
                <!-- Causes a rollover if the log file is older than the current JVM's start time -->
                <OnStartupTriggeringPolicy />
                <!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
            <AppenderRef ref="rollingFile" />
        </Root>
    </Loggers>
</Configuration>

TimeBasedTriggeringPolicy

interval (integer) - How often a rollover should occur based on the most specific time unit in the date pattern. For example, with a date pattern with hours as the most specific item and and increment of 4 rollovers would occur every 4 hours. The default value is 1.

modulate (boolean) - Indicates whether the interval should be adjusted to cause the next rollover to occur on the interval boundary. For example, if the item is hours, the current hour is 3 am and the interval is 4 then the first rollover will occur at 4 am and then next ones will occur at 8 am, noon, 4pm, etc.

Source: https://logging.apache.org/log4j/2.x/manual/appenders.html

Output:

[INFO ] 2018-07-21 12:03:47,412 ScenarioHook.beforeScenario() - Browser=CHROME32_NOHEAD
[INFO ] 2018-07-21 12:03:48,623 ScenarioHook.beforeScenario() - Screen Resolution (WxH)=1366x768
[DEBUG] 2018-07-21 12:03:52,125 HomePageNavigationSteps.I_Am_At_The_Home_Page() - Base URL=http://simplydo.com/projector/
[DEBUG] 2018-07-21 12:03:52,700 NetIncomeProjectorSteps.I_Enter_My_Start_Balance() - Start Balance=348000

A new log file will be created daily with previous day automatically renamed to:

cucumber_yyyy-MM-dd.log

In a Maven project, you would put the log4j2.xml in src/main/resources or src/test/resources.

Adding link a href to an element using css

You cannot simply add a link using CSS. CSS is used for styling.

You can style your using CSS.

If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.

You can accomplish that very easily using jQuery.

I have done a sample for you. You can refer that.

URL : http://jsfiddle.net/zyk9w/

$('#link').attr('href','http://www.google.com');

This single line will do the trick.

How can I load the contents of a text file into a batch file variable?

If your set command supports the /p switch, then you can pipe input that way.

set /p VAR1=<test.txt
set /? |find "/P"

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

This has the added benefit of working for un-registered file types (which the accepted answer does not).

How to give color to each class in scatter plot in R?

One way is to use the lattice package and xyplot():

R> DF <- data.frame(x=1:10, y=rnorm(10)+5, 
+>                  z=sample(letters[1:3], 10, replace=TRUE))
R> DF
    x       y z
1   1 3.91191 c
2   2 4.57506 a
3   3 3.16771 b
4   4 5.37539 c
5   5 4.99113 c
6   6 5.41421 a
7   7 6.68071 b
8   8 5.58991 c
9   9 5.03851 a
10 10 4.59293 b
R> with(DF, xyplot(y ~ x, group=z))

By giving explicit grouping information via variable z, you obtain different colors. You can specify colors etc, see the lattice documentation.

Because z here is a factor variable for which we obtain the levels (== numeric indices), you can also do

R> with(DF, plot(x, y, col=z))

but that is less transparent (to me, at least :) then xyplot() et al.

How do I delete NuGet packages that are not referenced by any project in my solution?

You can use Package Manager Console with command: Uninstall-Package PackageId to remove it, or just delete package folder from 'packages' folder under solution folder. More information about Package Manager Console you can find here: http://docs.nuget.org/docs/reference/package-manager-console-powershell-reference

How to properly make a http web GET request

Simpliest way for my opinion

  var web = new WebClient();
  var url = $"{hostname}/LoadDataSync?systemID={systemId}";
  var responseString = web.DownloadString(url);

OR

 var bytes = web.DownloadData(url);

How to use OpenCV SimpleBlobDetector

// creation 
            cv::SimpleBlobDetector * blob_detector; 
            blob_detector = new SimpleBlobDetector(); 
            blob_detector->create("SimpleBlobDetector"); 
// change params - first move it to public!! 
            blob_detector->params.filterByArea = true; 
            blob_detector->params.minArea = 1; 
            blob_detector->params.maxArea = 32000; 
// or read / write them with file 
            FileStorage fs("test_fs.yml", FileStorage::WRITE); 
            FileNode fn = fs["features"]; 

            //blob_detector->read(fn); 
// detect 
            vector<KeyPoint> keypoints; 
            blob_detector->detect(img_text, keypoints); 
            fs.release(); 

I do know why, but params are protected. So I moved it in file features2d.hpp to be public:

  virtual void read( const FileNode& fn ); 
  virtual void write( FileStorage& fs ) const; 

public: 
Params params; 




protected: 
struct CV_EXPORTS Center 
  { 
      Point2d loc 

If you will not do this, the only way to change params is to create file (FileStorage fs("test_fs.yml", FileStorage::WRITE);), than open it in notepad, and edit. Or maybe there is another way, but I`m not aware of it.

jquery fill dropdown with json data

This should do the trick:

$($.parseJSON(data.msg)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');

Here's the distinction between ajax and getJSON (from the jQuery documentation):

[getJSON] is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:

{
    "msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}

...So that msg property needed to be parsed manually using $.parseJSON().

How to convert JSON to CSV format and store in a variable

Very nice solution by praneybehl, but if someone wants to save the data as a csv file and using a blob method then they can refer this:

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {

    //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    var CSV = '';
    //This condition will generate the Label/Header
    if (ShowLabel) {
        var row = "";

        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {
            //Now convert each value to string and comma-seprated
            row += index + ',';
        }
        row = row.slice(0, -1);
        //append Label row with line break
        CSV += row + '\r\n';
    }

    //1st loop is to extract each row
    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        //2nd loop will extract each column and convert it in string comma-seprated
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }
        row.slice(0, row.length - 1);
        //add a line break after each row
        CSV += row + '\r\n';
    }

    if (CSV == '') {
        alert("Invalid data");
        return;
    }

    //this trick will generate a temp "a" tag
    var link = document.createElement("a");
    link.id = "lnkDwnldLnk";

    //this part will append the anchor tag and remove it after automatic click
    document.body.appendChild(link);

    var csv = CSV;
    blob = new Blob([csv], { type: 'text/csv' });
    var csvUrl = window.webkitURL.createObjectURL(blob);
    var filename =  (ReportTitle || 'UserExport') + '.csv';
    $("#lnkDwnldLnk")
        .attr({
            'download': filename,
            'href': csvUrl
        });

    $('#lnkDwnldLnk')[0].click();
    document.body.removeChild(link);
}

Check if current directory is a Git repository

Use git rev-parse --git-dir

if git rev-parse --git-dir > /dev/null 2>&1; then
  : # This is a valid git repository (but the current working
    # directory may not be the top level.
    # Check the output of the git rev-parse command if you care)
else
  : # this is not a git repository
fi

JavaScript string newline character?

It might be easiest to just handle all cases of the new line character instead of checking which case then applying it. For example, if you need to replace the newline then do the following:

htmlstring = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "<br>");

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

NSDate *date         = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"]
NSString *dateString  = [df stringFromDate:date];
[df setDateFormat:@"hh:mm:ss"];
NSString *hoursString = [df stringFromDate:date];

Thats it, you got it all you want.

Delete all documents from index/type without deleting type

You can delete documents from type with following query:

POST /index/type/_delete_by_query
{
    "query" : { 
        "match_all" : {}
    }
}

I tested this query in Kibana and Elastic 5.5.2

Adding Lombok plugin to IntelliJ project

There is a lot of really helpful info posted here, but there is one thing that all the posts seem to have wrong. I could not find any 'Settings' option under 'Files', and I hunted around for 10 minutes looking through all the menus until I found the settings under 'IntelliJ IDE' -> 'Preferences'.

I don't know if I am using a differing OS version or IntelliJ version from other posters, or if it is because I am a stupid Windows user that doesn't know that settings == preferences on a mac (Did I miss the memo?), but I hope this helps you if you aren't finding the paths that other posts are suggesting.

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

In some cases, when necessary using has been obviously added and studio can't see this namespace, studio restart can save the day.

Laravel 5 Application Key

From the line

'key' => env('APP_KEY', 'SomeRandomString'),

APP_KEY is a global environment variable that is present inside the .env file.

You can replace the application key if you trigger

php artisan key:generate

command. This will always generate the new key.

The output may be like this:


Application key [Idgz1PE3zO9iNc0E3oeH3CHDPX9MzZe3] set successfully.

Application key [base64:uynE8re8ybt2wabaBjqMwQvLczKlDSQJHCepqxmGffE=] set successfully.

Base64 encoding should be the default in Laravel 5.4

Note that when you first create your Laravel application, key:generate is automatically called.

If you change the key be aware that passwords saved with Hash::make() will no longer be valid.

Stretch Image to Fit 100% of Div Height and Width

Or you can put in the CSS,

<style>
div#img {
  background-image: url(“file.png");
  color:yellow (this part doesn't matter;
  height:100%;
  width:100%;
}
</style>

How do I POST XML data with curl

I prefer the following command-line options:

cat req.xml | curl -X POST -H 'Content-type: text/xml' -d @- http://www.example.com

or

curl -X POST -H 'Content-type: text/xml' -d @req.xml http://www.example.com

or

curl -X POST -H 'Content-type: text/xml'  -d '<XML>data</XML>' http://www.example.com 

Selecting multiple classes with jQuery

Have you tried this?

$('.myClass, .myOtherClass').removeClass('theclass');

How to write Unicode characters to the console?

I found some elegant solution on MSDN

System.Console.Write('\uXXXX') //XXXX is hex Unicode for character

This simple program writes ? right on the screen.

using System;

public class Test
{
    public static void Main()
    {
        Console.Write('\u2103'); //? character code
    }
}

How to preview an image before and after upload?

Try this: (For Preview)

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

<body>
    <form id="form1" runat="server">
        <input type="file" onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Working Demo here>

jQuery How do you get an image to fade in on load?

OK so I did this and it works. It's basically hacked together from different responses here. Since there is STILL not a clear answer in this thread I decided to post this.

<script type="text/javascript">
  $(document).ready(function () {
    $("#logo").hide();
    $("#logo").bind("load", function () { $(this).fadeIn(); });
  });
</script>

This seems to me to be the best way to go about it. Despite Sohnee's best intentions he failed to mention that the object must first be set to display:none with CSS. The problem here is that if for what ever reason the user's JS is not working the object will just never appear. Not good, especially if it's the frikin' logo.

This solution leaves the item alone in the CSS, and first hides, then fades it in all using JS. This way if JS is not working properly the item will just load as normal.

Hope that helps anyone else who stumbles into this google ranked #1 not-so-helpful thread.

Why AVD Manager options are not showing in Android Studio

I had installed Android studio and was not able to access the AVD Manager directly. I had to follow the steps as mentioned below:

  1. Created a blank project using Android Studio
  2. Once the Project is ready to use I tried open action using the shortcut ctrl+shift+a option and searched for AVD Manager AVD Manager
  3. On double clicking the AVD Manager I got a few errors in console about the missing libararies along with the link to install the neccessary dependencies. On clicking the links which was displayed with the error message few packages which were needed were installed. Once all the required packages were installed the AVD Manager icon becomes active.

enter image description here

How to change the port number for Asp.Net core app?

you can also code like this

        IConfiguration config  = new ConfigurationBuilder()
        .AddCommandLine(args)
        .Build(); 
        var host = new WebHostBuilder()
         .UseConfiguration(config)
         .UseKestrel()
         .UseContentRoot(Directory.GetCurrentDirectory()) 
         .UseStartup<Startup>()
         .Build();

and set up your application by command line :dotnet run --server.urls http://*:5555

angularjs - ng-repeat: access key and value from JSON array object

Solution I have json object which has data

[{"name":"Ata","email":"[email protected]"}]

You can use following approach to iterate through ng-repeat and use table format instead of list.

<div class="container" ng-controller="fetchdataCtrl">    
  <ul ng-repeat="item in numbers">
    <li>            
      {{item.name}}: {{item.email}}
    </li>
  </ul>     
</div>

Passing a method as a parameter in Ruby

You have to call the method "call" of the function object:

weight = weightf.call( dist )

EDIT: as explained in the comments, this approach is wrong. It would work if you're using Procs instead of normal functions.

How to loop through an array of objects in swift

You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:

class ModelAttachment {
    var id: String?
    var url: String?
    var thumb: String?
}

var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"

var imgs: Array<ModelAttachment> = [modelAttachementObj]

for img in imgs  {
    let url = img.url
    NSLog(url!)
}

See docs here

How to see data from .RData file?

isfar<-load("C:/Users/isfar.RData") 
if(is.data.frame(isfar)){
   names(isfar)
}

If isfar is a dataframe, this will print out the names of its columns.

When do I need a fb:app_id or fb:admins?

To use the Like Button and have the Open Graph inspect your website, you need an application.

So you need to associate the Like Button with a fb:app_id

If you want other users to see the administration page for your website on Facebook you add fb:admins. So if you are the developer of the application and the website owner there is no need to add fb:admins

HTML: How to center align a form

The last two lines are important to align in center:

.f01 {
    background-color: rgb(16, 216, 252);
    padding: 100px;
    text-align: left;
    margin: auto;
    display: table;
}

ECMAScript 6 arrow function that returns an object

You can always check this out for more custom solutions:

x => ({}[x.name] = x);

WPF Button with Image

Most simple approach would be using the Image tag.

<Button Name="btn" Width="26" Height="26" Click="btnClick"> 
   <Image Source="Resource/btn-icon.png"/>
</Button>

Suppose your image file is added in Resource folder

Smooth scrolling when clicking an anchor link

$('a[href*=#]').click(function(event){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    event.preventDefault();
});

this worked perfect for me

Pass mouse events through absolutely-positioned element

pointer-events: none;

Is a CSS property that makes events "pass through" the element to which it is applied and makes the event occur on the element "below".

See for details: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

It is not supported up to IE 11; all other vendors support it since quite some time (global support was ~92% in 12/'16): http://caniuse.com/#feat=pointer-events (thanks to @s4y for providing the link in the comments).

Pass an array of integers to ASP.NET Web API?

My solution was to create an attribute to validate strings, it does a bunch of extra common features, including regex validation that you can use to check for numbers only and then later I convert to integers as needed...

This is how you use:

public class MustBeListAndContainAttribute : ValidationAttribute
{
    private Regex regex = null;
    public bool RemoveDuplicates { get; }
    public string Separator { get; }
    public int MinimumItems { get; }
    public int MaximumItems { get; }

    public MustBeListAndContainAttribute(string regexEachItem,
        int minimumItems = 1,
        int maximumItems = 0,
        string separator = ",",
        bool removeDuplicates = false) : base()
    {
        this.MinimumItems = minimumItems;
        this.MaximumItems = maximumItems;
        this.Separator = separator;
        this.RemoveDuplicates = removeDuplicates;

        if (!string.IsNullOrEmpty(regexEachItem))
            regex = new Regex(regexEachItem, RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var listOfdValues = (value as List<string>)?[0];

        if (string.IsNullOrWhiteSpace(listOfdValues))
        {
            if (MinimumItems > 0)
                return new ValidationResult(this.ErrorMessage);
            else
                return null;
        };

        var list = new List<string>();

        list.AddRange(listOfdValues.Split(new[] { Separator }, System.StringSplitOptions.RemoveEmptyEntries));

        if (RemoveDuplicates) list = list.Distinct().ToList();

        var prop = validationContext.ObjectType.GetProperty(validationContext.MemberName);
        prop.SetValue(validationContext.ObjectInstance, list);
        value = list;

        if (regex != null)
            if (list.Any(c => string.IsNullOrWhiteSpace(c) || !regex.IsMatch(c)))
                return new ValidationResult(this.ErrorMessage);

        return null;
    }
}

Where to change the value of lower_case_table_names=2 on windows xampp

Look for a file named my.ini in your hard disk, in my system it's in

c:\program files\mysql\mysql server 5.1

If it's not my.ini it should be my.cnf

Linq to SQL how to do "where [column] in (list of values)"

Here is how I do it by using HashSet

        HashSet<String> hs = new HashSet<string>(new String[] { "Pluto", "Earth", "Neptune" });
        String[] arr =
        {
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            // etc.
        };
        ICollection<String> coll = arr;

        String[] arrStrFiltered = coll.Where(str => hs.Contains(str)).ToArray();

HashSet is basically almost to O(1) so your complexity remains O(n).

ASP.NET Web API : Correct way to return a 401/unauthorised response

you can use follow code in asp.net core 2.0:

public IActionResult index()
{
     return new ContentResult() { Content = "My error message", StatusCode = (int)HttpStatusCode.Unauthorized };
}

How do you convert an entire directory with ffmpeg?

For Linux and macOS this can be done in one line, using parameter expansion to change the filename extension of the output file:

for i in *.avi; do ffmpeg -i "$i" "${i%.*}.mp4"; done

What are some ways of accessing Microsoft SQL Server from Linux?

FreeTDS + unixODBC or iODBC

Install first FreeTDS, then configure one of the two ODBC engines to use FreeTDS as its ODBC driver. Then use the commandline interface of the ODBC engine.

unixODBC has isql, iODBC has iodbctest

You can also use your favorite programming language (I've successfully used Perl, C, Python and Ruby to connect to MSSQL)

I'm personally using FreeTDS + iODBC:

$more /etc/freetds/freetds.conf
[10.0.1.251]
    host = 10.0.1.251
    port = 1433
    tds version = 8.0

$ more /etc/odbc.ini
[ACCT]
Driver = /usr/local/freetds/lib/libtdsodbc.so
Description = ODBC to SQLServer via FreeTDS
Trace = No
Servername = 10.0.1.251
Database = accounts_ver8

IIS7: Setup Integrated Windows Authentication like in IIS6

So do you want them to get the IE password-challenge box, or should they be directed to your login page and enter their information there? If it's the second option, then you should at least enable Anonymous access to your login page, since the site won't know who they are yet.

If you want the first option, then the login page they're getting forwarded to will need to read the currently logged-in user and act based on that, since they would have had to correctly authenticate to get this far.

What are the best JVM settings for Eclipse?

If you're going with jdk6 update 14, I'd suggest using using the G1 garbage collector which seems to help performance.

To do so, remove these settings:

-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing

and replace them with these:

-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC