Programs & Examples On #Nested transactions

Git: "please tell me who you are" error

I spent lots of hours on it when I call PHP script to init and commit to git. And I found the work flow should be as:

  1. git init
  2. git config user.name "someone"
  3. git config user.email "[email protected]"
  4. git add *
  5. git commit -m "some init msg"

If you swap [23] and 1, the config will not work at all.

I wish this will do some help.

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

I had the same problem after changing JDK from 1.6 to 1.7 in my pom.xml and setting Maven 3 path + JDK project settings to 1.7.

What did it for me was => File -> Invalidate Caches and Restart

PS: problem occured again, so i just reimported the full project after deleting the .idea folder and now it works fine as usual :)

Maven 3 warnings about build.plugins.plugin.version

Run like:

  $ mvn help:describe -DartifactId=maven-war-plugin -DgroupId=org.apache.maven.plugins

for plug-in that have no version. You get output:

Name: Maven WAR Plugin
Description: Builds a Web Application Archive (WAR) file from the project
  output and its dependencies.
Group Id: org.apache.maven.plugins
Artifact Id: maven-war-plugin
Version: 2.2
Goal Prefix: war

Use version that shown in output.

UPDATE If you want to select among list of versions, use http://search.maven.org/ or http://mvnrepository.com/ Note that your favorite Java IDE must have Maven package search dialog. Just check docs.

SUPER UPDATE I also use:

$ mvn dependency:tree
$ mvn dependency:list
$ mvn dependency:resolve
$ mvn dependency:resolve-plugins  # <-- THIS

Recently I discover how to get latest version for plug-in (or library) so no longer needs for googling or visiting Maven Central:

$ mvn versions:display-dependency-updates
$ mvn versions:display-plugin-updates     # <-- THIS

XAMPP installation on Win 8.1 with UAC Warning

There are two things you need to check:

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC (User Account Control) as it restricts certain administrative function needed to run a web server.

To ensure that your user account has administrator privilege, run lusrmgr.msc from the Windows Start > Run menu to bring up the Local Users and Groups Windows. Double-click on your user account that appears under Users, and verifies that it is a member of Administrators.

To disable UAC (as an administrator), from Control Panel:

  1. Type UAC in the search field in the upper right corner.
  2. Click Change User Account Control settings in the search results.
  3. Drag the slider down to Never notifyand click OK.

open up the User Accounts window from Control Panel. Click on the Turn User Account Control on or off option, and un-check the checkbox.

Alternately, if you don't want to disable UAC, you will have to install XAMPP in a different folder, outside of C:\Program Files (x86), such as C:\xampp.

Hope this helps.

Applying .gitignore to committed files

to leave the file in the repo but ignore future changes to it:

git update-index --assume-unchanged <file>

and to undo this:

git update-index --no-assume-unchanged <file>

to find out which files have been set this way:

git ls-files -v|grep '^h'

credit for the original answer to http://blog.pagebakers.nl/2009/01/29/git-ignoring-changes-in-tracked-files/

How to start and stop android service from a adb shell?

If you want to run the script in adb shell, then I am trying to do the same, but with an application. I think you can use "am start" command

usage: am [subcommand] [options]

start an Activity: am start [-D] [-W] <INTENT>
    -D: enable debugging
    -W: wait for launch to complete

**start a Service: am startservice <INTENT>**

send a broadcast Intent: am broadcast <INTENT>

start an Instrumentation: am instrument [flags] <COMPONENT>
    -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)
    -e <NAME> <VALUE>: set argument <NAME> to <VALUE>
    -p <FILE>: write profiling data to <FILE>
    -w: wait for instrumentation to finish before returning

start profiling: am profile <PROCESS> start <FILE>
stop profiling: am profile <PROCESS> stop

start monitoring: am monitor [--gdb <port>]
    --gdb: start gdbserv on the given port at crash/ANR

<INTENT> specifications include these flags:
    [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
    [-c <CATEGORY> [-c <CATEGORY>] ...]
    [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
    [--esn <EXTRA_KEY> ...]
    [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
    [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
    [-n <COMPONENT>] [-f <FLAGS>]
    [--grant-read-uri-permission] [--grant-write-uri-permission]
    [--debug-log-resolution]
    [--activity-brought-to-front] [--activity-clear-top]
    [--activity-clear-when-task-reset] [--activity-exclude-from-recents]
    [--activity-launched-from-history] [--activity-multiple-task]
    [--activity-no-animation] [--activity-no-history]
    [--activity-no-user-action] [--activity-previous-is-top]
    [--activity-reorder-to-front] [--activity-reset-task-if-needed]
    [--activity-single-top]
    [--receiver-registered-only] [--receiver-replace-pending]
    [<URI>]

What is the largest TCP/IP network port number allowable for IPv4?

As I understand it, you should only use up to 49151, as from 49152 up to 65535 are reserved for Ephemeral ports

Switch on Enum in Java

First, you can switch on an enum in Java. I'm guessing you intended to say you can’t, but you can. chars have a set range of values, so it's easy to compare. Strings can be anything.

A switch statement is usually implemented as a jump table (branch table) in the underlying compilation, which is only possible with a finite set of values. C# can switch on strings, but it causes a performance decrease because a jump table cannot be used.

Java 7 and later supports String switches with the same characteristics.

int object is not iterable?

maybe you're trying to

for i in range(inp)

This will print your input value (inp) times, to print it only once, follow: for i in range(inp - inp + 1 ) print(i)

I just had this error because I wasn't using range()

Node.js https pem error: routines:PEM_read_bio:no start line

I guess this is because your nodejs cert has expired. Type this line :
npm set registry http://registry.npmjs.org/
and after that try again with npm install . This actually solved my problem.

What's the "Content-Length" field in HTTP header?

One octet is 8 bits. Content-length is the number of octets that the message body represents.

Full-screen responsive background image

You can also make full screen banner section without use of JavaScript, pure css based responsive full screen banner section , using height: 100vh; in banner main div, here have live example for this

#bannersection {
    position: relative;
    display: table;
    width: 100%;
    background: rgba(99,214,250,1);
    height: 100vh;
}

https://www.htmllion.com/fullscreen-header-banner-section.html

Is #pragma once a safe include guard?

Using gcc 3.4 and 4.1 on very large trees (sometimes making use of distcc), I have yet to see any speed up when using #pragma once in lieu of, or in combination with standard include guards.

I really don't see how its worth potentially confusing older versions of gcc, or even other compilers since there's no real savings. I have not tried all of the various de-linters, but I'm willing to bet it will confuse many of them.

I too wish it had been adopted early on, but I can see the argument "Why do we need that when ifndef works perfectly fine?". Given C's many dark corners and complexities, include guards are one of the easiest, self explaining things. If you have even a small knowledge of how the preprocessor works, they should be self explanatory.

If you do observe a significant speed up, however, please update your question.

Difference between e.target and e.currentTarget

target  is the element that triggered the event (e.g., the user clicked on)

currenttarget is the element that the event listener is attached to.

How do you log all events fired by an element in jQuery?

$(element).on("click mousedown mouseup focus blur keydown change",function(e){
     console.log(e);
});

That will get you a lot (but not all) of the information on if an event is fired... other than manually coding it like this, I can't think of any other way to do that.

How to set JFrame to appear centered, regardless of monitor resolution?

i am using NetBeans IDE 7.2.1 as my developer environmental and there you have an option to configure the JForm properties.

in the JForm Properties go to the 'Code' tab and configure the 'Generate Center'. you will need first to set the Form Size Policy to 'Generate Resize Code'.

Getting attributes of Enum's value

Guys if it helps I will share with you my solution: Definition of Custom attribute:

    [AttributeUsage(AttributeTargets.Field,AllowMultiple = false)]
public class EnumDisplayName : Attribute
{
    public string Name { get; private set; }
    public EnumDisplayName(string name)
    {
        Name = name;
    }
}

Now because I needed it inside of HtmlHelper definition of HtmlHelper Extension:

public static class EnumHelper
{
    public static string EnumDisplayName(this HtmlHelper helper,EPriceType priceType)
    {
        //Get every fields from enum
        var fields = priceType.GetType().GetFields();
        //Foreach field skipping 1`st fieldw which keeps currently sellected value
        for (int i = 0; i < fields.Length;i++ )
        {
            //find field with same int value
            if ((int)fields[i].GetValue(priceType) == (int)priceType)
            {
                //get attributes of found field
                var attributes = fields[i].GetCustomAttributes(false);
                if (attributes.Length > 0)
                {
                    //return name of found attribute
                    var retAttr = (EnumDisplayName)attributes[0];
                    return retAttr.Name;
                }
            }
        }
        //throw Error if not found
        throw new Exception("Blad podczas ustalania atrybutów dla typu ceny allegro");
    }
}

Hope it helps

Adding up BigDecimals using Streams

Original answer

Yes, this is possible:

List<BigDecimal> bdList = new ArrayList<>();
//populate list
BigDecimal result = bdList.stream()
        .reduce(BigDecimal.ZERO, BigDecimal::add);

What it does is:

  1. Obtain a List<BigDecimal>.
  2. Turn it into a Stream<BigDecimal>
  3. Call the reduce method.

    3.1. We supply an identity value for addition, namely BigDecimal.ZERO.

    3.2. We specify the BinaryOperator<BigDecimal>, which adds two BigDecimal's, via a method reference BigDecimal::add.

Updated answer, after edit

I see that you have added new data, therefore the new answer will become:

List<Invoice> invoiceList = new ArrayList<>();
//populate
Function<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());
BigDecimal result = invoiceList.stream()
        .map(totalMapper)
        .reduce(BigDecimal.ZERO, BigDecimal::add);

It is mostly the same, except that I have added a totalMapper variable, that has a function from Invoice to BigDecimal and returns the total price of that invoice.

Then I obtain a Stream<Invoice>, map it to a Stream<BigDecimal> and then reduce it to a BigDecimal.

Now, from an OOP design point I would advice you to also actually use the total() method, which you have already defined, then it even becomes easier:

List<Invoice> invoiceList = new ArrayList<>();
//populate
BigDecimal result = invoiceList.stream()
        .map(Invoice::total)
        .reduce(BigDecimal.ZERO, BigDecimal::add);

Here we directly use the method reference in the map method.

How to switch to another domain and get-aduser

Try specifying a DC in DomainB using the -Server property. Ex:

Get-ADUser -Server "dc01.DomainB.local" -Filter {EmailAddress -like "*Smith_Karla*"} -Properties EmailAddress

How to export a MySQL database to JSON?

If you have Ruby, you can install the mysql2xxxx gem (not the mysql2json gem, which is a different gem):

$ gem install mysql2xxxx

and then run the command

$ mysql2json --user=root --password=password --database=database_name --execute "select * from mytable" >mytable.json

The gem also provides mysql2csv and mysql2xml. It's not as fast as mysqldump, but also doesn't suffer from some of mysqldump's weirdnesses (like only being able to dump CSV from the same computer as the MySQL server itself)

How to access model hasMany Relation with where condition?

I have fixed the similar issue by passing associative array as the first argument inside Builder::with method.

Imagine you want to include child relations by some dynamic parameters but don't want to filter parent results.

Model.php

public function child ()
{
    return $this->hasMany(ChildModel::class);
}

Then, in other place, when your logic is placed you can do something like filtering relation by HasMany class. For example (very similar to my case):

$search = 'Some search string';
$result = Model::query()->with(
    [
        'child' => function (HasMany $query) use ($search) {
            $query->where('name', 'like', "%{$search}%");
        }
    ]
);

Then you will filter all the child results but parent models will not filter. Thank you for attention.

Decode Base64 data in Java

Guava now has Base64 decoding built in.

Use BaseEncoding.base64().decode()

As for dealing with possible whitespace in input use

BaseEncoding.base64().decode(CharMatcher.WHITESPACE.removeFrom(...));

See this discussion for more information

Convert Pandas Column to DateTime

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

works, however it results in a Python warning of A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

I would guess this is due to some chaining indexing.

What does the "On Error Resume Next" statement do?

It basically tells the program when you encounter an error just continue at the next line.

Eventviewer eventid for lock and unlock

For newer versions of Windows (including but not limited to both Windows 10 and Windows Server 2016), the event IDs are:

  • 4800 - The workstation was locked.
  • 4801 - The workstation was unlocked.

Locking and unlocking a workstation also involve the following logon and logoff events:

  • 4624 - An account was successfully logged on.
  • 4634 - An account was logged off.
  • 4648 - A logon was attempted using explicit credentials.

When using a Terminal Services session, locking and unlocking may also involve the following events if the session is disconnected, and event 4778 may replace event 4801:

  • 4779 - A session was disconnected from a Window Station.
  • 4778 - A session was reconnected to a Window Station.

Events 4800 and 4801 are not audited by default, and must be enabled using either Local Group Policy Editor (gpedit.msc) or Local Security Policy (secpol.msc).

The path for the policy using Local Group Policy Editor is:

  • Local Computer Policy
  • Computer Configuration
  • Windows Settings
  • Security Settings
  • Advanced Audit Policy Configuration
  • System Audit Policies - Local Group Policy Object
  • Logon/Logoff
  • Audit Other Logon/Logoff Events

The path for the policy using Local Security Policy is the following subset of the path for Local Group Policy Editor:

  • Security Settings
  • Advanced Audit Policy Configuration
  • System Audit Policies - Local Group Policy Object
  • Logon/Logoff
  • Audit Other Logon/Logoff Events

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

I am adding two sollution that work for me.

1st sollution is:

  1. Open database.php file insde config dir/folder.
  2. Edit 'engine' => null, to 'engine' => 'InnoDB',

    This worked for me.

2nd sollution is:

  1. Open database.php file insde config dir/folder.
    2.Edit
    'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci',
    to

    'charset' => 'utf8', 'collation' => 'utf8_unicode_ci',


Goodluck

Move_uploaded_file() function is not working

maybe you need to grant more permissions to your files.

suppose your code are under /var/www/my_project

try chmod -R 777 /var/www/my_project

How to split a dataframe string column into two columns?

TL;DR version:

For the simple case of:

  • I have a text column with a delimiter and I want two columns

The simplest solution is:

df[['A', 'B']] = df['AB'].str.split(' ', 1, expand=True)

You must use expand=True if your strings have a non-uniform number of splits and you want None to replace the missing values.

Notice how, in either case, the .tolist() method is not necessary. Neither is zip().

In detail:

Andy Hayden's solution is most excellent in demonstrating the power of the str.extract() method.

But for a simple split over a known separator (like, splitting by dashes, or splitting by whitespace), the .str.split() method is enough1. It operates on a column (Series) of strings, and returns a column (Series) of lists:

>>> import pandas as pd
>>> df = pd.DataFrame({'AB': ['A1-B1', 'A2-B2']})
>>> df

      AB
0  A1-B1
1  A2-B2
>>> df['AB_split'] = df['AB'].str.split('-')
>>> df

      AB  AB_split
0  A1-B1  [A1, B1]
1  A2-B2  [A2, B2]

1: If you're unsure what the first two parameters of .str.split() do, I recommend the docs for the plain Python version of the method.

But how do you go from:

  • a column containing two-element lists

to:

  • two columns, each containing the respective element of the lists?

Well, we need to take a closer look at the .str attribute of a column.

It's a magical object that is used to collect methods that treat each element in a column as a string, and then apply the respective method in each element as efficient as possible:

>>> upper_lower_df = pd.DataFrame({"U": ["A", "B", "C"]})
>>> upper_lower_df

   U
0  A
1  B
2  C
>>> upper_lower_df["L"] = upper_lower_df["U"].str.lower()
>>> upper_lower_df

   U  L
0  A  a
1  B  b
2  C  c

But it also has an "indexing" interface for getting each element of a string by its index:

>>> df['AB'].str[0]

0    A
1    A
Name: AB, dtype: object

>>> df['AB'].str[1]

0    1
1    2
Name: AB, dtype: object

Of course, this indexing interface of .str doesn't really care if each element it's indexing is actually a string, as long as it can be indexed, so:

>>> df['AB'].str.split('-', 1).str[0]

0    A1
1    A2
Name: AB, dtype: object

>>> df['AB'].str.split('-', 1).str[1]

0    B1
1    B2
Name: AB, dtype: object

Then, it's a simple matter of taking advantage of the Python tuple unpacking of iterables to do

>>> df['A'], df['B'] = df['AB'].str.split('-', 1).str
>>> df

      AB  AB_split   A   B
0  A1-B1  [A1, B1]  A1  B1
1  A2-B2  [A2, B2]  A2  B2

Of course, getting a DataFrame out of splitting a column of strings is so useful that the .str.split() method can do it for you with the expand=True parameter:

>>> df['AB'].str.split('-', 1, expand=True)

    0   1
0  A1  B1
1  A2  B2

So, another way of accomplishing what we wanted is to do:

>>> df = df[['AB']]
>>> df

      AB
0  A1-B1
1  A2-B2

>>> df.join(df['AB'].str.split('-', 1, expand=True).rename(columns={0:'A', 1:'B'}))

      AB   A   B
0  A1-B1  A1  B1
1  A2-B2  A2  B2

The expand=True version, although longer, has a distinct advantage over the tuple unpacking method. Tuple unpacking doesn't deal well with splits of different lengths:

>>> df = pd.DataFrame({'AB': ['A1-B1', 'A2-B2', 'A3-B3-C3']})
>>> df
         AB
0     A1-B1
1     A2-B2
2  A3-B3-C3
>>> df['A'], df['B'], df['C'] = df['AB'].str.split('-')
Traceback (most recent call last):
  [...]    
ValueError: Length of values does not match length of index
>>> 

But expand=True handles it nicely by placing None in the columns for which there aren't enough "splits":

>>> df.join(
...     df['AB'].str.split('-', expand=True).rename(
...         columns={0:'A', 1:'B', 2:'C'}
...     )
... )
         AB   A   B     C
0     A1-B1  A1  B1  None
1     A2-B2  A2  B2  None
2  A3-B3-C3  A3  B3    C3

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

grep exclude multiple strings

grep -Fv -e 'Nopaging the limit is' -e 'keyword to remove is'

-F matches by literal strings (instead of regex)

-v inverts the match

-e allows for multiple search patterns (all literal and inverted)

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

How can I pass a Bitmap object from one activity to another

Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.

To store bitmap in a file myImage in internal storage:

public String createImageFromBitmap(Bitmap bitmap) {
    String fileName = "myImage";//no .png or .jpg needed
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
        fo.write(bytes.toByteArray());
        // remember close file output
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
        fileName = null;
    }
    return fileName;
}

Then in the next activity you can decode this file myImage to a bitmap using following code:

//here context can be anything like getActivity() for fragment, this or MainActivity.this
Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));

Note A lot of checking for null and scaling bitmap's is ommited.

Convert String to equivalent Enum value

Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration class), you can use the valueOf method of java.lang.Enum subclass:

MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");

Efficient way to remove keys with empty strings from a dict

Some benchmarking:

1. List comprehension recreate dict

In [7]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
   ...: dic = {k: v for k, v in dic.items() if v is not None} 
   1000000 loops, best of 7: 375 ns per loop

2. List comprehension recreate dict using dict()

In [8]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
   ...: dic = dict((k, v) for k, v in dic.items() if v is not None)
1000000 loops, best of 7: 681 ns per loop

3. Loop and delete key if v is None

In [10]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
    ...: for k, v in dic.items():
    ...:   if v is None:
    ...:     del dic[k]
    ...: 
10000000 loops, best of 7: 160 ns per loop

so loop and delete is the fastest at 160ns, list comprehension is half as slow at ~375ns and with a call to dict() is half as slow again ~680ns.

Wrapping 3 into a function brings it back down again to about 275ns. Also for me PyPy was about twice as fast as neet python.

How do I request and process JSON with python?

For anything with requests to URLs you might want to check out requests. For JSON in particular:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

Extract digits from string - StringUtils Java

I've created a JUnit Test class(as a additional knowledge/info) for the same issue. Hope you'll be finding this helpful.

   public class StringHelper {
    //Separate words from String which has gigits
        public String drawDigitsFromString(String strValue){
            String str = strValue.trim();
            String digits="";
            for (int i = 0; i < str.length(); i++) {
                char chrs = str.charAt(i);              
                if (Character.isDigit(chrs))
                    digits = digits+chrs;
            }
            return digits;
        }
    }

And JUnit Test case is:

 public class StringHelperTest {
    StringHelper helper;

        @Before
        public void before(){
            helper = new StringHelper();
        }

        @Test
    public void testDrawDigitsFromString(){
        assertEquals("187111", helper.drawDigitsFromString("TCS187TCS111"));
    }
 }

How do I count unique values inside a list

If you would like to have a histogram of unique values here's oneliner

import numpy as np    
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))

Check if list<t> contains any of another list

If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:

var items = (from x in parameters
                join y in myStrings on x.Source equals y
                select x)
            .ToList();

Mocking member variables of a class using Mockito

If you want an alternative to ReflectionTestUtils from Spring in mockito, use

Whitebox.setInternalState(first, "second", sec);

Javascript change color of text and background to input value

document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';

python convert list to dictionary

If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.

How to turn a list into a dictionary using built-in functions only

We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.

l = ["a", "b", "c", "d", "e"]

dict()

To create a dictionary we can use the built in dict function for Mapping Types as per the manual the following methods are supported.

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

The last option suggests that we supply a list of lists with 2 values or (key, value) tuples, so we want to turn our sequential list into:

l = [["a", "b"], ["c", "d"], ["e",]]

We are also introduced to the zip function, one of the built-in functions which the manual explains:

returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments

In other words if we can turn our list into two lists a, c, e and b, d then zip will do the rest.

slice notation

Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:

>>> l[::2]
['a', 'c', 'e']

>>> l[1::2]
['b', 'd']

>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]

>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}

Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]

>>> b is a
True

>>> b = a[:]
>>> b
[1, 2, 3]

>>> b is a
False

Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.

grouper recipe

Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.

Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.

*[iter(l)]*2

Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.

zip for shortest

>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]

>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]

>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}

As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.

You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.

>>> it = iter(l)     
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}

What about the empty key e if you've noticed it has been missing from all the examples which is because zip picks the shortest of the two arguments, so what are we to do.

Well one solution might be adding an empty value to odd length lists, you may choose to use append and an if statement which would do the trick, albeit slightly boring, right?

>>> if len(l) % 2:
...     l.append("")

>>> l
['a', 'b', 'c', 'd', 'e', '']

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}

Now before you shrug away to go type from itertools import izip_longest you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.

map for longest

I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None empty value when required, automagically.

>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']

>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None} 

Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.

$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real    0m3.755s
user    0m2.815s
sys     0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real    0m2.102s
user    0m1.451s
sys     0m0.539s

However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.

$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real    0m0.046s
user    0m0.029s
sys     0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real    0m0.067s
user    0m0.042s
sys     0m0.021s

$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real    0m0.074s
user    0m0.050s
sys     0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real    0m0.075s
user    0m0.047s
sys     0m0.024s

See nothing to it! =)

nJoy!

How to convert HTML to PDF using iTextSharp

As of 2018, there is also iText7 (A next iteration of old iTextSharp library) and its HTML to PDF package available: itext7.pdfhtml

Usage is straightforward:

HtmlConverter.ConvertToPdf(
    new FileInfo(@"Path\to\Html\File.html"),
    new FileInfo(@"Path\to\Pdf\File.pdf")
);

Method has many more overloads.

Update: iText* family of products has dual licensing model: free for open source, paid for commercial use.

How to run a SQL query on an Excel table?

tl;dr; Excel does all of this natively - use filters and or tables

(http://office.microsoft.com/en-gb/excel-help/filter-data-in-an-excel-table-HA102840028.aspx)

You can open excel programatically through an oledb connection and execute SQL on the tables within the worksheet.

But you can do everything you are asking to do with no formulas just filters.

  1. click anywhere within the data you are looking at
  2. go to data on the ribbon bar
  3. select "Filter" its about the middle and looks like a funnel
    • you will have arrows on the tight hand side of each cell in the the first row of your table now
  4. click the arrow on phone number and de-select blanks (last option)
  5. click the arrow on last name and select a-z ordering (top option)

have a play around.. some things to note:

  1. you can select the filtered rows and pasty them somewhere else
  2. in the status bar on the left you will see how many rows meet you filter criteria out of the total number of rows. (e.g. 308 of 313 records found)
  3. you can filter by color in excel 2010 on wards
  4. Sometimes i create calculated columns that give statuses or cleaned versions of data you can then filter or sort by theses too. (e.g. like the formulae in the other answers)

DO it with filters unless you are going to do it a lot or you want to automate importing data somewhere or something.. but for completeness:

A c# option:

 OleDbConnection ExcelFile = new OleDbConnection( String.Format( "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES\"", filename));
 ExcelFile.Open();

a handy place to start is to take a look at the schema as there may be more there than you think:

List<String> excelSheets = new List<string>();

// Add the sheet name to the string array.
foreach (DataRow row in dt.Rows) {
    string temp = row["TABLE_NAME"].ToString();
    if (temp[temp.Length - 1] == '$') {
         excelSheets.Add(row["TABLE_NAME"].ToString());
    }
}

then when you want to query a sheet:

 OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + sheet + "]", ExcelFile);
 dt = new DataTable();
  da.Fill(dt);

NOTE - Use Tables in excel!:

Excel has "tables" functionality that make data behave more like a table.. this gives you some great benefits but is not going to let you do every type of query.

http://office.microsoft.com/en-gb/excel-help/overview-of-excel-tables-HA010048546.aspx

For tabular data in excel this is my default.. first thing i do is click into the data then select "format as table" from the home section on the ribbon. this gives you filtering, and sorting by default and allows you to access the table and fields by name (e.g. table[fieldname] ) this also allows aggregate functions on columns e.g. max and average

How to search images from private 1.0 registry in docker?

So I know this is a rapidly changing field but (as of 2015-09-08) I found the following in the Docker Registry HTTP API V2:

Listing Repositories (link)

GET /v2/_catalog

Listing Image Tags (link)

GET /v2/<name>/tags/list

Based on that the following worked for me on a local registry (registry:2 IMAGE ID 1e847b14150e365a95d76a9cc6b71cd67ca89905e3a0400fa44381ecf00890e1 created on 2015-08-25T07:55:17.072):

$ curl -X GET http://localhost:5000/v2/_catalog
{"repositories":["ubuntu"]}
$ curl -X GET http://localhost:5000/v2/ubuntu/tags/list
{"name":"ubuntu","tags":["latest"]}

iPhone SDK on Windows (alternative solutions)

I looked into this before buying a Mac Mini. The answer is, essentially, no. You pretty much have to buy a Leopard Mac to do iPhone SDK development for apps that run on non-jailbroken iPhones.

Not that it's 100% impossible, but it's 99.99% unreasonable. Like changing light bulbs with your feet.

Not only do you have to be in Xcode, but you have to get certificates into the Keychain manager to be able to have Xcode and the iPhone communicate. And you have to set all kinds of setting in Xcode just right.

How to extract the n-th elements from a list of tuples?

This also works:

zip(*elements)[1]

(I am mainly posting this, to prove to myself that I have groked zip...)

See it in action:

>>> help(zip)

Help on built-in function zip in module builtin:

zip(...)

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.

>>> elements = [(1,1,1),(2,3,7),(3,5,10)]
>>> zip(*elements)
[(1, 2, 3), (1, 3, 5), (1, 7, 10)]
>>> zip(*elements)[1]
(1, 3, 5)
>>>

Neat thing I learned today: Use *list in arguments to create a parameter list for a function...

Note: In Python3, zip returns an iterator, so instead use list(zip(*elements)) to return a list of tuples.

error: (-215) !empty() in function detectMultiScale

On OSX with a homebrew install the full path to the opencv folder should work:

face_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/3.4.0_1/share/OpenCV/haarcascades/haarcascade_eye.xml')

Take care of the version number in the path.

IIS - can't access page by ip address instead of localhost

In IIS Manager, I added a binding to the site specifying the IP address. Previously, all my bindings were host names.

DevTools failed to load SourceMap: Could not load content for chrome-extension

For me, the problem was caused not by the app in development itself but by the Chrome extension: React Developer Tool. I solved partially that by right-clicking the extension icon in the toolbar, clicking "manage extension" (I'm freely translating menu text here since my browser language is in Brazilian Portuguese), then enabling "Allow access to files URLs." But this measure fixed just some of the alerts.

I found issues in the react repo that suggests the cause is a bug in their extension and is planned to be corrected soon - see issues 20091 and 20075.

You can confirm is extension-related by accessing your app in an anonymous tab without any extension enabled.

How do I escape ampersands in batch files?

From a cmd:

  • & is escaped like this: ^& (based on @Wael Dalloul's answer)
  • % does not need to be escaped

An example:

start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%20and%20percentage+in+cmd^&sourceid=opera^&ie=utf-8^&oe=utf-8

From a batch file

  • & is escaped like this: ^& (based on @Wael Dalloul's answer)
  • % is escaped like this: %% (based on the OPs update)

An example:

start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%%20and%%20percentage+in+batch+file^&sourceid=opera^&ie=utf-8^&oe=utf-8

Checking if an Android application is running in the background

This code will check foreground and background in any condition:

Java Code:

private static boolean isApplicationForeground(Context context) {
    KeyguardManager keyguardManager =
            (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);

    if (keyguardManager.isKeyguardLocked()) {
        return false;
    }
    int myPid = Process.myPid();

    ActivityManager activityManager =
            (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

    List<ActivityManager.RunningAppProcessInfo> list;

    if ((list = activityManager.getRunningAppProcesses()) != null) {
        for (ActivityManager.RunningAppProcessInfo aList : list) {
            ActivityManager.RunningAppProcessInfo info;
            if ((info = aList).pid == myPid) {
                return info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
            }
        }
    }
    return false;
}

Kotlin Code:

private fun isApplicationForeground(context: Context): Boolean {
        val keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
        if (keyguardManager.isKeyguardLocked) {
            return false
        }
        val myPid = Process.myPid()
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        var list: List<ActivityManager.RunningAppProcessInfo>
        if (activityManager.runningAppProcesses.also { list = it } != null) {
            for (aList in list) {
                var info: ActivityManager.RunningAppProcessInfo
                if (aList.also { info = it }.pid == myPid) {
                    return info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                }
            }
        }
        return false
    }

What is the difference between ( for... in ) and ( for... of ) statements?

I found the following explanation from https://javascript.info/array very helpful:

One of the oldest ways to cycle array items is the for loop over indexes:

let arr = ["Apple", "Orange", "Pear"];

for (let i = 0; i < arr.length; i++) { alert( arr[i] ); } But for arrays there is another form of loop, for..of:

let fruits = ["Apple", "Orange", "Plum"];

// iterates over array elements for (let fruit of fruits) { alert( fruit ); } The for..of doesn’t give access to the number of the current element, just its value, but in most cases that’s enough. And it’s shorter.

Technically, because arrays are objects, it is also possible to use for..in:

let arr = ["Apple", "Orange", "Pear"];

for (let key in arr) { alert( arr[key] ); // Apple, Orange, Pear } But that’s actually a bad idea. There are potential problems with it:

The loop for..in iterates over all properties, not only the numeric ones.

There are so-called “array-like” objects in the browser and in other environments, that look like arrays. That is, they have length and indexes properties, but they may also have other non-numeric properties and methods, which we usually don’t need. The for..in loop will list them though. So if we need to work with array-like objects, then these “extra” properties can become a problem.

The for..in loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it’s still very fast. The speedup may only matter in bottlenecks. But still we should be aware of the difference.

Generally, we shouldn’t use for..in for arrays.

Regex for not empty and not whitespace

/^$|\s+/ This matches when empty or white spaces

/(?!^$)([^\s])/ This matches when its not empty or white spaces

Send JSON via POST in C# and Receive the JSON returned?

You can also use the PostAsJsonAsync() method available in HttpClient()

_x000D_
_x000D_
   var requestObj= JsonConvert.SerializeObject(obj);_x000D_
   HttpResponseMessage response = await    client.PostAsJsonAsync($"endpoint",requestObj).ConfigureAwait(false);
_x000D_
_x000D_
_x000D_

How do I free my port 80 on localhost Windows?

in my case,window iis to stop Web Deployment Agent Service.Type in cmd

 net stop msdepsvc 

How to set the action for a UIBarButtonItem in Swift

Swift 5 & iOS 13+ Programmatic Example

  1. You must mark your function with @objc, see below example!
  2. No parenthesis following after the function name! Just use #selector(name).
  3. private or public doesn't matter; you can use private.

Code Example

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    let menuButtonImage = UIImage(systemName: "flame")
    let menuButton = UIBarButtonItem(image: menuButtonImage, style: .plain, target: self, action: #selector(didTapMenuButton))
    navigationItem.rightBarButtonItem = menuButton
}

@objc public func didTapMenuButton() {
    print("Hello World")
}

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

I was using CakePHP and I was seeing this error:

This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500

I went to see the CakePHP Debug Level defined at app\config\core.php:

/**
 * CakePHP Debug Level:
 *
 * Production Mode:
 *  0: No error messages, errors, or warnings shown. Flash messages redirect.
 *
 * Development Mode:
 *  1: Errors and warnings shown, model caches refreshed, flash messages halted.
 *  2: As in 1, but also with full debug messages and SQL output.
 *  3: As in 2, but also with full controller dump.
 *
 * In production mode, flash messages redirect after a time interval.
 * In development mode, you need to click the flash message to continue.
 */
Configure::write('debug', 0);

I chanted the value from 0 to 1:

Configure::write('debug', 1);

After this change, when trying to reload the page again, I saw the corresponding error:

Fatal error: Uncaught Exception: Facebook needs the CURL PHP extension.

Conclusion: The solution in my case to see the errors was to change the CakePHP Debug Level from 0 to 1 in order to show errors and warnings.

How to input a string from user into environment variable from batch file

A rather roundabout way, just for completeness:

 for /f "delims=" %i in ('type CON') do set inp=%i

Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.

How to get selected value from Dropdown list in JavaScript

Direct value should work just fine:

var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

How to get object length

Summarizing all together, here is a universal function (including ie8 support):

_x000D_
_x000D_
var objSize = function(obj) {_x000D_
    var count = 0;_x000D_
    _x000D_
    if (typeof obj == "object") {_x000D_
    _x000D_
        if (Object.keys) {_x000D_
            count = Object.keys(obj).length;_x000D_
        } else if (window._) {_x000D_
            count = _.keys(obj).length;_x000D_
        } else if (window.$) {_x000D_
            count = $.map(obj, function() { return 1; }).length;_x000D_
        } else {_x000D_
            for (var key in obj) if (obj.hasOwnProperty(key)) count++;_x000D_
        }_x000D_
        _x000D_
    }_x000D_
    _x000D_
    return count;_x000D_
};_x000D_
_x000D_
document.write(objSize({ a: 1, b: 2, c: 3 }));_x000D_
// 3
_x000D_
_x000D_
_x000D_

Copy every nth line from one sheet to another

insert a new column and put a series in 1,2,3,4, etc. Then create another new column and use the command =if(int(a1/7)=(a1/7),1,0) you should get a 1 in every 7th row, filter the column on the 1

The system cannot find the file specified. in Visual Studio

Another take on this that hasn't been mentioned here is that, when in debug, the project may build, but it won't run, giving the error message displayed in the question.

If this is the case, another option to look at is the output file versus the target file. These should match.

A quick way to check the output file is to go to the project's property pages, then go to Configuration Properties -> Linker -> General (In VS 2013 - exact path may vary depending on IDE version).

There is an "Output File" setting. If it is not $(OutDir)$(TargetName)$(TargetExt), then you may run into issues.

This is also discussed in more detail here.

How to install the current version of Go in Ubuntu Precise

You can use a script from udhos/update-golang.

Here is a two-liner as example (run as root):

bash <(curl -s https://raw.githubusercontent.com/udhos/update-golang/master/update-golang.sh)
ln -vs /usr/local/go/bin/go* /usr/local/bin/

How do I install PIL/Pillow for Python 3.6?

You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:

pip install some-package.whl

If you have problem to install the wheel read this answer

Splitting String and put it on int array

List<String> stringList = new ArrayList<String>(Arrays.asList(arr.split(",")));
List<Integer> intList = new ArrayList<Integer>();
for (String s : stringList) 
   intList.add(Integer.valueOf(s));

C# SQL Server - Passing a list to a stored procedure

The typical pattern in this situation is to pass the elements in a comma delimited list, and then in SQL split that out into a table you can use. Most people usually create a specified function for doing this like:

 INSERT INTO <SomeTempTable>
 SELECT item FROM dbo.SplitCommaString(@myParameter)

And then you can use it in other queries.

How to ignore SSL certificate errors in Apache HttpClient 4.0

We are using HTTPClient 4.3.5 and we tried almost all solutions exist on the stackoverflow but nothing, After thinking and figuring out the problem, we come to the following code which works perfectly, just add it before creating HttpClient instance.

some method to call when making post requests....

SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    });

    SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
    HttpPost postRequest = new HttpPost(url);

continue your request in the normal form

How to set UITextField height?

try this

UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(20, 80, 280, 120)];

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

you just need to run the command as a super user:

just type from the terminal: sudo su mongod

Change color of Button when Mouse is over

<Button Content="Click" Width="200" Height="50">
<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="LightBlue" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="Border" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="LightGreen" TargetName="Border" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Button.Style>

How do I write to a Python subprocess' stdin?

It might be better to use communicate:

from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]

"Better", because of this warning:

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

How to determine the first and last iteration in a foreach loop?

An attempt to find the first would be:

$first = true; 
foreach ( $obj as $value )
{
  if ( $first )
  {
    // do something
    $first = false; //in order not to get into the if statement for the next loops
  }
  else
  {
    // do something else for all loops except the first
  }
}

How to revert a merge commit that's already pushed to remote branch?

This is a very old thread, but I am missing another in my opinion convenient solution:

I never revert a merge. I just create another branch from the revision where everything was ok and then cherry pick everything that needs to picked from the old branch which was added in between.

So, if the GIT history is like this:

  • d
  • c
  • b <<< the merge
  • a
  • ...

I create a new branch from a, cherry pick c and d and then the new branch is clear from b. I can ever decide to do the merge of "b" in my new branch again. The old branch becomes deprecated and will be deleted if "b" is not necessary anymore or still in another (feature/hotfix) branch.

The only problem is now one of the very hardest things in computer science: How do you name the new branch? ;)

Ok, if you failed esp. in devel, you create newdevel as mentioned above, delete old devel and rename newdevel to devel. Mission accomplished. You can now merge the changes again when you want. It is like never merged before....

get parent's view from a layout

The getParent method returns a ViewParent, not a View. You need to cast the first call to getParent() also:

RelativeLayout r = (RelativeLayout) ((ViewGroup) this.getParent()).getParent();

As stated in the comments by the OP, this is causing a NPE. To debug, split this up into multiple parts:

ViewParent parent = this.getParent();
RelativeLayout r;
if (parent == null) {
    Log.d("TEST", "this.getParent() is null");
}
else {
    if (parent instanceof ViewGroup) {
        ViewParent grandparent = ((ViewGroup) parent).getParent();
        if (grandparent == null) {
            Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is null");
        }
        else {
            if (parent instanceof RelativeLayout) {
                r = (RelativeLayout) grandparent;
            }
            else {
                Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is not a RelativeLayout");
            }
        }
    }
    else {
        Log.d("TEST", "this.getParent() is not a ViewGroup");
    }
}

//now r is set to the desired RelativeLayout.

Check free disk space for current partition in bash

I think this should be a comment or an edit to ThinkingMedia's answer on this very question (Check free disk space for current partition in bash), but I am not allowed to comment (not enough rep) and my edit has been rejected (reason: "this should be a comment or an answer"). So please, powers of the SO universe, don't damn me for repeating and fixing someone else's "answer". But someone on the internet was wrong!™ and they wouldn't let me fix it.

The code

  df --output=avail -h "$PWD" | sed '1d;s/[^0-9]//g'

has a substantial flaw: Yes, it will output 50G free as 50 -- but it will also output 5.0M free as 50 or 3.4G free as 34 or 15K free as 15.

To create a script with the purpose of checking for a certain amount of free disk space you have to know the unit you're checking against. Remove it (as sed does in the example above) the numbers don't make sense anymore.

If you actually want it to work, you will have to do something like:

FREE=`df -k --output=avail "$PWD" | tail -n1`   # df -k not df -h
if [[ $FREE -lt 10485760 ]]; then               # 10G = 10*1024*1024k
     # less than 10GBs free!
fi;

Also for an installer to df -k $INSTALL_TARGET_DIRECTORY might make more sense than df -k "$PWD". Finally, please note that the --output flag is not available in every version of df / linux.

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

Is it possible to make abstract classes in Python?

Most Previous answers were correct but here is the answer and example for Python 3.7. Yes, you can create an abstract class and method. Just as a reminder sometimes a class should define a method which logically belongs to a class, but that class cannot specify how to implement the method. For example, in the below Parents and Babies classes they both eat but the implementation will be different for each because babies and parents eat a different kind of food and the number of times they eat is different. So, eat method subclasses overrides AbstractClass.eat.

from abc import ABC, abstractmethod

class AbstractClass(ABC):

    def __init__(self, value):
        self.value = value
        super().__init__()

    @abstractmethod
    def eat(self):
        pass

class Parents(AbstractClass):
    def eat(self):
        return "eat solid food "+ str(self.value) + " times each day"

class Babies(AbstractClass):
    def eat(self):
        return "Milk only "+ str(self.value) + " times or more each day"

food = 3    
mom = Parents(food)
print("moms ----------")
print(mom.eat())

infant = Babies(food)
print("infants ----------")
print(infant.eat())

OUTPUT:

moms ----------
eat solid food 3 times each day
infants ----------
Milk only 3 times or more each day

When do I use the PHP constant "PHP_EOL"?

The definition of PHP_EOL is that it gives you the newline character of the operating system you're working on.

In practice, you should almost never need this. Consider a few cases:

  • When you are outputting to the web, there really isn't any convention except that you should be consistent. Since most servers are Unixy, you'll want to use a "\n" anyway.

  • If you're outputting to a file, PHP_EOL might seem like a good idea. However, you can get a similar effect by having a literal newline inside your file, and this will help you out if you're trying to run some CRLF formatted files on Unix without clobbering existing newlines (as a guy with a dual-boot system, I can say that I prefer the latter behavior)

PHP_EOL is so ridiculously long that it's really not worth using it.

Left Join without duplicate rows from left table

Try an OUTER APPLY

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    OUTER APPLY
    (
        SELECT TOP 1 *
        FROM tbl_Media M 
        WHERE M.Content_Id = C.Content_Id 
    ) m
ORDER BY 
    C.Content_DatePublished ASC

Alternatively, you could GROUP BY the results

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
GROUP BY
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
ORDER BY
    C.Content_DatePublished ASC

The OUTER APPLY selects a single row (or none) that matches each row from the left table.

The GROUP BY performs the entire join, but then collapses the final result rows on the provided columns.

How to check for an undefined or null variable in JavaScript?

here's another way using the Array includes() method:

[undefined, null].includes(value)

Clear and reset form input fields

/* See newState and use of it in eventSubmit() for resetting all the state. I have tested it is working for me. Please let me know for mistakes */

import React from 'react';
    
    const newState = {
        fullname: '',
        email: ''
    }
    
    class Form extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                fullname: ' ',
                email: ' '
            }
    
            this.eventChange = this
                .eventChange
                .bind(this);
            this.eventSubmit = this
                .eventSubmit
                .bind(this);
        }
        eventChange(event) {
            const target = event.target;
            const value = target.type === 'checkbox'
                ? target.type
                : target.value;
            const name = target.name;
    
            this.setState({[name]: value})
        }
    
        eventSubmit(event) {
            alert(JSON.stringify(this.state))
            event.preventDefault();
            this.setState({...newState});
        }
    
        render() {
            return (
                <div className="container">
                    <form className="row mt-5" onSubmit={this.eventSubmit}>
                        <label className="col-md-12">
                            Full Name
                            <input
                                type="text"
                                name="fullname"
                                id="fullname"
                                value={this.state.fullname}
                                onChange={this.eventChange}/>
                        </label>
                        <label className="col-md-12">
                            email
                            <input
                                type="text"
                                name="email"
                                id="email"
                                value={this.state.value}
                                onChange={this.eventChange}/>
                        </label>
                        <input type="submit" value="Submit"/>
                    </form>
                </div>
            )
        }
    }
    
    export default Form;
    

Sort Pandas Dataframe by Date

sort method has been deprecated and replaced with sort_values. After converting to datetime object using df['Date']=pd.to_datetime(df['Date'])

df.sort_values(by=['Date'])

Note: to sort in-place and/or in a descending order (the most recent first):

df.sort_values(by=['Date'], inplace=True, ascending=False)

ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.

error: the details of the application error from being viewed remotely

This can be the message you receive even when custom errors is turned off in web.config file. It can mean you have run out of free space on the drive that hosts the application. Clean your log files if you have no other space to gain on the drive.

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

How to read json file into java with simple JSON library

Add Jackson databind:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0.pr2</version>
</dependency>

Create DTO class with related fields and read JSON file:

ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);

Distinct by property of class with LINQ

You can't effectively use Distinct on a collection of objects (without additional work). I will explain why.

The documentation says:

It uses the default equality comparer, Default, to compare values.

For objects that means it uses the default equation method to compare objects (source). That is on their hash code. And since your objects don't implement the GetHashCode() and Equals methods, it will check on the reference of the object, which are not distinct.

Understanding colors on Android (six characters)

at new chrome version (maybe 67.0.3396.62) , CSS hex color can use this model display,

eg:

div{
  background-color:#FF00FFcc;
}

cc is opacity , but old chrome not support that mod

Create view with primary key?

A little late to this party - but this also works well:

CREATE VIEW [ABC].[View_SomeDataUniqueKey]
AS
SELECT 
CAST(CONCAT(CAST([ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY [ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,[ID]
FROM SOME_TABLE JOIN SOME_OTHER_TABLE
GO

In my case the join resulted in [ID] - the primary key being repeated up to 5 times (associated different unique data) The nice trick with this is that the original ID can be determined from each UniqueID effectively [ID]+RowNumber() = 11, 12, 13, 14, 21, 22, 23, 24 etc. If you add RowNumber() and [ID] back into the view - you can easily determine your original key from the data. But - this is not something that should be committed to a table because I am fairly sure that the RowNumber() of a view will never be reliably the same as the underlying data alters, even with the OVER(ORDER BY [ID] ASC) to try and help it.

Example output ( Select UniqueId, ID, ROWNR, Name from [REF].[View_Systems] ) :

UniqueId ID ROWNR Name 11 1 1 Amazon A 12 1 2 Amazon B 13 1 3 Amazon C 14 1 4 Amazon D 15 1 5 Amazon E

Table1:

[ID] [Name] 1 Amazon

Table2:

[ID] [Version] 1 A 1 B 1 C 1 D 1 E

CREATE VIEW [REF].[View_Systems]
AS    
SELECT 
CAST(CONCAT(CAST(TABA.[ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY TABA.[ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,TABA.[ID]
,ROW_NUMBER()  OVER(ORDER BY TABA.[ID] ASC) AS ROWNR
,TABA.[Name]  
FROM  [Ref].[Table1] TABA LEFT JOIN [Ref].[Table2] TABB ON TABA.[ID] = TABB.[ID]
GO

How to get the query string by javascript?

You can use this Javascript :

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

OR

You can also use the plugin jQuery-URL-Parser allows to retrieve all parts of URL, including anchor, host, etc.

Usage is very simple and cool:

$.url().param("itemID")

via James&Alfa

Peak memory usage of a linux/unix process

Well, if you really want to show the memory peak and some more in-depth statistics i recommend using a profiler such as valgrind. A nice valgrind front-end is alleyoop.

Get JSON Data from URL Using Android?

private class GetProfileRequestAsyncTasks extends AsyncTask<String, Void, JSONObject> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected JSONObject doInBackground(String... urls) {
        if (urls.length > 0) {
            String url = urls[0];
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            httpget.setHeader("x-li-format", "json");
            try {
                HttpResponse response = httpClient.execute(httpget);
                if (response != null) {
                    //If status is OK 200
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String result = EntityUtils.toString(response.getEntity());
                        //Convert the string result to a JSON Object
                        return new JSONObject(result);
                    }
                }
            } catch (IOException e) {

            } catch (JSONException e) {
            }
        }
        return null;
    }
    @Override
    protected void onPostExecute(JSONObject data) {
        if (data != null) {
            Log.d(TAG, String.valueOf(data));
        }
    }

}

Outputting data from unit test in Python

You can use simple print statements, or any other way of writing to stdout. You can also invoke the Python debugger anywhere in your tests.

If you use nose to run your tests (which I recommend), it will collect the stdout for each test and only show it to you if the test failed, so you don't have to live with the cluttered output when the tests pass.

nose also has switches to automatically show variables mentioned in asserts, or to invoke the debugger on failed tests. For example -s (--nocapture) prevents the capture of stdout.

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

Well, there are many solutions already given above. If there are none of them works, maybe you should just try to reset your password again to 'root' as described here, and then reopen http://localhost/phpMyAdmin/ in other browser. At least this solution works for me.

Cannot use Server.MapPath

Try adding System.Web as a reference to your project.

Java compiler level does not match the version of the installed Java project facet

Right click the project and select properties Click the java compiler from the left and change to your required version Hope this helps

SQL to Query text in access with an apostrophe in it

...better is declare the name as varible ,and ask before if thereis a apostrophe in the string:

e.g.:

DIM YourName string

YourName = "Daniel O'Neal"

  If InStr(YourName, "'") Then
      SELECT * FROM tblStudents WHERE [name]  Like """ Your Name """ ;
   else
      SELECT * FROM tblStudents WHERE [name] Like '" Your Name "' ;       
  endif

Display text from .txt file in batch file

Here is a good date and time code:

@echo off
if %date:~4,2%==01 set month=January
if %date:~4,2%==02 set month=February
if %date:~4,2%==03 set month=March
if %date:~4,2%==04 set month=April
if %date:~4,2%==05 set month=May
if %date:~4,2%==06 set month=June
if %date:~4,2%==07 set month=July
if %date:~4,2%==08 set month=August
if %date:~4,2%==09 set month=September
if %date:~4,2%==10 set month=October
if %date:~4,2%==11 set month=November
if %date:~4,2%==12 set month=December

if %date:~0,3%==Mon set day=Monday
if %date:~0,3%==Tue set day=Tuesday
if %date:~0,3%==Wed set day=Wednesday
if %date:~0,3%==Thu set day=Thursday
if %date:~0,3%==Fri set day=Friday
if %date:~0,3%==Sat set day=Saturday
if %date:~0,3%==Sun set day=Sunday
echo.
echo The Date is %day%, %month% %date:~7,2%, %date:~10,4% the current time is: %time:~0,5%
pause

Outputs: The Date is Sunday, September 27, 2009 the current time is: 3:07

Limiting number of displayed results when using ngRepeat

Use limitTo filter to display a limited number of results in ng-repeat.

<ul class="phones">
      <li ng-repeat="phone in phones | limitTo:5">
        {{phone.name}}
        <p>{{phone.snippet}}</p>
      </li>
</ul>

Eclipse DDMS error "Can't bind to local 8600 for debugger"

For people running Android Studio and Eclipse:

I know that answers are already saturated, but I'll just add that it appears that this error surfaces after installing Android Studio and returning to Eclipse to build and run your project.

Make sure you close all other instances of ADB that may be running (including Android Studio). Once you've done this if you are still having troubles try killing all ADB server processes and restarting. If you haven't setup a global variable, open terminal and navigate to the platform-tools folder of the Android SDK Eclipse is referencing, then run:

./adb kill-server
./adb start-server

How to convert 1 to true or 0 to false upon model fetch

Assigning Comparison to property value

JavaScript

You could assign the comparison of the property to "1"

obj["isChecked"] = (obj["isChecked"]==="1");

This only evaluates for a String value of "1" though. Other variables evaulate to false like an actual typeof number would be false. (i.e. obj["isChecked"]=1)

If you wanted to be indiscrimate about "1" or 1, you could use:

obj["isChecked"] = (obj["isChecked"]=="1");

Example Outputs

console.log(obj["isChecked"]==="1"); // true
console.log(obj["isChecked"]===1); // false
console.log(obj["isChecked"]==1); // true
console.log(obj["isChecked"]==="0"); // false
console.log(obj["isChecked"]==="Elephant"); // false

PHP

Same concept in PHP

$obj["isChecked"] = ($obj["isChecked"] == "1");

The same operator limitations as stated above for JavaScript apply.

Double Not

The 'double not' also works. It's confusing when people first read it but it works in both languages for integer/number type values. It however does not work in JavaScript for string type values as they always evaluate to true:

JavaScript

!!"1"; //true
!!"0"; //true
!!1; //true
!!0; //false
!!parseInt("0",10); // false

PHP

echo !!"1"; //true
echo !!"0"; //false
echo !!1; //true
echo !!0; //false

How to merge two files line by line in Bash

Check

man paste

possible followed by some command like untabify or tabs2spaces

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

For Single valued associations, i.e.-One-to-One and Many-to-One:-
Default Lazy=proxy
Proxy lazy loading:- This implies a proxy object of your associated entity is loaded. This means that only the id connecting the two entities is loaded for the proxy object of associated entity.
Eg: A and B are two entities with Many to one association. ie: There may be multiple A's for every B. Every object of A will contain a reference of B.
`

public class A{
    int aid;
    //some other A parameters;
    B b;
}
public class B{
    int bid;
     //some other B parameters;
}

`
The relation A will contain columns(aid,bid,...other columns of entity A).
The relation B will contain columns(bid,...other columns of entity B)

Proxy implies when A is fetched, only id is fetched for B and stored into a proxy object of B which contains only id. Proxy object of B is a an object of a proxy-class which is a subclass of B with only minimal fields. Since bid is already part of relation A, it is not necessary to fire a query to get bid from the relation B. Other attributes of entity B are lazily loaded only when a field other than bid is accessed.

For Collections, i.e.-Many-to-Many and One-to-Many:-
Default Lazy=true


Please also note that the fetch strategy(select,join etc) can override lazy. ie: If lazy='true' and fetch='join', fetching of A will also fetch B or Bs(In case of collections). You can get the reason if you think about it.
Default fetch for single valued association is "join".
Default fetch for collections is "select". Please verify the last two lines. I have deduced that logically.

How to do Base64 encoding in node.js?

I have created a ultimate small js npm library for the base64 encode/decode conversion in Node.js.

Installation

npm install nodejs-base64-converter --save

Usage

var nodeBase64 = require('nodejs-base64-converter');

console.log(nodeBase64.encode("test text")); //dGVzdCB0ZXh0
console.log(nodeBase64.decode("dGVzdCB0ZXh0")); //test text

NPM doesn't install module dependencies

I suspect you're facing the issue where your package.json file is not in the same directory as your Gruntfile.js. When you run your grunt xxx commands, you get error an message like:

Local Npm module "xxx" not found. Is it installed?

For now, the solution is:

  • Create package.json in the same directory as Gruntfile.js
  • Define the modules required by your grunt project
  • Execute npm install to load them locally
  • Now the required grunt command should work.

IMHO, it is sad that we cannot have grunt resolve modules loaded from a parent npm module (i.e. package.json in a parent directory within the same project). The discussion here seems to indicate that it was done to avoid loading "global" modules but I think what we want is loading from "my project" modules instead.

How to get a list of programs running with nohup

When I started with $ nohup storm dev-zookeper ,

METHOD1 : using jobs,

prayagupd@prayagupd:/home/vmfest# jobs -l
[1]+ 11129 Running                 nohup ~/bin/storm/bin/storm dev-zookeeper &

METHOD2 : using ps command.

$ ps xw
PID  TTY      STAT   TIME COMMAND
1031 tty1     Ss+    0:00 /sbin/getty -8 38400 tty1
10582 ?        S      0:01 [kworker/0:0]
10826 ?        Sl     0:18 java -server -Dstorm.options= -Dstorm.home=/root/bin/storm -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dsto
10853 ?        Ss     0:00 sshd: vmfest [priv] 

TTY column with ? => nohup running programs.

Description

  • TTY column = the terminal associated with the process
  • STAT column = state of a process
    • S = interruptible sleep (waiting for an event to complete)
    • l = is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)

Reference

$ man ps # then search /PROCESS STATE CODES

Requery a subform from another form?

Just a comment on the method of accomplishing this:

You're making your EntryForm permanently tied to the form you're calling it from. I think it's better to not have forms tied to context like that. I'd remove the requery from the Save/Close routine and instead open the EntryForm modally, using the acDialog switch:

  DoCmd.OpenForm "EntryForm", , ,"[ID]=" & Me!SubForm.Form!ID, , acDialog
  Me!SubForm.Form.Requery

That way, EntryForm is not tied down to use in one context. The alternative is to complicate EntryForm with something that is knowledgable of which form opened it and what needs to requeried. I think it's better to keep that kind of thing as close to the context in which it's used, and keep the called form's code as simple as possible.

Perhaps a principle here is that any time you are requerying a form using the Forms collection from another form, it's a good indication something's not right about your architecture -- that should happen seldom, in my opinion.

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

This kind of error can also happen when using COPY and having an escaped string containing NULL values(00) such as:

"H\x00\x00\x00tj\xA8\x9E#D\x98+\xCA\xF0\xA7\xBBl\xC5\x19\xD7\x8D\xB6\x18\xEDJ\x1En"

If you use COPY without specifying the format 'CSV' postgres by default will assume format 'text'. This has a different interaction with backlashes, see text format.

If you're using COPY or a file_fdw make sure to specify format 'CSV' to avoid this kind of errors.

CSS Auto hide elements after 5 seconds

based from the answer of @SW4, you could also add a little animation at the end.

_x000D_
_x000D_
body > div{_x000D_
    border:1px solid grey;_x000D_
}_x000D_
html, body, #container {_x000D_
    height:100%;_x000D_
    width:100%;_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
#container {_x000D_
    overflow:hidden;_x000D_
    position:relative;_x000D_
}_x000D_
#hideMe {_x000D_
    -webkit-animation: cssAnimation 5s forwards; _x000D_
    animation: cssAnimation 5s forwards;_x000D_
}_x000D_
@keyframes cssAnimation {_x000D_
    0%   {opacity: 1;}_x000D_
    90%  {opacity: 1;}_x000D_
    100% {opacity: 0;}_x000D_
}_x000D_
@-webkit-keyframes cssAnimation {_x000D_
    0%   {opacity: 1;}_x000D_
    90%  {opacity: 1;}_x000D_
    100% {opacity: 0;}_x000D_
}
_x000D_
<div>_x000D_
<div id='container'>_x000D_
    <div id='hideMe'>Wait for it...</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Making the remaining 0.5 seconds to animate the opacity attribute. Just make sure to do the math if you're changing the length, in this case, 90% of 5 seconds leaves us 0.5 seconds to animate the opacity.

How to save a plot into a PDF file without a large margin around

This works for displaying purposes:

set(gca(), 'LooseInset', get(gca(), 'TightInset'));

Should work for printing as well.

How to solve time out in phpmyadmin?

If even after repeated upload you still get timeout error, pleasechange your settings in

\phpmyadmin\libraries\config.default.php

from $cfg['ExecTimeLimit'] = 300; to $cfg['ExecTimeLimit'] = 0; and restart. Now there is no execution time limit (trust we are talking about local server).

Source : Change Script time out in phpmyadmin

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

Slightly different option usually works for me:

  1. "mvn eclipse:eclipse" for this project in the command line.
  2. "Refresh/F5" this project in eclipse.

That's all, no need to re-import but need to have the terminal window handy.

SQLite3 database or disk is full / the database disk image is malformed

To repair a corrupt database you can use the sqlite3 commandline utility. Type in the following commands in a shell after setting the environment variables:

cd $DATABASE_LOCATION
echo '.dump'|sqlite3 $DB_NAME|sqlite3 repaired_$DB_NAME
mv $DB_NAME corrupt_$DB_NAME
mv repaired_$DB_NAME $DB_NAME

This code helped me recover a SQLite database I use as a persistent store for Core Data and which produced the following error upon save:

Could not save: NSError 259 in Domain NSCocoaErrorDomain { NSFilePath = mydata.db NSUnderlyingException = Fatal error. The database at mydata.db is corrupted. SQLite error code:11, 'database disk image is malformed' }

wget command to download a file and save as a different filename

wget -O yourfilename.zip remote-storage.url/theirfilename.zip

will do the trick for you.

Note:

a) its a capital O.

b) wget -O filename url will only work. Putting -O last will not.

how to get login option for phpmyadmin in xampp

If you wish to go to the login page of phpmyadmin, click the "exit" button (the second one from left to right under the main logo "phpmyadmin").

Pandas read_csv low_memory and dtype options

It worked for me with low_memory = False while importing a DataFrame. That is all the change that worked for me:

df = pd.read_csv('export4_16.csv',low_memory=False)

jQuery - Add active class and remove active from other element on click

Use jquery cookie https://github.com/carhartl/jquery-cookie and then you can be sure the class will stay on page refresh.

Stores the id of the clicked element in the cookie and then uses that to add the class on refresh.

        //Get cookie value and set active
        var tab = $.cookie('active');
        $('#' + tab).addClass('active');

        //Set cookie active tab value on click
        //Done this way to preserve after page refresh
        $('.topTab').click(function (event) {
            var clickedTab = event.target.id;
            $.removeCookie('active', { path: '/' });
            $( '.active' ).removeClass( 'active' );
            $.cookie('active', clickedTab, { path: '/' });
        });

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

Undo git pull, how to bring repos to old state

Running git pull performs the following tasks, in order:

  1. git fetch
  2. git merge

The merge step combines branches that have been setup to be merged in your config. You want to undo the merge step, but probably not the fetch (doesn't make a lot of sense and shouldn't be necessary).

To undo the merge, use git reset --hard to reset the local repository to a previous state; use git-reflog to find the SHA-1 of the previous state and then reset to it.

Warning

The commands listed in this section remove all uncommitted changes, potentially leading to a loss of work:

git reset --hard

Alternatively, reset to a particular point in time, such as:

git reset --hard master@{"10 minutes ago"}

How do I use shell variables in an awk script?

You could pass in the command-line option -v with a variable name (v) and a value (=) of the environment variable ("${v}"):

% awk -vv="${v}" 'BEGIN { print v }'
123test

Or to make it clearer (with far fewer vs):

% environment_variable=123test
% awk -vawk_variable="${environment_variable}" 'BEGIN { print awk_variable }'
123test

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

All of the answers above are correct, for the case of DISTINCT on a single column vs GROUP BY on a single column. Every db engine has its own implementation and optimizations, and if you care about the very little difference (in most cases) then you have to test against specific server AND specific version! As implementations may change...

BUT, if you select more than one column in the query, then the DISTINCT is essentially different! Because in this case it will compare ALL columns of all rows, instead of just one column.

So if you have something like:

// This will NOT return unique by [id], but unique by (id,name)
SELECT DISTINCT id, name FROM some_query_with_joins

// This will select unique by [id].
SELECT id, name FROM some_query_with_joins GROUP BY id

It is a common mistake to think that DISTINCT keyword distinguishes rows by the first column you specified, but the DISTINCT is a general keyword in this manner.

So people you have to be careful not to take the answers above as correct for all cases... You might get confused and get the wrong results while all you wanted was to optimize!

OpenCV in Android Studio

Anybody facing problemn while creating jniLibs cpp is shown ..just add ndk ..

How can I check if mysql is installed on ubuntu?

With this command:

 dpkg -s mysql-server | grep Status

When to use Comparable and Comparator

My annotation lib for implementing Comparable and Comparator:

public class Person implements Comparable<Person> {         
    private String firstName;  
    private String lastName;         
    private int age;         
    private char gentle;         

    @Override         
    @CompaProperties({ @CompaProperty(property = "lastName"),              
        @CompaProperty(property = "age",  order = Order.DSC) })           
    public int compareTo(Person person) {                 
        return Compamatic.doComparasion(this, person);         
    }  
}

Click the link to see more examples. http://code.google.com/p/compamatic/wiki/CompamaticByExamples

How to shift a block of code left/right by one space in VSCode?

There was a feature request for that in vscode repo. But it was marked as extension-candidate and closed. So, here is the extension: Indent One space

Unlike the answer below that tells you to use Ctrl+[ this extension indents code by ONE whtespace ???.

enter image description here

Writing a dict to txt file and reading it back?

Hi there is a way to write and read the dictionary to file you can turn your dictionary to JSON format and read and write quickly just do this :

To write your date:

 import json

 your_dictionary = {"some_date" : "date"}
 f = open('destFile.txt', 'w+')
 f.write(json.dumps(your_dictionary))

and to read your data:

 import json

 f = open('destFile.txt', 'r')
 your_dictionary = json.loads(f.read())

How can I reorder my divs using only CSS?

If you know, or can enforce the size for the to-be-upper element, you could use

position : absolute;

In your css and give the divs their position.

otherwise javascript seems the only way to go:

fd = document.getElementById( 'firstDiv' );
sd = document.getElementById( 'secondDiv' );
fd.parentNode.removeChild( fd );
sd.parentNode.insertAfter( fd, sd );

or something similar.

edit: I just found this which might be useful: w3 document css3 move-to

How do I convert the date from one format to another date object in another format without using any deprecated classes?

Try this

This is the simplest way of changing one date format to another

public String changeDateFormatFromAnother(String date){
    @SuppressLint("SimpleDateFormat") DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    @SuppressLint("SimpleDateFormat") DateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy");
    String resultDate = "";
    try {
        resultDate=outputFormat.format(inputFormat.parse(date));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return resultDate;
}

How to list all available Kafka brokers in a cluster?

echo dump | nc localhost 2181 | grep brokers

(replace localhost with the host where zookeeper is running)

How to escape JSON string?

I have used following code to escape the string value for json. You need to add your '"' to the output of the following code:

public static string EscapeStringValue(string value)
{
    const char BACK_SLASH = '\\';
    const char SLASH = '/';
    const char DBL_QUOTE = '"';

    var output = new StringBuilder(value.Length);
    foreach (char c in value)
    {
        switch (c)
        {
            case SLASH:
                output.AppendFormat("{0}{1}", BACK_SLASH, SLASH);
                break;

            case BACK_SLASH:
                output.AppendFormat("{0}{0}", BACK_SLASH);
                break;

            case DBL_QUOTE:
                output.AppendFormat("{0}{1}",BACK_SLASH,DBL_QUOTE);
                break;

            default:
                output.Append(c);
                break;
        }
    }

    return output.ToString();
}

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

This worked for me.

mElement.sendKeys(Keys.HOME,Keys.chord(Keys.SHIFT,Keys.END),MY_VALUE);

Routing HTTP Error 404.0 0x80070002

My solution, after trying EVERYTHING:

Bad deployment, an old PrecompiledApp.config was hanging around my deploy location, and making everything not work.

My final settings that worked:

  • IIS 7.5, Win2k8r2 x64,
  • Integrated mode application pool
  • Nothing changes in the web.config - this means no special handlers for routing. Here's my snapshot of the sections a lot of other posts reference. I'm using FluorineFX, so I do have that handler added, but I did not need any others:

    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <authentication mode="None"/>
    
      <pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
      <httpRuntime requestPathInvalidCharacters=""/>
    
      <httpModules>
        <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx"/>
      </httpModules>
    </system.web>
      <system.webServer>
        <!-- Modules for IIS 7.0 Integrated mode -->
        <modules>
          <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx" />
        </modules>
    
        <!-- Disable detection of IIS 6.0 / Classic mode ASP.NET configuration -->
        <validation validateIntegratedModeConfiguration="false" />
      </system.webServer>
    
  • Global.ashx: (only method of any note)

    void Application_Start(object sender, EventArgs e) {
        // Register routes...
        System.Web.Routing.Route echoRoute = new System.Web.Routing.Route(
              "{*message}",
            //the default value for the message
              new System.Web.Routing.RouteValueDictionary() { { "message", "" } },
            //any regular expression restrictions (i.e. @"[^\d].{4,}" means "does not start with number, at least 4 chars
              new System.Web.Routing.RouteValueDictionary() { { "message", @"[^\d].{4,}" } },
              new TestRoute.Handlers.PassthroughRouteHandler()
           );
    
        System.Web.Routing.RouteTable.Routes.Add(echoRoute);
    }
    
  • PassthroughRouteHandler.cs - this achieved an automatic conversion from http://andrew.arace.info/stackoverflow to http://andrew.arace.info/#stackoverflow which would then be handled by the default.aspx:

    public class PassthroughRouteHandler : IRouteHandler {
    
        public IHttpHandler GetHttpHandler(RequestContext requestContext) {
            HttpContext.Current.Items["IncomingMessage"] = requestContext.RouteData.Values["message"];
            requestContext.HttpContext.Response.Redirect("#" + HttpContext.Current.Items["IncomingMessage"], true);
            return null;
        }
    }
    

Replace missing values with column mean

Similar to the answer pointed out by @Thomas, This can also be done using ifelse() method of R:

for(i in 1:ncol(data)){
  data[,i]=ifelse(is.na(data[,i]),
                  ave(data[,i],FUN=function(y) mean(y, na.rm = TRUE)),
                  data[,i])
}

where, Arguments to ifelse(TEST, YES , NO) are:-

TEST- logical condition to be checked

YES- executed if the condition is True

NO- else when the condition is False

and ave(x, ..., FUN = mean) is method in R used for calculating averages of subsets of x[]

JQuery - Storing ajax response into global variable

There's no way around it except to store it. Memory paging should reduce potential issues there.

I would suggest instead of using a global variable called 'xml', do something more like this:

var dataStore = (function(){
    var xml;

    $.ajax({
      type: "GET",
      url: "test.xml",
      dataType: "xml",
      success : function(data) {
                    xml = data;
                }
    });

    return {getXml : function()
    {
        if (xml) return xml;
        // else show some error that it isn't loaded yet;
    }};
})();

then access it with:

$(dataStore.getXml()).find('something').attr('somethingElse');

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

Make sure that you have enter valid detail in application.properties and whether your database server is available. As a example when you are connecting with MySQL check whether XAMPP is running properly.

How to create a file in memory for user to download, but not through server?

All the above solutions didn't work in all browsers. Here is what finally works on IE 10+, Firefox and Chrome (and without jQuery or any other library):

save: function(filename, data) {
    var blob = new Blob([data], {type: 'text/csv'});
    if(window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveBlob(blob, filename);
    }
    else{
        var elem = window.document.createElement('a');
        elem.href = window.URL.createObjectURL(blob);
        elem.download = filename;        
        document.body.appendChild(elem);
        elem.click();        
        document.body.removeChild(elem);
    }
}

Note that, depending on your situation, you may also want to call URL.revokeObjectURL after removing elem. According to the docs for URL.createObjectURL:

Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them. Browsers will release these automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.

How is using OnClickListener interface different via XML and Java code?

These are exactly the same. android:onClick was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an OnClickListener on the Button, which calls your DoIt method.

Here is what using a android:onClick="DoIt" does internally:

Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DoIt(v);
    }
});

The only thing you trade off by using android:onClick, as usual with XML configuration, is that it becomes a bit more difficult to add dynamic content (programatically, you could decide to add one listener or another depending on your variables). But this is easily defeated by adding your test within the DoIt method.

What is the difference between $routeProvider and $stateProvider?

Both do the same work as they are used for routing purposes in SPA(Single Page Application).

1. Angular Routing - per $routeProvider docs

URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

HTML

<div ng-view></div>

Above tag will render the template from the $routeProvider.when() condition which you had mentioned in .config (configuration phase) of angular

Limitations:-

  • The page can only contain single ng-view on page
  • If your SPA has multiple small components on the page that you wanted to render based on some conditions, $routeProvider fails. (to achieve that, we need to use directives like ng-include, ng-switch, ng-if, ng-show, which looks bad to have them in SPA)
  • You can not relate between two routes like parent and child relationship.
  • You cannot show and hide a part of the view based on url pattern.

2. ui-router - per $stateProvider docs

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

Multiple & Named Views

Another great feature is the ability to have multiple ui-views in a template.

While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your views, and pairing those views with nested states.

HTML

<div ui-view>
    <div ui-view='header'></div>
    <div ui-view='content'></div>
    <div ui-view='footer'></div>
</div>

The majority of ui-router's power is it can manage nested state & views.

Pros

  • You can have multiple ui-view on single page
  • Various views can be nested in each other and maintained by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Another way you could do relative routing is by using only @ to change ui-view="some". This will replace the ui-view rather than checking if it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

For more Information Angular ui-router

For better flexibility with various nested view with states, I'd prefer you to go for ui-router

Using logging in multiple modules

The best practice would be to create a module separately which has only one method whose task we be to give a logger handler to the the calling method. Save this file as m_logger.py

import logger, logging

def getlogger():
    # logger
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    # create console handler and set level to debug
    #ch = logging.StreamHandler()
    ch = logging.FileHandler(r'log.txt')
    ch.setLevel(logging.DEBUG)
    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    # add formatter to ch
    ch.setFormatter(formatter)
    # add ch to logger
    logger.addHandler(ch)
    return logger

Now call the getlogger() method whenever logger handler is needed.

from m_logger import getlogger
logger = getlogger()
logger.info('My mssg')

Why use Redux over Facebook Flux?

I'm an early adopter and implemented a mid-large single page application using the Facebook Flux library.

As I'm a little late to the conversation I'll just point out that despite my best hopes Facebook seem to consider their Flux implementation to be a proof of concept and it has never received the attention it deserves.

I'd encourage you to play with it, as it exposes more of the inner working of the Flux architecture which is quite educational, but at the same time it does not provide many of the benefits that libraries like Redux provide (which aren't that important for small projects, but become very valuable for bigger ones).

We have decided that moving forward we will be moving to Redux and I suggest you do the same ;)

How do you kill a Thread in Java?

Generally you don't..

You ask it to interrupt whatever it is doing using Thread.interrupt() (javadoc link)

A good explanation of why is in the javadoc here (java technote link)

App.settings - the Angular way?

Here's my two solutions for this

1. Store in json files

Just make a json file and get in your component by $http.get() method. If I was need this very low then it's good and quick.

2. Store by using data services

If you want to store and use in all components or having large usage then it's better to use data service. Like this :

  1. Just create static folder inside src/app folder.

  2. Create a file named as fuels.ts into static folder. You can store other static files here also. Let define your data like this. Assuming you having fuels data.

__

export const Fuels {

   Fuel: [
    { "id": 1, "type": "A" },
    { "id": 2, "type": "B" },
    { "id": 3, "type": "C" },
    { "id": 4, "type": "D" },
   ];
   }
  1. Create a file name static.services.ts

__

import { Injectable } from "@angular/core";
import { Fuels } from "./static/fuels";

@Injectable()
export class StaticService {

  constructor() { }

  getFuelData(): Fuels[] {
    return Fuels;
  }
 }`
  1. Now You can make this available for every module

just import in app.module.ts file like this and change in providers

import { StaticService } from './static.services';

providers: [StaticService]

Now use this as StaticService in any module.

That's All.

laravel 5.4 upload image

You can use it by easy way, through store method in your controller

like the below

First, we must create a form with file input to let us upload our file.

{{Form::open(['route' => 'user.store', 'files' => true])}}

{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}

{{Form::close()}}

Here is how we can handle file in our controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{

  public function store(Request $request)
  {

  // get current time and append the upload file extension to it,
  // then put that name to $photoName variable.
  $photoName = time().'.'.$request->user_photo->getClientOriginalExtension();

  /*
  talk the select file and move it public directory and make avatars
  folder if doesn't exsit then give it that unique name.
  */
  $request->user_photo->move(public_path('avatars'), $photoName);

  }
}

That’s it. Now you can save the $photoName to the database as a user_photo field value. You can use asset(‘avatars’) function in your view and access the photos.

How to choose an AWS profile when using boto3 to connect to CloudFront

I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.

So there are three different ways to do this:

Option A) Create a new session with the profile

    dev = boto3.session.Session(profile_name='dev')

Option B) Change the profile of the default session in code

    boto3.setup_default_session(profile_name='dev')

Option C) Change the profile of the default session with an environment variable

    $ AWS_PROFILE=dev ipython
    >>> import boto3
    >>> s3dev = boto3.resource('s3')

CSS: stretching background image to 100% width and height of screen?

html, body {
    min-height: 100%;
}

Will do the trick.

By default, even html and body are only as big as the content they hold, but never more than the width/height of the windows. This can often lead to quite strange results.

You might also want to read http://css-tricks.com/perfect-full-page-background-image/

There are some great ways do achieve a very good and scalable full background image.

printf formatting (%d versus %u)

The difference is simple: they cause different warning messages to be emitted when compiling:

1156942.c:7:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %d\n", &a); // prints "memory add=-12"
                               ^
1156942.c:8:31: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %u\n", &a); // prints "memory add=65456"
                               ^

If you pass your pointer as a void* and use %p as the conversion specifier, then you get no error message:

#include <stdio.h>

int main()
{
    int a = 5;
    // check the memory address
    printf("memory address = %d\n", &a); /* wrong */
    printf("memory address = %u\n", &a); /* wrong */
    printf("memory address = %p\n", (void*)&a); /* right */
}

Bootstrap datepicker disabling past dates without current date

If your requirement is to disable the startDate and endDate dynamically based on one on another you can you this.

$('#date2').datepicker({
            todayHighlight: true,
            autoclose: true,
            format: "dd/mm/yyyy",
            clearBtn : true
        }).on('show', function(e){
            var date = $('#date3').datepicker('getDate');
            if(date){
             $('#date2').datepicker('setEndDate', date);
                }
    });

        $('#date3').datepicker({
            todayHighlight: true,
            autoclose: true,
            format: "dd/mm/yyyy",
            clearBtn : true
        }).on('show', function(e){
            var date = $('#date2').datepicker('getDate');
            if(date){
             $('#date3').datepicker('setStartDate', date);
                }
    });

If your requirement is just disabled past dates then you can use below snippet.

$('#date2').datepicker({
            todayHighlight: true,
            autoclose: true,
            format: "dd/mm/yyyy",
            clearBtn : true,
            startDate : new Date()
        })

If your requirement is just disabled future dates then you can use below snippet.

 $('#date2').datepicker({
                todayHighlight: true,
                autoclose: true,
                format: "dd/mm/yyyy",
                clearBtn : true,
                endDate : new Date()
            })

I hope it will help someone.

What is the difference between Integrated Security = True and Integrated Security = SSPI?

Note that connection strings are specific to what and how you are connecting to data. These are connecting to the same database but the first is using .NET Framework Data Provider for SQL Server. Integrated Security=True will not work for OleDb.

  • Data Source=.;Initial Catalog=aspnetdb;Integrated Security=True
  • Provider=SQLOLEDB;Data Source=.;Integrated Security=SSPI;Initial Catalog=aspnetdb

When in doubt use the Visual Studio Server Explorer Data Connections.

Loading scripts after page load?

Here is a code I am using and which is working for me.

window.onload = function(){
    setTimeout(function(){
        var scriptElement=document.createElement('script');
        scriptElement.type = 'text/javascript';
        scriptElement.src = "vendor/js/jquery.min.js";
        document.head.appendChild(scriptElement);

        setTimeout(function() {
            var scriptElement1=document.createElement('script');
            scriptElement1.type = 'text/javascript';
            scriptElement1.src = "gallery/js/lc_lightbox.lite.min.js";
            document.head.appendChild(scriptElement1);
        }, 100);
        setTimeout(function() {
            $(document).ready(function(e){
                lc_lightbox('.elem', {
                    wrap_class: 'lcl_fade_oc',
                    gallery : true, 
                    thumb_attr: 'data-lcl-thumb', 
                    slideshow_time  : 3000,
                    skin: 'minimal',
                    radius: 0,
                    padding : 0,
                    border_w: 0,
                }); 
            });
        }, 200);

    }, 150);
};

Does VBA have Dictionary Structure?

VBA has the collection object:

    Dim c As Collection
    Set c = New Collection
    c.Add "Data1", "Key1"
    c.Add "Data2", "Key2"
    c.Add "Data3", "Key3"
    'Insert data via key into cell A1
    Range("A1").Value = c.Item("Key2")

The Collection object performs key-based lookups using a hash so it's quick.


You can use a Contains() function to check whether a particular collection contains a key:

Public Function Contains(col As Collection, key As Variant) As Boolean
    On Error Resume Next
    col(key) ' Just try it. If it fails, Err.Number will be nonzero.
    Contains = (Err.Number = 0)
    Err.Clear
End Function

Edit 24 June 2015: Shorter Contains() thanks to @TWiStErRob.

Edit 25 September 2015: Added Err.Clear() thanks to @scipilot.

bool to int conversion

You tagged your question [C] and [C++] at the same time. The results will be consistent between the languages, but the structure of the the answer is different for each of these languages.

In C language your examples has no relation to bool whatsoever (that applies to C99 as well). In C language relational operators do not produce bool results. Both 4 > 5 and 4 < 5 are expressions that produce results of type int with values 0 or 1. So, there's no "bool to int conversion" of any kind taking place in your examples in C.

In C++ relational operators do indeed produce bool results. bool values are convertible to int type, with true converting to 1 and false converting to 0. This is guaranteed by the language.

P.S. C language also has a dedicated boolean type _Bool (macro-aliased as bool), and its integral conversion rules are essentially the same as in C++. But nevertheless this is not relevant to your specific examples in C. Once again, relational operators in C always produce int (not bool) results regardless of the version of the language specification.

Should I put #! (shebang) in Python scripts, and what form should it take?

You should add a shebang if the script is intended to be executable. You should also install the script with an installing software that modifies the shebang to something correct so it will work on the target platform. Examples of this is distutils and Distribute.

MySQL pivot table query with dynamic columns

Here's stored procedure, which will generate the table based on data from one table and column and data from other table and column.

The function 'sum(if(col = value, 1,0)) as value ' is used. You can choose from different functions like MAX(if()) etc.

delimiter //

  create procedure myPivot(
    in tableA varchar(255),
    in columnA varchar(255),
    in tableB varchar(255),
    in columnB varchar(255)
)
begin
  set @sql = NULL;
    set @sql = CONCAT('select group_concat(distinct concat(
            \'SUM(IF(', 
        columnA, 
        ' = \'\'\',',
        columnA,
        ',\'\'\', 1, 0)) AS \'\'\',',
        columnA, 
            ',\'\'\'\') separator \', \') from ',
        tableA, ' into @sql');
    -- select @sql;

    PREPARE stmt FROM @sql;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;
    -- select @sql;

    SET @sql = CONCAT('SELECT p.', 
        columnB, 
        ', ', 
        @sql, 
        ' FROM ', tableB, ' p GROUP BY p.',
        columnB,'');

    -- select @sql;

    /* */
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    /* */
    DEALLOCATE PREPARE stmt;
end//

delimiter ;

Get Unix timestamp with C++

C++20 introduced a guarantee that time_since_epoch is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to units of seconds rather than hours:

#include <iostream>
#include <chrono>
 
int main()
{
    const auto p1 = std::chrono::system_clock::now();
 
    std::cout << "seconds since epoch: "
              << std::chrono::duration_cast<std::chrono::seconds>(
                   p1.time_since_epoch()).count() << '\n';
}

Using C++17 or earlier, time() is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.

The cppreference page linked above gives this example:

#include <ctime>
#include <iostream>
 
int main()
{
    std::time_t result = std::time(nullptr);
    std::cout << std::asctime(std::localtime(&result))
              << result << " seconds since the Epoch\n";
}

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

Window->Preferences->Java->Installed JREs. Then choose your current JRE(JDK) and click Edit. Fill Default VM Arguments: -Djava.library.path=/usr/local/xuggler/lib. Done!

Can an int be null in Java?

Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so

public int getHeight(String name){
    if(map.containsKey(name)){
        return map.get(name);
    }else{
        return -1;
    }
}

How to create an on/off switch with Javascript/CSS?

Initial answer from 2013

If you don't mind something related to Bootstrap, an excellent (unofficial) Bootstrap Switch is available.

Classic 2013 Switch

It uses radio types or checkboxes as switches. A type attribute has been added since V.1.8.

Source code is available on Github.

Note from 2018

I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.

Please consider having a look at modern Switches like those.

Modern 2018 Switch

get the latest fragment in backstack

The answer given by deepak goel does not work for me because I always get null from entry.getName();

What I do is to set a Tag to the fragment this way:

ft.add(R.id.fragment_container, fragmentIn, FRAGMENT_TAG);

Where ft is my fragment transaction and FRAGMENT_TAG is the tag. Then I use this code to get the fragment:

Fragment prev_fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);

How do I return to an older version of our code in Subversion?

The standard way of using merge to undo the entire check-in works great, if that's what you want to do. Sometimes, though, all you want to do is revert a single file. There's no legitimate way to do that, but there is a hack:

  1. Find the version that you want using svn log.
  2. Use svn's export subcommand:

    svn export http://url-to-your-file@123 /tmp/filename

(Where 123 is the revision number for a good version of the file.) Then either move or copy that single file to overwrite the old one. Check in the modified file and you are done.

How to sum array of numbers in Ruby?

If you feel golfy, you can do

eval([123,321,12389]*?+)

This will create a string "123+321+12389" and then use function eval to do the sum. This is only for golfing purpose, you should not use it in proper code.

How to link 2 cell of excel sheet?

The simplest solution is to select the second cell, and press =. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.

To read up more on different options for referencing see - This Article.

How do I create a basic UIButton programmatically?

In Swift 5 and Xcode 10.2

Basically we have two types of buttons.

1) System type button

2) Custom type button (In custom type button we can set background image for button)

And these two types of buttons has few control states https://developer.apple.com/documentation/uikit/uicontrol/state

Important states are

1) Normal state

2) Selected state

3) Highlighted state

4) Disabled state etc...

//For system type button
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
//  button.backgroundColor = .blue
button.setTitle("Button", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
button.titleLabel?.textAlignment = .center//Text alighment center
button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
button.tag = 1//To assign tag value
button.btnProperties()//Call UIButton properties from extension function
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

//For custom type button (add image to your button)
let button2 = UIButton(type: .custom)
button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
//        button2.backgroundColor = .blue
button2.setImage(UIImage.init(named: "img.png"), for: .normal)
button2.tag = 2
button2.btnProperties()//Call UIButton properties from extension function
button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button2)

@objc func buttonClicked(sender:UIButton) {
    print("Button \(sender.tag) clicked")
}

//You can add UIButton properties using extension
extension UIButton {
    func btnProperties() {
        layer.cornerRadius = 10//Set button corner radious
        clipsToBounds = true
        backgroundColor = .blue//Set background colour
        //titleLabel?.textAlignment = .center//add properties like this
    }
}

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:

SELECT * FROM match WHERE id NOT IN 
    ( SELECT id FROM email WHERE id IS NOT NULL) ;

SELECT
    m.*
FROM
    match m
    LEFT OUTER JOIN email e ON
        m.id = e.id
        AND e.id IS NOT NULL
WHERE
    e.id IS NULL

The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.

Facebook Graph API : get larger pictures in one request

I researched Graph API Explorer extensively and finally found full_picture

https://graph.facebook.com/v2.2/$id/posts?fields=picture,full_picture

P.S. I noticed that full_picture won't always provide full size image I want. 'attachments' does

https://graph.facebook.com/v2.2/$id/posts?fields=picture,full_picture,attachments

Can you force Vue.js to reload/re-render?

<router-view :key="$route.params.slug" />

just use key with your any params its auto reload children..

Debugging with Android Studio stuck at "Waiting For Debugger" forever

Well, I guess there is a plethora of circumstances that can trigger this issue. I'm using IntelliJ Idea instead, but it's mostly the same than Android Studio. My solution for this problem:

Fastest way:

Right click on the class file that contains the main activity of your project, and then on "Debug 'WhateverActivity'". This will create a new run configuration that should debug fine.

Other solution, without creating a new run configuration:

  1. Open Run/Debug configurations and within "Android app" pick the configuration you're using to debug your app.
  2. Locate "Launch Options/Launch" there and set it to "Specified Activity" instead of "Default Activity".
  3. In the "Launch" field just below the aforementioned option, click on the three ellipsis (three dots) button and select your main activity.

At least it worked for me. I hope it works for others too.

Adding new files to a subversion repository

Normally svn add * works. But if you get message like svn: warning: W150002: due to mix off versioned and non-versioned files in working copy. Use this command:

svn add <path to directory> --force

or

svn add * --force

How do I POST a x-www-form-urlencoded request using Fetch?

No need to use jQuery, querystring or manually assemble the payload. URLSearchParams is a way to go and here is one of the most concise answers with the full request example:

fetch('https://example.com/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams({
    'param': 'Some value',
    'another_param': 'Another value'
  })
})
  .then(res => {
    // Do stuff with the result
  });

Yes, you can use Axios or whatever you want instead of fetch.

P.S. URLSearchParams is not supported in IE.

Python: Get HTTP headers from urllib2.urlopen call?

What about sending a HEAD request instead of a normal GET request. The following snipped (copied from a similar question) does exactly that.

>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]

How to set the text color of TextView in code?

You can use

holder.text.setTextColor(Color.rgb(200,0,0));

You can also specify what color you want with Transparency.

holder.text.setTextColor(Color.argb(0,200,0,0));

a for Alpha (Transparent) value r-red g-green b-blue

An invalid form control with name='' is not focusable

Not only required field as mentioned in other answers. Its also caused by placing a <input> field in a hidden <div> which holds a invalid value.

Consider below example,

<div style="display:none;">
   <input type="number" name="some" min="1" max="50" value="0">
</div> 

This throws the same error. So make sure the <input> fields inside hidden <div> doesnt hold any invalid value.

How to automatically add user account AND password with a Bash script?

The following works for me and tested on Ubuntu 14.04. It is a one liner that does not require any user input.

sudo useradd -p $(openssl passwd -1 $PASS) $USERNAME

Taken from @Tralemonkey

Uri not Absolute exception getting while calling Restful Webservice

An absolute URI specifies a scheme; a URI that is not absolute is said to be relative.

http://docs.oracle.com/javase/8/docs/api/java/net/URI.html

So, perhaps your URLEncoder isn't working as you're expecting (the https bit)?

    URLEncoder.encode(uri) 

How do I apply CSS3 transition to all properties except background-position?

For anyone looks for a shorthand way, to add transition for all properties except for one specific property with delay, be aware of there're differences among even modern browsers.

A simple demo below shows the difference. Check out full code

div:hover {
  width: 500px;
  height: 500px;
  border-radius: 0;
  transition: all 2s, border-radius 2s 4s;
}

Chrome will "combine" the two animation (which is like I expect), like below:

enter image description here

While Safari "separates" it (which may not be expected):

enter image description here

A more compatible way is that you assign the specific transition for specific property, if you have a delay for one of them.

Connecting to SQL Server Express - What is my server name?

All of the following services should be running,for successful connectivity: SQL Full test filter Daemon, SQL server(SQLEXPRESS), SQL Server Agent(SQLEXPRESS), SQL Server Browser, SQL server reporting service and SQL Server VSS Writer

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

const express = require('express')
const cors = require('cors')
const app = express()

app.get('/with-cors', cors(), (req, res, next) => {
  res.json({ msg: 'WHOAH with CORS it works!  ' })
})

Adding cors in get function Is what worked for me

Python - Check If Word Is In A String

What about to split the string and strip words punctuation?

w in [ws.strip(',.?!') for ws in p.split()]

Or working the case:

w.lower() in [ws.strip(',.?!') for ws in p.lower().split()]

Maybe that way:

def wsearch(word, phrase):
    # Attention about punctuation and about split characters
    punctuation = ',.?!'
    return word.lower() in [words.strip(punctuation) for words in phrase.lower().split()]

Sample:

print(wsearch('CAr', 'I own a caR.'))

I didn't check performance...

How to use componentWillMount() in React Hooks?

https://reactjs.org/docs/hooks-reference.html#usememo

Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.

Java: random long number in 0 <= x < n range

If you want a uniformly distributed pseudorandom long in the range of [0,m), try using the modulo operator and the absolute value method combined with the nextLong() method as seen below:

Math.abs(rand.nextLong()) % m;

Where rand is your Random object.

The modulo operator divides two numbers and outputs the remainder of those numbers. For example, 3 % 2 is 1 because the remainder of 3 and 2 is 1.

Since nextLong() generates a uniformly distributed pseudorandom long in the range of [-(2^48),2^48) (or somewhere in that range), you will need to take the absolute value of it. If you don't, the modulo of the nextLong() method has a 50% chance of returning a negative value, which is out of the range [0,m).

What you initially requested was a uniformly distributed pseudorandom long in the range of [0,100). The following code does so:

Math.abs(rand.nextLong()) % 100;

Access to Image from origin 'null' has been blocked by CORS policy

Under the covers there will be some form of URL loading request. You can't load images or any other content via this method from a local file system.

Your image needs to be loaded via a web server, so accessed via a proper http URL.

Downloading all maven dependencies to a directory NOT in repository?

I found the next command

mvn dependency:copy-dependencies -Dclassifier=sources

here maven.apache.org

How do I print a double value with full precision using cout?

With ostream::precision(int)

cout.precision( numeric_limits<double>::digits10 + 1);
cout << M_PI << ", " << M_E << endl;

will yield

3.141592653589793, 2.718281828459045

Why you have to say "+1" I have no clue, but the extra digit you get out of it is correct.

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

Joining a WORKGROUP then rejoining the domain fixed this issue for me.

I got this error while using Virtual Box VM's. The issue started to happen when I moved the VM files to a new drive location or computer.

Hope this helps the VM folks.

Sorting list based on values from another list

more_itertools has a tool for sorting iterables in parallel:

Given

from more_itertools import sort_together


X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]

Demo

sort_together([Y, X])[1]
# ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')

ssh: The authenticity of host 'hostname' can't be established

Make sure ~/.ssh/known_hosts is writable. That fixed it for me.

in_array multiple values

IMHO Mark Elliot's solution's best one for this problem. If you need to make more complex comparison operations between array elements AND you're on PHP 5.3, you might also think about something like the following:

<?php

// First Array To Compare
$a1 = array('foo','bar','c');

// Target Array
$b1 = array('foo','bar');


// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
        if (!in_array($x,$b1)) {
                $b=false;
        }
};


// Actual Test on array (can be repeated with others, but guard 
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);

This relies on a closure; comparison function can become much more powerful. Good luck!

batch file to list folders within a folder to one level

I tried this command to display the list of files in the directory.

dir /s /b > List.txt

In the file it displays the list below.

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll

What is want to do is only to display sub-directory not the full directory path.

Just like this:

Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll

Cisco Jabber\accessories\JabraJabberPlugin.dll

Cisco Jabber\accessories\Logitech

Cisco Jabber\accessories\Plantronics

Cisco Jabber\accessories\SennheiserJabberPlugin.dll

Getting a 'source: not found' error when using source in a bash script

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

How to play a notification sound on websites?

As of 2016, the following will suffice (you don't even need to embed):

let src = 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3';
let audio = new Audio(src);
audio.play();

See more here.

Very Simple Image Slider/Slideshow with left and right button. No autoplay

After reading your comment on my previous answer I thought I might put this as a separate answer.

Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.

That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with

WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/

This is the jQuery

$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();    
$('.active').show();

    $('#button-next').click(function(){

    $('.active').removeClass('active').addClass('oldActive');    
                   if ( $('.oldActive').is(':last-child')) {
        $('.sp').first().addClass('active');
        }
        else{
        $('.oldActive').next().addClass('active');
        }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();


    });

       $('#button-previous').click(function(){
    $('.active').removeClass('active').addClass('oldActive');    
           if ( $('.oldActive').is(':first-child')) {
        $('.sp').last().addClass('active');
        }
           else{
    $('.oldActive').prev().addClass('active');
           }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();
    });




});

So now the explanation.
Stage 1
1) Load the script on document ready.

2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.

3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;

Stage 2 Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.

2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.

3) We remove the class oldActive because it's no longer needed.

4) fadeOut all of the slides

5) fade In the active slides

Step 3

Same as in step two but using some reverse logic for traversing through the elements backwards.

It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.

Where can I find php.ini?

find / -name php.ini

Hey... it worked for me!

SQL use CASE statement in WHERE IN clause

No you can't use case and in like this. But you can do

SELECT * FROM Product P    
WHERE @Status='published' and P.Status IN (1,3)
or @Status='standby' and P.Status IN  (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)

BTW you can reduce that to

SELECT * FROM Product P    
WHERE @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)

since or P.Status IN (1,3) gives you also all records of @Status='published' and P.Status IN (1,3)

How do I specify the JDK for a GlassFish domain?

In my case the problem was the JAVA_HOME variable was set an installed jre.

An alternative to setting the AS_JAVA variable is to set JAVA_HOME environment variable to the jdk (i.e. /usr/local/jdk1.7.0.51).

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Invalid argument supplied for foreach()

Please do not depend on casting as a solution, even though others are suggesting this as a valid option to prevent an error, it might cause another one.

Be aware: If you expect a specific form of array to be returned, this might fail you. More checks are required for that.

E.g. casting a boolean to an array (array)bool, will NOT result in an empty array, but an array with one element containing the boolean value as an int: [0=>0] or [0=>1].

I wrote a quick test to present this problem. (Here is a backup Test in case the first test url fails.)

Included are tests for: null, false, true, a class, an array and undefined.


Always test your input before using it in foreach. Suggestions:

  1. Quick type checking: $array = is_array($var) or is_object($var) ? $var : [] ;
  2. Type hinting arrays in methods before using a foreach and specifying return types
  3. Wrapping foreach within if
  4. Using try{}catch(){} blocks
  5. Designing proper code / testing before production releases
  6. To test an array against proper form you could use array_key_exists on a specific key, or test the depth of an array (when it is one !).
  7. Always extract your helper methods into the global namespace in a way to reduce duplicate code

IndentationError expected an indented block

If you are using a mac and sublime text 3, this is what you do.

Go to your /Packages/User/ and create a file called Python.sublime-settings.

Typically /Packages/User is inside your ~/Library/Application Support/Sublime Text 3/Packages/User/Python.sublime-settings if you are using mac os x.

Then you put this in the Python.sublime-settings.

{
    "tab_size": 4,
    "translate_tabs_to_spaces": false
}

Credit goes to Mark Byer's answer, sublime text 3 docs and python style guide.

This answer is mostly for readers who had the same issue and stumble upon this and are using sublime text 3 on Mac OS X.

Vue.js—Difference between v-model and v-bind

There are cases where you don't want to use v-model. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.

In these cases, it's not a good idea to use either watchers or computed properties.

Instead, take your v-model and split it as above answer indicates

<input
   :value="something"
   @input="something = $event.target.value"
>

In practice, if you are decoupling your logic this way, you'll probably be calling a method.

This is what it would look like in a real world scenario:

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
  <p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
  var app = new Vue({_x000D_
    el: "#app",_x000D_
    data: function(){_x000D_
      return {_x000D_
        extendedCost: 0,_x000D_
      }_x000D_
    },_x000D_
    methods: {_x000D_
      _onInputExtendedCost: function($event) {_x000D_
        this.extendedCost = parseInt($event.target.value);_x000D_
        // Go update other inputs here_x000D_
    }_x000D_
  }_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_