Programs & Examples On #Android pullparser

How do I make a column unique and index it in a Ruby on Rails migration?

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name.

Negation in Python

try instead:

if not os.path.exists(pathName):
    do this

Convert List<DerivedClass> to List<BaseClass>

To quote the great explanation of Eric

What happens? Do you want the list of giraffes to contain a tiger? Do you want a crash? or do you want the compiler to protect you from the crash by making the assignment illegal in the first place? We choose the latter.

But what if you want to choose for a runtime crash instead of a compile error? You would normally use Cast<> or ConvertAll<> but then you will have 2 problems: It will create a copy of the list. If you add or remove something in the new list, this won't be reflected in the original list. And secondly, there is a big performance and memory penalty since it creates a new list with the existing objects.

I had the same problem and therefore I created a wrapper class that can cast a generic list without creating an entirely new list.

In the original question you could then use:

class Test
{
    static void Main(string[] args)
    {
        A a = new C(); // OK
        IList<A> listOfA = new List<C>().CastList<C,A>(); // now ok!
    }
}

and here the wrapper class (+ an extention method CastList for easy use)

public class CastedList<TTo, TFrom> : IList<TTo>
{
    public IList<TFrom> BaseList;

    public CastedList(IList<TFrom> baseList)
    {
        BaseList = baseList;
    }

    // IEnumerable
    IEnumerator IEnumerable.GetEnumerator() { return BaseList.GetEnumerator(); }

    // IEnumerable<>
    public IEnumerator<TTo> GetEnumerator() { return new CastedEnumerator<TTo, TFrom>(BaseList.GetEnumerator()); }

    // ICollection
    public int Count { get { return BaseList.Count; } }
    public bool IsReadOnly { get { return BaseList.IsReadOnly; } }
    public void Add(TTo item) { BaseList.Add((TFrom)(object)item); }
    public void Clear() { BaseList.Clear(); }
    public bool Contains(TTo item) { return BaseList.Contains((TFrom)(object)item); }
    public void CopyTo(TTo[] array, int arrayIndex) { BaseList.CopyTo((TFrom[])(object)array, arrayIndex); }
    public bool Remove(TTo item) { return BaseList.Remove((TFrom)(object)item); }

    // IList
    public TTo this[int index]
    {
        get { return (TTo)(object)BaseList[index]; }
        set { BaseList[index] = (TFrom)(object)value; }
    }

    public int IndexOf(TTo item) { return BaseList.IndexOf((TFrom)(object)item); }
    public void Insert(int index, TTo item) { BaseList.Insert(index, (TFrom)(object)item); }
    public void RemoveAt(int index) { BaseList.RemoveAt(index); }
}

public class CastedEnumerator<TTo, TFrom> : IEnumerator<TTo>
{
    public IEnumerator<TFrom> BaseEnumerator;

    public CastedEnumerator(IEnumerator<TFrom> baseEnumerator)
    {
        BaseEnumerator = baseEnumerator;
    }

    // IDisposable
    public void Dispose() { BaseEnumerator.Dispose(); }

    // IEnumerator
    object IEnumerator.Current { get { return BaseEnumerator.Current; } }
    public bool MoveNext() { return BaseEnumerator.MoveNext(); }
    public void Reset() { BaseEnumerator.Reset(); }

    // IEnumerator<>
    public TTo Current { get { return (TTo)(object)BaseEnumerator.Current; } }
}

public static class ListExtensions
{
    public static IList<TTo> CastList<TFrom, TTo>(this IList<TFrom> list)
    {
        return new CastedList<TTo, TFrom>(list);
    }
}

Get first row of dataframe in Python Pandas based on criteria

This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:

>>> df[condition]

This will return a slice of your dataframe which you can index using iloc. Here are your examples:

  1. Get first row where A > 3 (returns row 2)

    >>> df[df.A > 3].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

If what you actually want is the row number, rather than using iloc, it would be df[df.A > 3].index[0].

  1. Get first row where A > 4 AND B > 3:

    >>> df[(df.A > 4) & (df.B > 3)].iloc[0]
    A    5
    B    4
    C    5
    Name: 4, dtype: int64
    
  2. Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)

    >>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:

>>> def series_or_default(X, condition, default_col, ascending=False):
...     sliced = X[condition]
...     if sliced.shape[0] == 0:
...         return X.sort_values(default_col, ascending=ascending).iloc[0]
...     return sliced.iloc[0]
>>> 
>>> series_or_default(df, df.A > 6, 'A')
A    5
B    4
C    5
Name: 4, dtype: int64

As expected, it returns row 4.

ASP.NET Identity reset password

Best way to Reset Password in Asp.Net Core Identity use for Web API.

Note* : Error() and Result() are created for internal use. You can return you want.

        [HttpPost]
        [Route("reset-password")]
        public async Task<IActionResult> ResetPassword(ResetPasswordModel model)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            try
            {
                if (model is null)
                    return Error("No data found!");


                var user = await _userManager.FindByIdAsync(AppCommon.ToString(GetUserId()));
                if (user == null)
                    return Error("No user found!");

                Microsoft.AspNetCore.Identity.SignInResult checkOldPassword =
                    await _signInManager.PasswordSignInAsync(user.UserName, model.OldPassword, false, false);

                if (!checkOldPassword.Succeeded)
                    return Error("Old password does not matched.");

                string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
                if (string.IsNullOrEmpty(resetToken))
                    return Error("Error while generating reset token.");

                var result = await _userManager.ResetPasswordAsync(user, resetToken, model.Password);

                if (result.Succeeded)
                    return Result();
                else
                    return Error();
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

Generating a random password in php

I know you are trying to generate your password in a specific way, but you might want to look at this method as well...

$bytes = openssl_random_pseudo_bytes(2);

$pwd = bin2hex($bytes);

It's taken from the php.net site and it creates a string which is twice the length of the number you put in the openssl_random_pseudo_bytes function. So the above would create a password 4 characters long.

In short...

$pwd = bin2hex(openssl_random_pseudo_bytes(4));

Would create a password 8 characters long.

Note however that the password only contains numbers 0-9 and small cap letters a-f!

Calculate distance between two points in google maps V3

//JAVA
    public Double getDistanceBetweenTwoPoints(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {
    final int RADIUS_EARTH = 6371;

    double dLat = getRad(latitude2 - latitude1);
    double dLong = getRad(longitude2 - longitude1);

    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getRad(latitude1)) * Math.cos(getRad(latitude2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return (RADIUS_EARTH * c) * 1000;
    }

    private Double getRad(Double x) {
    return x * Math.PI / 180;
    }

Throw away local commits in Git

Find the sha1 for the commit you want to revert to:

za$ git reflog
... snip ...
cf42fa2... HEAD@{0}: commit: fixed misc bugs
~
~
cf42fa2... HEAD@{84}: commit: fixed params for .....
73b9363... HEAD@{85}: commit: Don't symlink to themes on deployment.
547cc1b... HEAD@{86}: commit: Deploy to effectif.com web server.
1dc3298... HEAD@{87}: commit: Updated the theme.
18c3f51... HEAD@{88}: commit: Verify with Google webmaster tools.
26fbb9c... HEAD@{89}: checkout: moving to effectif

And then use --mixed flag so that you "reset HEAD and index":

za$ git reset --mixed cf42fa2

Available flags:

za$ git reset -h

-q, --quiet           be quiet, only report errors
--mixed               reset HEAD and index
--soft                reset only HEAD
--hard                reset HEAD, index and working tree
--merge               reset HEAD, index and working tree
--keep                reset HEAD but keep local changes
--recurse-submodules[=<reset>]
                      control recursive updating of submodules
-p, --patch           select hunks interactively
-N, --intent-to-add

Getting windbg without the whole WDK?

For Windows 7 x86 you can also download the ISO: http://www.microsoft.com/en-us/download/confirmation.aspx?id=8442

And run \Setup\WinSDKDebuggingTools\dbg_x86.msi

WinDbg.exe will then be installed (default location) to: C:\Program Files (x86)\Debugging Tools for Windows (x86)

Difference between <span> and <div> with text-align:center;?

Like other have said, span is an in-line element.

See here: http://www.w3.org/TR/CSS2/visuren.html

Additionally, you can make a span behave like a div by applying a

style="display: block; margin: 0px auto; text-align: center;"

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I had the same error in Crashlytics from a strange device: Motorola One Vision Android 5.1 and 20 GB (free) RAM, rooted This device comes originally with Android 9.0, 4 GB RAM

Probably someone is trying to hack the app I'm currently developing and has problems dealing with multi-APKs. So drawables can't be found and the app delivers the crash

appending list but error 'NoneType' object has no attribute 'append'

I think what you want is this:

last_list=[]
if p.last_name != None and p.last_name != "":
    last_list.append(p.last_name)
print last_list

Your current if statement:

if p.last_name == None or p.last_name == "":
    pass

Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.

Also, it looks like your statement pan_list.append(p.last) is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.

How to grep and replace

I got the answer.

grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'

Adding custom radio buttons in android

Setting android:background and android:button of the RadioButton like the accepted answer didn't work for me. The drawable image was being displayed as a background(eventhough android:button was being set to transparent ) to the radio button text as enter image description here

android:background="@drawable/radiobuttonstyle"
    android:button="@android:color/transparent"

so gave radiobutton as the custom drawable radiobuttonstyle.xml

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Maintenance"
    android:id="@+id/radioButton1"
    android:button="@drawable/radiobuttonstyle"
      />

and radiobuttonstyle.xml is as follows

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_checked="true" android:drawable="@drawable/ic_radio_checked"></item>
  <item android:state_checked="false" android:drawable="@drawable/ic_radio_unchecked"></item>
</selector>

and after this radiobutton with custom button style worked.

enter image description here

How to get folder path for ClickOnce application

I'm using Assembly.GetExecutingAssembly().Location to get the path to a ClickOnce deployed application in .Net 4.5.1.

However, you shouldn't write to any folder where your application is deployed to ever, regardless of deployment method (xcopy, ClickOnce, InstallShield, anything) because those are usually read only for applications, especially in newer Windows versions and server environments.

An app must always write to the folders reserved for such purposes. You can get the folders you need starting from Environment.SpecialFolder Enumeration. The MSDN page explains what each folder is for: http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx

I.e. for data, logs and other files one can use ApplicationData (roaming), LocalApplicationData (local) or CommonApplicationData. For temporary files use Path.GetTempPath or Path.GetTempFileName.

The above work on servers and desktops too.

EDIT: Assembly.GetExecutingAssembly() is called in main executable.

Adding and reading from a Config file

  1. Add an Application Configuration File item to your project (Right -Click Project > Add item). This will create a file called app.config in your project.

  2. Edit the file by adding entries like <add key="keyname" value="someValue" /> within the <appSettings> tag.

  3. Add a reference to the System.Configuration dll, and reference the items in the config using code like ConfigurationManager.AppSettings["keyname"].

What killed my process and why?

The user has the ability to kill his own programs, using kill or Control+C, but I get the impression that's not what happened, and that the user complained to you.

root has the ability to kill programs of course, but if someone has root on your machine and is killing stuff you have bigger problems.

If you are not the sysadmin, the sysadmin may have set up quotas on CPU, RAM, ort disk usage and auto-kills processes that exceed them.

Other than those guesses, I'm not sure without more info about the program.

How to send a "multipart/form-data" with requests in python?

To clarify examples given above,

"You need to use the files parameter to send a multipart form POST request even when you do not need to upload any files."

files={}

won't work, unfortunately.

You will need to put some dummy values in, e.g.

files={"foo": "bar"}

I came up against this when trying to upload files to Bitbucket's REST API and had to write this abomination to avoid the dreaded "Unsupported Media Type" error:

url = "https://my-bitbucket.com/rest/api/latest/projects/FOO/repos/bar/browse/foobar.txt"
payload = {'branch': 'master', 
           'content': 'text that will appear in my file',
           'message': 'uploading directly from python'}
files = {"foo": "bar"}
response = requests.put(url, data=payload, files=files)

:O=

"Could not find Developer Disk Image"

Xcode 7.0.1 and iOS 9.1 are incompatible. You will need to update your version of Xcode via the Mac app store.

If your iOS version is lower then the Xcode version on the other hand, you can change the deployment target for a lower version of iOS by going to the General Settings and under Deployment set your Deployment Target:

enter image description here

Note:

Xcode 7.1 does not include iOS 9.2 beta SDK. Upgraded to Xcode to 7.2 beta by downloading it from the Xcode website.

How can I count the number of matches for a regex?

From Java 9, you can use the stream provided by Matcher.results()

long matches = matcher.results().count();

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

Refresh DataGridView when updating data source

This is copy my answer from THIS place.

Only need to fill datagrid again like this:

this.XXXTableAdapter.Fill(this.DataSet.XXX);

If you use automaticlly connect from dataGridView this code create automaticlly in Form_Load()

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

Populating a ListView using an ArrayList?

tutorial

Also look up ArrayAdapter interface:

ArrayAdapter(Context context, int textViewResourceId, List<T> objects)

npm install from Git in a specific version

The accepted answer did not work for me. Here's what I'm doing to pull a package from github:

npm install --save "git://github.com/username/package.git#commit"

Or adding it manually on package.json:

"dependencies": {
  "package": "git://github.com/username/package.git#commit"
}

Write to .txt file?

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

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

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

How to SUM parts of a column which have same text value in different column in the same row

This can be done by using SUMPRODUCT as well. Update the ranges as you see fit

=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)

A2:A7 = First name range

B2:B7 = Last Name Range

C2:C7 = Numbers Range

This will find all the names with the same first and last name and sum the numbers in your numbers column

How to use Visual Studio Code as Default Editor for Git

Another useful option is to set EDITOR environment variable. This environment variable is used by many utilities to know what editor to use. Git also uses it if no core.editor is set.

You can set it for current session using:

export EDITOR="code --wait"

This way not only git, but many other applications will use VS Code as an editor.

To make this change permanent, add this to your ~/.profile for example. See this question for more options.


Another advantage of this approach is that you can set different editors for different cases:

  1. When you working from local terminal.
  2. When you are connected through SSH session.

This is useful especially with VS Code (or any other GUI editor) because it just doesn't work without GUI.

On Linux OS, put this into your ~/.profile:

# Preferred editor for local and remote sessions
if [[ -n $SSH_CONNECTION ]]; then # SSH mode
  export EDITOR='vim'
else # Local terminal mode
  export EDITOR='code -w'
fi

This way when you use a local terminal, the $SSH_CONNECTION environment variable will be empty, so the code -w editor will be used, but when you are connected through SSH, then $SSH_CONNECTION environment variable will be a non-empty string, so the vim editor will be used. It is console editor, so it will work even when you are connected through SSH.

How do I drop a foreign key in SQL Server?

You can also Right Click on the table, choose modify, then go to the attribute, right click on it, and choose drop primary key.

Can I do a max(count(*)) in SQL?

Thanks to the last answer

SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr HAVING COUNT(title) >= ALL
  (SELECT COUNT(title)
   FROM actor
   JOIN casting ON actor.id = casting.actorid
   JOIN movie ON casting.movieid = movie.id
   WHERE name = 'John Travolta'
   GROUP BY yr)

I had the same problem: I needed to know just the records which their count match the maximus count (it could be one or several records).

I have to learn more about "ALL clause", and this is exactly the kind of simple solution that I was looking for.

Searching if value exists in a list of objects using Linq

LINQ defines an extension method that is perfect for solving this exact problem:

using System.Linq;
...
    bool has = list.Any(cus => cus.FirstName == "John");

make sure you reference System.Core.dll, that's where LINQ lives.

How to change an application icon programmatically in Android?

Try this solution

<activity android:name=".SplashActivity"
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity-alias android:label="ShortCut"
        android:icon="@drawable/ic_short_cut"
        android:name=".SplashActivityAlias"
        android:enabled="false"
        android:targetActivity=".SplashActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity-alias>

Add the following code when you want to change your app icon

PackageManager pm = getPackageManager();
                    pm.setComponentEnabledSetting(
                            new ComponentName(YourActivity.this,
                                    "your_package_name.SplashActivity"),
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                            PackageManager.DONT_KILL_APP);

                    pm.setComponentEnabledSetting(
                            new ComponentName(YourActivity.this,
                                    "your_package_name.SplashActivityAlias"),
                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                            PackageManager.DONT_KILL_APP);

Store output of subprocess.Popen call in a string

In Python 2.7 or Python 3

Instead of making a Popen object directly, you can use the subprocess.check_output() function to store output of a command in a string:

from subprocess import check_output
out = check_output(["ntpq", "-p"])

In Python 2.4-2.6

Use the communicate method.

import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()

out is what you want.

Important note about the other answers

Note how I passed in the command. The "ntpq -p" example brings up another matter. Since Popen does not invoke the shell, you would use a list of the command and options—["ntpq", "-p"].

Java regex email

One another simple alternative to validate 99% of emails

public static final String EMAIL_VERIFICATION = "^([\\w-\\.]+){1,64}@([\\w&&[^_]]+){2,255}.[a-z]{2,}$";

How to get a string after a specific substring?

In Python 3.9, a new removeprefix method is being added:

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

Using client certificate in Curl command

This is how I did it:

curl -v \
  --key ./admin-key.pem \
  --cert ./admin.pem \
  https://xxxx/api/v1/

How to return a value from try, catch, and finally?

It is because you are in a try statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally block, that way it will for sure be returned.

Make sure that you initialize sum outside the try/catch/finally so that it is in scope.

How to properly add cross-site request forgery (CSRF) token using PHP

For security code, please don't generate your tokens this way: $token = md5(uniqid(rand(), TRUE));

Try this out:

Generating a CSRF Token

PHP 7

session_start();
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['token'];

Sidenote: One of my employer's open source projects is an initiative to backport random_bytes() and random_int() into PHP 5 projects. It's MIT licensed and available on Github and Composer as paragonie/random_compat.

PHP 5.3+ (or with ext-mcrypt)

session_start();
if (empty($_SESSION['token'])) {
    if (function_exists('mcrypt_create_iv')) {
        $_SESSION['token'] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
    } else {
        $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32));
    }
}
$token = $_SESSION['token'];

Verifying the CSRF Token

Don't just use == or even ===, use hash_equals() (PHP 5.6+ only, but available to earlier versions with the hash-compat library).

if (!empty($_POST['token'])) {
    if (hash_equals($_SESSION['token'], $_POST['token'])) {
         // Proceed to process the form data
    } else {
         // Log this as a warning and keep an eye on these attempts
    }
}

Going Further with Per-Form Tokens

You can further restrict tokens to only be available for a particular form by using hash_hmac(). HMAC is a particular keyed hash function that is safe to use, even with weaker hash functions (e.g. MD5). However, I recommend using the SHA-2 family of hash functions instead.

First, generate a second token for use as an HMAC key, then use logic like this to render it:

<input type="hidden" name="token" value="<?php
    echo hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
?>" />

And then using a congruent operation when verifying the token:

$calc = hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
if (hash_equals($calc, $_POST['token'])) {
    // Continue...
}

The tokens generated for one form cannot be reused in another context without knowing $_SESSION['second_token']. It is important that you use a separate token as an HMAC key than the one you just drop on the page.

Bonus: Hybrid Approach + Twig Integration

Anyone who uses the Twig templating engine can benefit from a simplified dual strategy by adding this filter to their Twig environment:

$twigEnv->addFunction(
    new \Twig_SimpleFunction(
        'form_token',
        function($lock_to = null) {
            if (empty($_SESSION['token'])) {
                $_SESSION['token'] = bin2hex(random_bytes(32));
            }
            if (empty($_SESSION['token2'])) {
                $_SESSION['token2'] = random_bytes(32);
            }
            if (empty($lock_to)) {
                return $_SESSION['token'];
            }
            return hash_hmac('sha256', $lock_to, $_SESSION['token2']);
        }
    )
);

With this Twig function, you can use both the general purpose tokens like so:

<input type="hidden" name="token" value="{{ form_token() }}" />

Or the locked down variant:

<input type="hidden" name="token" value="{{ form_token('/my_form.php') }}" />

Twig is only concerned with template rendering; you still must validate the tokens properly. In my opinion, the Twig strategy offers greater flexibility and simplicity, while maintaining the possibility for maximum security.


Single-Use CSRF Tokens

If you have a security requirement that each CSRF token is allowed to be usable exactly once, the simplest strategy regenerate it after each successful validation. However, doing so will invalidate every previous token which doesn't mix well with people who browse multiple tabs at once.

Paragon Initiative Enterprises maintains an Anti-CSRF library for these corner cases. It works with one-use per-form tokens, exclusively. When enough tokens are stored in the session data (default configuration: 65535), it will cycle out the oldest unredeemed tokens first.

TortoiseSVN icons overlay not showing after updating to Windows 10

If you are using other version control software, it may be in conflict. In my case, uninstalling Plastic SCM restored Tortoise SVN icons.

jQuery: keyPress Backspace won't fire?

I came across this myself. I used .on so it looks a bit different but I did this:

 $('#element').on('keypress', function() {
   //code to be executed
 }).on('keydown', function(e) {
   if (e.keyCode==8)
     $('element').trigger('keypress');
 });

Adding my Work Around here. I needed to delete ssn typed by user so i did this in jQuery

  $(this).bind("keydown", function (event) {
        // Allow: backspace, delete
        if (event.keyCode == 46 || event.keyCode == 8) 
        {
            var tempField = $(this).attr('name');
            var hiddenID = tempField.substr(tempField.indexOf('_') + 1);
            $('#' + hiddenID).val('');
            $(this).val('')
            return;
        }  // Allow: tab, escape, and enter
        else if (event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
        // Allow: Ctrl+A
        (event.keyCode == 65 && event.ctrlKey === true) ||
        // Allow: home, end, left, right
        (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        else 
        {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) &&       (event.keyCode < 96 || event.keyCode > 105)) 
            {
                event.preventDefault();
            }
        }
    });

C++ - Decimal to binary converting

here a simple converter by using std::string as container. it allows a negative value.

#include <iostream>
#include <string>
#include <limits>

int main()
{
    int x = -14;

    int n = std::numeric_limits<int>::digits - 1;

    std::string s;
    s.reserve(n + 1);

    do
        s.push_back(((x >> n) & 1) + '0');
    while(--n > -1);

    std::cout << s << '\n';
}

Up, Down, Left and Right arrow keys do not trigger KeyDown event

    protected override bool IsInputKey(Keys keyData)
    {
        switch (keyData)
        {
            case Keys.Right:
            case Keys.Left:
            case Keys.Up:
            case Keys.Down:
                return true;
            case Keys.Shift | Keys.Right:
            case Keys.Shift | Keys.Left:
            case Keys.Shift | Keys.Up:
            case Keys.Shift | Keys.Down:
                return true;
        }
        return base.IsInputKey(keyData);
    }
    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        switch (e.KeyCode)
        {
            case Keys.Left:
            case Keys.Right:
            case Keys.Up:
            case Keys.Down:
                if (e.Shift)
                {

                }
                else
                {
                }
                break;                
        }
    }

scikit-learn random state in splitting dataset

It doesn't matter if the random_state is 0 or 1 or any other integer. What matters is that it should be set the same value, if you want to validate your processing over multiple runs of the code. By the way I have seen random_state=42 used in many official examples of scikit as well as elsewhere also.

random_state as the name suggests, is used for initializing the internal random number generator, which will decide the splitting of data into train and test indices in your case. In the documentation, it is stated that:

If random_state is None or np.random, then a randomly-initialized RandomState object is returned.

If random_state is an integer, then it is used to seed a new RandomState object.

If random_state is a RandomState object, then it is passed through.

This is to check and validate the data when running the code multiple times. Setting random_state a fixed value will guarantee that same sequence of random numbers are generated each time you run the code. And unless there is some other randomness present in the process, the results produced will be same as always. This helps in verifying the output.

Django Rest Framework File Upload

After spending 1 day on this, I figured out that ...

For someone who needs to upload a file and send some data, there is no straight fwd way you can get it to work. There is an open issue in json api specs for this. One possibility i have seen is to use multipart/related as shown here, but i think its very hard to implement it in drf.

Finally what i had implemented was to send the request as formdata. You would send each file as file and all other data as text. Now for sending the data as text you have two choices. case 1) you can send each data as key value pair or case 2) you can have a single key called data and send the whole json as string in value.

The first method would work out of the box if you have simple fields, but will be a issue if you have nested serializes. The multipart parser wont be able to parse the nested fields.

Below i am providing the implementation for both the cases

Models.py

class Posts(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
    caption = models.TextField(max_length=1000)
    media = models.ImageField(blank=True, default="", upload_to="posts/")
    tags = models.ManyToManyField('Tags', related_name='posts')

serializers.py -> no special changes needed, not showing my serializer here as its too lengthy because of the writable ManyToMany Field implimentation.

views.py

class PostsViewset(viewsets.ModelViewSet):
    serializer_class = PostsSerializer
    #parser_classes = (MultipartJsonParser, parsers.JSONParser) use this if you have simple key value pair as data with no nested serializers
    #parser_classes = (parsers.MultipartParser, parsers.JSONParser) use this if you want to parse json in the key value pair data sent
    queryset = Posts.objects.all()
    lookup_field = 'id'

Now, if you are following the first method and is only sending non-Json data as key value pairs, you don't need a custom parser class. DRF'd MultipartParser will do the job. But for the second case or if you have nested serializers (like i have shown) you will need custom parser as shown below.

utils.py

from django.http import QueryDict
import json
from rest_framework import parsers

class MultipartJsonParser(parsers.MultiPartParser):

    def parse(self, stream, media_type=None, parser_context=None):
        result = super().parse(
            stream,
            media_type=media_type,
            parser_context=parser_context
        )
        data = {}

        # for case1 with nested serializers
        # parse each field with json
        for key, value in result.data.items():
            if type(value) != str:
                data[key] = value
                continue
            if '{' in value or "[" in value:
                try:
                    data[key] = json.loads(value)
                except ValueError:
                    data[key] = value
            else:
                data[key] = value

        # for case 2
        # find the data field and parse it
        data = json.loads(result.data["data"])

        qdict = QueryDict('', mutable=True)
        qdict.update(data)
        return parsers.DataAndFiles(qdict, result.files)

This serializer would basically parse any json content in the values.

The request example in post man for both cases: case 1 case 1,

Case 2 case2

How to do the Recursive SELECT query in MySQL?

If you want to be able to have a SELECT without problems of the parent id having to be lower than child id, a function could be used. It supports also multiple children (as a tree should do) and the tree can have multiple heads. It also ensure to break if a loop exists in the data.

I wanted to use dynamic SQL to be able to pass the table/columns names, but functions in MySQL don't support this.

DELIMITER $$

CREATE FUNCTION `isSubElement`(pParentId INT, pId INT) RETURNS int(11)
DETERMINISTIC    
READS SQL DATA
BEGIN
DECLARE isChild,curId,curParent,lastParent int;
SET isChild = 0;
SET curId = pId;
SET curParent = -1;
SET lastParent = -2;

WHILE lastParent <> curParent AND curParent <> 0 AND curId <> -1 AND curParent <> pId AND isChild = 0 DO
    SET lastParent = curParent;
    SELECT ParentId from `test` where id=curId limit 1 into curParent;

    IF curParent = pParentId THEN
        SET isChild = 1;
    END IF;
    SET curId = curParent;
END WHILE;

RETURN isChild;
END$$

Here, the table test has to be modified to the real table name and the columns (ParentId,Id) may have to be adjusted for your real names.

Usage :

SET @wantedSubTreeId = 3;
SELECT * FROM test WHERE isSubElement(@wantedSubTreeId,id) = 1 OR ID = @wantedSubTreeId;

Result :

3   7   k
5   3   d
9   3   f
1   5   a

SQL for test creation :

CREATE TABLE IF NOT EXISTS `test` (
  `Id` int(11) NOT NULL,
  `ParentId` int(11) DEFAULT NULL,
  `Name` varchar(300) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

insert into test (id, parentid, name) values(3,7,'k');
insert into test (id, parentid, name) values(5,3,'d');
insert into test (id, parentid, name) values(9,3,'f');
insert into test (id, parentid, name) values(1,5,'a');
insert into test (id, parentid, name) values(6,2,'o');
insert into test (id, parentid, name) values(2,8,'c');

EDIT : Here is a fiddle to test it yourself. It forced me to change the delimiter using the predefined one, but it works.

resize2fs: Bad magic number in super-block while trying to open

resize2fs Command will not work for all file systems.

Please confirm the file system of your instance using below command. enter image description here

Please follow the procedure to expand volume by following the steps mentioned in Amazon official document for different file systems.

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recognize-expanded-volume-linux.html

Default file system in Centos is xfs, use the following command for xfs file system to increase partition size.

sudo xfs_growfs -d /

then "df -h" to check.

How to run Nginx within a Docker container without halting?

To add Tomer and Charles answers,

Syntax to run nginx in forground in Docker container using Entrypoint:

ENTRYPOINT nginx -g 'daemon off;' 

Not directly related but to run multiple commands with Entrypoint:

ENTRYPOINT /bin/bash -x /myscripts/myscript.sh && nginx -g 'daemon off;' 

clk'event vs rising_edge()

rising_edge is defined as:

FUNCTION rising_edge  (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
    RETURN (s'EVENT AND (To_X01(s) = '1') AND
                        (To_X01(s'LAST_VALUE) = '0'));
END;

FUNCTION To_X01  ( s : std_ulogic ) RETURN  X01 IS
BEGIN
    RETURN (cvt_to_x01(s));
END;

CONSTANT cvt_to_x01 : logic_x01_table := (
                     'X',  -- 'U'
                     'X',  -- 'X'
                     '0',  -- '0'
                     '1',  -- '1'
                     'X',  -- 'Z'
                     'X',  -- 'W'
                     '0',  -- 'L'
                     '1',  -- 'H'
                     'X'   -- '-'
                    );

If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.

Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk) to be more descriptive than the (clk'event and clk = '1') variant.

window.onunload is not working properly in Chrome browser. Can any one help me?

The onunload event won't fire if the onload event did not fire. Unfortunately the onload event waits for all binary content (e.g. images) to load, and inline scripts run before the onload event fires. DOMContentLoaded fires when the page is visible, before onload does. And it is now standard in HTML 5, and you can test for browser support but note this requires the <!DOCTYPE html> (at least in Chrome). However, I can not find a corresponding event for unloading the DOM. And such a hypothetical event might not work because some browsers may keep the DOM around to perform the "restore tab" feature.

The only potential solution I found so far is the Page Visibility API, which appears to require the <!DOCTYPE html>.

select data up to a space?

An alternative if you sometimes do not have spaces do not want to use the CASE statement

select REVERSE(RIGHT(REVERSE(YourColumn), LEN(YourColumn) - CHARINDEX(' ', REVERSE(YourColumn))))

This works in SQL Server, and according to my searching MySQL has the same functions

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

Update your schema_version record to mach the "Resolved locally" value which in your case is -1729781252

How much data can a List can hold at the maximum?

java.util.List is an interface. How much data a list can hold is dependant on the specific implementation of List you choose to use.

Generally, a List implementation can hold any number of items (If you use an indexed List, it may be limited to Integer.MAX_VALUE or Long.MAX_VALUE). As long as you don't run out of memory, the List doesn't become "full" or anything.

Is it possible to Turn page programmatically in UIPageViewController?

I also needed a button to navigate left on a PageViewController, one that should do exactly what you would expect from the swipe motion.

Since I had a few rules already in place inside "pageViewController:viewControllerBeforeViewController" for dealing with the natural swipe navigation, I wanted the button to re-use all that code, and simply could not afford to use specific indexes to reach pages as the previous answers did. So, I had to take an alternate solution.

Please note that the following code is for a Page View Controller that is a property inside my custom ViewController, and has its spine set to mid.

Here is the code I wrote for my Navigate Left button:

- (IBAction)btnNavigateLeft_Click:(id)sender {

    // Calling the PageViewController to obtain the current left page
    UIViewController *currentLeftPage = [_pageController.viewControllers objectAtIndex:0];

    // Creating future pages to be displayed
    NSArray *newDisplayedPages = nil;
    UIViewController *newRightPage = nil;
    UIViewController *newLeftPage = nil;

    // Calling the delegate to obtain previous pages
    // My "pageViewController:viewControllerBeforeViewController" method returns nil if there is no such page (first page of the book).
    newRightPage = [self pageViewController:_pageController viewControllerBeforeViewController:currentLeftPage];
    if (newRightPage) {
        newLeftPage = [self pageViewController:_pageController viewControllerBeforeViewController:newRightPage];
    }

    if (newLeftPage) {
        newDisplayedPages = [[NSArray alloc] initWithObjects:newLeftPage, newRightPage, nil];
    }

    // If there are two new pages to display, show them with animation.
    if (newDisplayedPages) {
        [_pageController setViewControllers:newDisplayedPages direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:nil];
    }
}

You can do something very similar to make a right navigation button from here.

HTML anchor tag with Javascript onclick event

If your onclick function returns false the default browser behaviour is cancelled. As such:

<a href='http://www.google.com' onclick='return check()'>check</a>

<script type='text/javascript'>

function check()
{
    return false;
}

</script>

Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.

Spring Boot - Cannot determine embedded database driver class for database type NONE

From the Spring manual.

Spring Boot can auto-configure embedded H2, HSQL, and Derby databases. You don’t need to provide any connection URLs, simply include a build dependency to the embedded database that you want to use.

For example, typical POM dependencies would be:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

For me leaving out the spring-boot-starter-data-jpa dependency and just using the spring-boot-starter-jdbc dependency worked like a charm, as long as I had h2 (or hsqldb) included as dependencies.

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

While I agree that the accepted answer is usually the best solution and definitely easier to use, I noticed no one displayed the proper usage of the iterator. So here is a quick example:

Iterator<Object> it = arrayList.iterator();
while(it.hasNext())
{
    Object obj = it.next();
    //Do something with obj
}

Java8: sum values from specific field of the objects in a list

You can also collect with an appropriate summing collector like Collectors#summingInt(ToIntFunction)

Returns a Collector that produces the sum of a integer-valued function applied to the input elements. If no elements are present, the result is 0.

For example

Stream<Obj> filtered = list.stream().filter(o -> o.field > 10);
int sum = filtered.collect(Collectors.summingInt(o -> o.field));

Convert data file to blob

A file object is an instance of Blob but a blob object is not an instance of File

new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true

new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false

new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false

If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
    let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
    console.log(blob);
};
reader.readAsArrayBuffer(file);

As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];

file.arrayBuffer().then((arrayBuffer) => {
    let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
    console.log(blob);
});

If your environment supports async/await you can use a one-liner like below

let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));

How to get object length

Have you taken a look at underscore.js (http://underscorejs.org/docs/underscore.html)? It's a utility library with a lot of useful methods. There is a collection size method, as well as a toArray method, which may get you what you need.

_.size({one : 1, two : 2, three : 3});
=> 3

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

The other answers here clearly explained what does it mean.I like to explain its use.

You can select an element in the elements tab and switch to console tab in chrome. Just type $0 or $1 or whatever number and press enter and the element will be displayed in the console for your use.

screenshot of chrome dev tools

Select All as default value for Multivalue parameter

This is rather easy to achieve by making a dataset with a text-query like this:

SELECT 'Item1'
UNION
SELECT 'Item2'
UNION
SELECT 'Item3'
UNION
SELECT 'Item4'
UNION
SELECT 'ItemN'

The query should return all items that can be selected.

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

You can use functions in pyspark.sql.functions: functions like year, month, etc

refer to here: https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame

from pyspark.sql.functions import *

newdf = elevDF.select(year(elevDF.date).alias('dt_year'), month(elevDF.date).alias('dt_month'), dayofmonth(elevDF.date).alias('dt_day'), dayofyear(elevDF.date).alias('dt_dayofy'), hour(elevDF.date).alias('dt_hour'), minute(elevDF.date).alias('dt_min'), weekofyear(elevDF.date).alias('dt_week_no'), unix_timestamp(elevDF.date).alias('dt_int'))

newdf.show()


+-------+--------+------+---------+-------+------+----------+----------+
|dt_year|dt_month|dt_day|dt_dayofy|dt_hour|dt_min|dt_week_no|    dt_int|
+-------+--------+------+---------+-------+------+----------+----------+
|   2015|       9|     6|      249|      0|     0|        36|1441497601|
|   2015|       9|     6|      249|      0|     0|        36|1441497601|
|   2015|       9|     6|      249|      0|     0|        36|1441497603|
|   2015|       9|     6|      249|      0|     1|        36|1441497694|
|   2015|       9|     6|      249|      0|    20|        36|1441498808|
|   2015|       9|     6|      249|      0|    20|        36|1441498811|
|   2015|       9|     6|      249|      0|    20|        36|1441498815|

Adding Permissions in AndroidManifest.xml in Android Studio?

Go to Android Manifest.xml and be sure to add the <uses-permission tag > inside the manifest tag but Outside of all other tags..

<manifest xlmns:android...>

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

This is an example of the permission of using Internet.

C# get and set properties for a List Collection

It would be inappropriate for it to be part of the setter - it's not like you're really setting the whole list of strings - you're just trying to add one.

There are a few options:

  • Put AddSubheading and AddContent methods in your class, and only expose read-only versions of the lists
  • Expose the mutable lists just with getters, and let callers add to them
  • Give up all hope of encapsulation, and just make them read/write properties

In the second case, your code can be just:

public class Section
{
    public String Head { get; set; }
    private readonly List<string> _subHead = new List<string>();
    private readonly List<string> _content = new List<string>();

    // Note: fix to case to conform with .NET naming conventions
    public IList<string> SubHead { get { return _subHead; } }
    public IList<string> Content { get { return _content; } }
}

This is reasonably pragmatic code, although it does mean that callers can mutate your collections any way they want, which might not be ideal. The first approach keeps the most control (only your code ever sees the mutable list) but may not be as convenient for callers.

Making the setter of a collection type actually just add a single element to an existing collection is neither feasible nor would it be pleasant, so I'd advise you to just give up on that idea.

global variable for all controller and views

I see, that this is still needed for 5.4+ and I just had the same problem, but none of the answers were clean enough, so I tried to accomplish the availability with ServiceProviders. Here is what i did:

  1. Created the Provider SettingsServiceProvider
    php artisan make:provider SettingsServiceProvider
  1. Created the Model i needed (GlobalSettings)
    php artisan make:model GlobalSettings
  1. Edited the generated register method in \App\Providers\SettingsServiceProvider. As you can see, I retrieve my settings using the eloquent model for it with Setting::all().
 

    public function register()
    {
        $this->app->singleton('App\GlobalSettings', function ($app) {
            return new GlobalSettings(Setting::all());
        });
    }

 
  1. Defined some useful parameters and methods (including the constructor with the needed Collection parameter) in GlobalSettings
 

    class GlobalSettings extends Model
    {
        protected $settings;
        protected $keyValuePair;

        public function __construct(Collection $settings)
        {
            $this->settings = $settings;
            foreach ($settings as $setting){
                $this->keyValuePair[$setting->key] = $setting->value;
            }
        }

        public function has(string $key){ /* check key exists */ }
        public function contains(string $key){ /* check value exists */ }
        public function get(string $key){ /* get by key */ }
    }

 
  1. At last I registered the provider in config/app.php
 

    'providers' => [
        // [...]

        App\Providers\SettingsServiceProvider::class
    ]

 
  1. After clearing the config cache with php artisan config:cache you can use your singleton as follows.
 

    $foo = app(App\GlobalSettings::class);
    echo $foo->has("company") ? $foo->get("company") : "Stack Exchange Inc.";

 

You can read more about service containers and service providers in Laravel Docs > Service Container and Laravel Docs > Service Providers.

This is my first answer and I had not much time to write it down, so the formatting ist a bit spacey, but I hope you get everything.


I forgot to include the boot method of SettingsServiceProvider, to make the settings variable global available in views, so here you go:

 

    public function boot(GlobalSettings $settinsInstance)
    {
        View::share('globalsettings', $settinsInstance);
    }

 

Before the boot methods are called all providers have been registered, so we can just use our GlobalSettings instance as parameter, so it can be injected by Laravel.

In blade template:

 

    {{ $globalsettings->get("company") }}

 

Setting up redirect in web.config file

  1. Open web.config in the directory where the old pages reside
  2. Then add code for the old location path and new destination as follows:

    <configuration>
      <location path="services.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/services" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
      <location path="products.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/products" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
    </configuration>
    

You may add as many location paths as necessary.

std::wstring VS std::string

When should you NOT use wide-characters?

When you're writing code before the year 1990.

Obviously, I'm being flip, but really, it's the 21st century now. 127 characters have long since ceased to be sufficient. Yes, you can use UTF8, but why bother with the headaches?

ERROR: Google Maps API error: MissingKeyMapError

All Google Maps JavaScript API applications require authentication( API KEY )

  1. Go to https://developers.google.com/maps/documentation/javascript/get-api-key.
  2. Login with Google Account
  3. Click on Get a key button 3 Select or create a project
  4. Click on Enable API ( Google Maps API)
  5. Copy YOUR API KEY in your Project: <script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=(Paste YOUR API KEY)"></script>

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

nchar(10) is a fixed-length Unicode string of length 10. nvarchar(10) is a variable-length Unicode string with a maximum length of 10. Typically, you would use the former if all data values are 10 characters and the latter if the lengths vary.

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

This one worked for me:

>> print(df)
                          TotalVolume  Symbol
2016-04-15 09:00:00       108400       2802.T
2016-04-15 09:05:00       50300        2802.T

>> print(df.set_index(pd.to_datetime(df.index.values) - datetime(2016, 4, 15)))

             TotalVolume  Symbol
09:00:00     108400       2802.T
09:05:00     50300        2802.T

CSS rotation cross browser with jquery.animate()

this is my solution:

var matrixRegex = /(?:matrix\(|\s*,\s*)([-+]?[0-9]*\.?[0-9]+(?:[e][-+]?[0-9]+)?)/gi;

var getMatches = function(string, regex) {
    regex || (regex = matrixRegex);
    var matches = [];
    var match;
    while (match = regex.exec(string)) {
        matches.push(match[1]);
    }
    return matches;
};

$.cssHooks['rotation'] = {
    get: function(elem) {
        var $elem = $(elem);
        var matrix = getMatches($elem.css('transform'));
        if (matrix.length != 6) {
            return 0;
        }
        return Math.atan2(parseFloat(matrix[1]), parseFloat(matrix[0])) * (180/Math.PI);
    }, 
    set: function(elem, val){
        var $elem = $(elem);
        var deg = parseFloat(val);
        if (!isNaN(deg)) {
            $elem.css({ transform: 'rotate(' + deg + 'deg)' });
        }
    }
};
$.cssNumber.rotation = true;
$.fx.step.rotation = function(fx) {
    $.cssHooks.rotation.set(fx.elem, fx.now + fx.unit);
};

then you can use it in the default animate fkt:

//rotate to 90 deg cw
$('selector').animate({ rotation: 90 });

//rotate to -90 deg ccw
$('selector').animate({ rotation: -90 });

//rotate 90 deg cw from current rotation
$('selector').animate({ rotation: '+=90' });

//rotate 90 deg ccw from current rotation
$('selector').animate({ rotation: '-=90' });

Reversing a linked list in Java, recursively

As Java is always pass-by-value, to recursively reverse a linked list in Java, make sure to return the "new head"(the head node after reversion) at the end of the recursion.

static ListNode reverseR(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }

    ListNode first = head;
    ListNode rest = head.next;

    // reverse the rest of the list recursively
    head = reverseR(rest);

    // fix the first node after recursion
    first.next.next = first;
    first.next = null;

    return head;
}

Create a new txt file using VB.NET

You can try writing into the Documents folder. Here is a "debug" function I did for the debugging needs of my project:

Private Sub writeDebug(ByVal x As String)
    Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    Dim FILE_NAME As String = path & "\mydebug.txt"
    MsgBox(FILE_NAME)
    If System.IO.File.Exists(FILE_NAME) = False Then
        System.IO.File.Create(FILE_NAME).Dispose()
    End If
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
    objWriter.WriteLine(x)
    objWriter.Close()
End Sub

There are more standard folders you can access through the "SpecialFolder" object.

What is the default boolean value in C#?

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

Remember that using uninitialized variables in C# is not allowed.

With

bool foo = new bool();

foo will have the default value.

Boolean default is false

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

How to build a DataTable from a DataGridView?

Well, you can do

DataTable data = (DataTable)(dgvMyMembers.DataSource);

and then use

data.Columns.Remove(...);

I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that DataGridView.DataSource is not necessarily of DataTable type.

Count the items from a IEnumerable<T> without iterating?

No, not in general. One point in using enumerables is that the actual set of objects in the enumeration is not known (in advance, or even at all).

Is the sizeof(some pointer) always equal to four?

No, the size of a pointer may vary depending on the architecture. There are numerous exceptions.

Rearrange columns using cut

You may also combine cut and paste:

paste <(cut -f2 file.txt) <(cut -f1 file.txt)

via comments: It's possible to avoid bashisms and remove one instance of cut by doing:

paste file.txt file.txt | cut -f2,3

Efficient way to determine number of digits in an integer

If faster is more efficient, this is a improvement on andrei alexandrescu's improvement. His version was already faster than the naive way (dividing by 10 at every digit). The version below is constant time and faster at least on x86-64 and ARM for all sizes, but occupies twice as much binary code, so it is not as cache-friendly.

Benchmarks for this version vs alexandrescu's version on my PR on facebook folly.

Works on unsigned, not signed.

inline uint32_t digits10(uint64_t v) {
  return  1
        + (std::uint32_t)(v>=10)
        + (std::uint32_t)(v>=100)
        + (std::uint32_t)(v>=1000)
        + (std::uint32_t)(v>=10000)
        + (std::uint32_t)(v>=100000)
        + (std::uint32_t)(v>=1000000)
        + (std::uint32_t)(v>=10000000)
        + (std::uint32_t)(v>=100000000)
        + (std::uint32_t)(v>=1000000000)
        + (std::uint32_t)(v>=10000000000ull)
        + (std::uint32_t)(v>=100000000000ull)
        + (std::uint32_t)(v>=1000000000000ull)
        + (std::uint32_t)(v>=10000000000000ull)
        + (std::uint32_t)(v>=100000000000000ull)
        + (std::uint32_t)(v>=1000000000000000ull)
        + (std::uint32_t)(v>=10000000000000000ull)
        + (std::uint32_t)(v>=100000000000000000ull)
        + (std::uint32_t)(v>=1000000000000000000ull)
        + (std::uint32_t)(v>=10000000000000000000ull);
}

Hive: how to show all partitions of a table?

CLI has some limit when ouput is displayed. I suggest to export output into local file:

$hive -e 'show partitions table;' > partitions

adb command for getting ip address assigned by operator

adb shell ip addr > ippdetails.txt This will get all list of ip's assigned to devices.

Matplotlib discrete colorbar

I have been investigating these ideas and here is my five cents worth. It avoids calling BoundaryNorm as well as specifying norm as an argument to scatter and colorbar. However I have found no way of eliminating the rather long-winded call to matplotlib.colors.LinearSegmentedColormap.from_list.

Some background is that matplotlib provides so-called qualitative colormaps, intended to use with discrete data. Set1, e.g., has 9 easily distinguishable colors, and tab20 could be used for 20 colors. With these maps it could be natural to use their first n colors to color scatter plots with n categories, as the following example does. The example also produces a colorbar with n discrete colors approprately labelled.

import matplotlib, numpy as np, matplotlib.pyplot as plt
n = 5
from_list = matplotlib.colors.LinearSegmentedColormap.from_list
cm = from_list(None, plt.cm.Set1(range(0,n)), n)
x = np.arange(99)
y = x % 11
z = x % n
plt.scatter(x, y, c=z, cmap=cm)
plt.clim(-0.5, n-0.5)
cb = plt.colorbar(ticks=range(0,n), label='Group')
cb.ax.tick_params(length=0)

which produces the image below. The n in the call to Set1 specifies the first n colors of that colormap, and the last n in the call to from_list specifies to construct a map with n colors (the default being 256). In order to set cm as the default colormap with plt.set_cmap, I found it to be necessary to give it a name and register it, viz:

cm = from_list('Set15', plt.cm.Set1(range(0,n)), n)
plt.cm.register_cmap(None, cm)
plt.set_cmap(cm)
...
plt.scatter(x, y, c=z)

scatterplot with disrete colors

Inverse dictionary lookup in Python

I know this might be considered 'wasteful', but in this scenario I often store the key as an additional column in the value record:

d = {'key1' : ('key1', val, val...), 'key2' : ('key2', val, val...) }

it's a tradeoff and feels wrong, but it's simple and works and of course depends on values being tuples rather than simple values.

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Below method solved my problem:

In ubuntu

Type: sudo vi /etc/mysql/my.cnf

type A to enter insert mode

In the last line paste below two line code:

[mysqld]
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Type esc to exit input mode

Type :wq to save and close vim.

Type sudo service mysql restart to restart MySQL.

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);

Android update activity UI from service

Callback from service to activity to update UI.
ResultReceiver receiver = new ResultReceiver(new Handler()) {
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        //process results or update UI
    }
}

Intent instructionServiceIntent = new Intent(context, InstructionService.class);
instructionServiceIntent.putExtra("receiver", receiver);
context.startService(instructionServiceIntent);

How to properly stop the Thread in Java?

You should always end threads by checking a flag in the run() loop (if any).

Your thread should look like this:

public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
    private volatile boolean execute;

    @Override
    public void run() {
        this.execute = true;
        while (this.execute) {
            try {
                LOGGER.debug("Sleeping...");
                Thread.sleep((long) 15000);

                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                this.execute = false;
            }
        }
    }

    public void stopExecuting() {
        this.execute = false;
    }
}

Then you can end the thread by calling thread.stopExecuting(). That way the thread is ended clean, but this takes up to 15 seconds (due to your sleep). You can still call thread.interrupt() if it's really urgent - but the prefered way should always be checking the flag.

To avoid waiting for 15 seconds, you can split up the sleep like this:

        ...
        try {
            LOGGER.debug("Sleeping...");
            for (int i = 0; (i < 150) && this.execute; i++) {
                Thread.sleep((long) 100);
            }

            LOGGER.debug("Processing");
        } catch (InterruptedException e) {
        ...

String comparison in Python: is vs. ==

See This question

Your logic in reading

For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.

is slightly flawed.

If is applies then == will be True, but it does NOT apply in reverse. == may yield True while is yields False.

Sequelize.js delete query?

  1. the best way to delete a record is to find it firstly (if exist in data base in the same time you want to delete it)
  2. watch this code
const StudentSequelize = require("../models/studientSequelize");
const StudentWork = StudentSequelize.Student;

const id = req.params.id;
    StudentWork.findByPk(id) // here i fetch result by ID sequelize V. 5
    .then( resultToDelete=>{
        resultToDelete.destroy(id); // when i find the result i deleted it by destroy function
    })
    .then( resultAfterDestroy=>{
        console.log("Deleted :",resultAfterDestroy);
    })
    .catch(err=> console.log(err));

How to show current user name in a cell?

if you don't want to create a UDF in VBA or you can't, this could be an alternative.

=Cell("Filename",A1) this will give you the full file name, and from this you could get the user name with something like this:

=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)


This Formula runs only from a workbook saved earlier.

You must start from 4th position because of the first slash from the drive.

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

Goto Window->Preferences, search for Launching.

Select the "Terminate and Relaunch while launching" option.

Press Apply.

String to Binary in C#

Here's an extension function:

        public static string ToBinary(this string data, bool formatBits = false)
        {
            char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))];
            int index = 0;
            for (int i = 0; i < data.Length; i++)
            {
                string binary = Convert.ToString(data[i], 2).PadLeft(8, '0');
                for (int j = 0; j < 8; j++)
                {
                    buffer[index] = binary[j];
                    index++;
                }
                if (formatBits && i < (data.Length - 1))
                {
                    buffer[index] = ' ';
                    index++;
                }
            }
            return new string(buffer);
        }

You can use it like:

Console.WriteLine("Testing".ToBinary());

and if you add 'true' as a parameter, it will automatically separate each binary sequence.

How to do a scatter plot with empty circles in Python?

So I assume you want to highlight some points that fit a certain criteria. You can use Prelude's command to do a second scatter plot of the hightlighted points with an empty circle and a first call to plot all the points. Make sure the s paramter is sufficiently small for the larger empty circles to enclose the smaller filled ones.

The other option is to not use scatter and draw the patches individually using the circle/ellipse command. These are in matplotlib.patches, here is some sample code on how to draw circles rectangles etc.

response.sendRedirect() from Servlet to JSP does not seem to work

You can use this:

response.sendRedirect(String.format("%s%s", request.getContextPath(), "/views/equipment/createEquipment.jsp"));

The last part is your path in your web-app

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

My mongo (3.2.9) was installed on Ubuntu, and my log file had the following lines:

2016-09-28T11:32:07.821+0100 E STORAGE  [initandlisten] WiredTiger (13) [1475058727:821829][6785:0x7fa9684ecc80], file:WiredTiger.wt, connection: /var/lib/mongodb/WiredTiger.turtle: handle-open: open: Permission denied 
2016-09-28T11:32:07.822+0100 I -        [initandlisten] Assertion: 28595:13: Permission denied 
2016-09-28T11:32:07.822+0100 I STORAGE  [initandlisten] exception in initAndListen: 28595 13: Permission denied, terminating

2016-09-28T11:32:07.822+0100 I CONTROL [initandlisten] dbexit: rc: 100

So the problem was in permissions on /var/lib/mongodb folder.

sudo chown -R mongodb:mongodb /var/lib/mongodb/
sudo chmod -R 755 /var/lib/mongodb
  • Restart the server

Fixed it, although I do realise that may be not too secure (it's my own dev box I'm in my case), bit following the change both db and authentication worked.

How to search JSON tree with jQuery

    var GDNUtils = {};

GDNUtils.loadJquery = function () {
    var checkjquery = window.jQuery && jQuery.fn && /^1\.[3-9]/.test(jQuery.fn.jquery);
    if (!checkjquery) {

        var theNewScript = document.createElement("script");
        theNewScript.type = "text/javascript";
        theNewScript.src = "http://code.jquery.com/jquery.min.js";

        document.getElementsByTagName("head")[0].appendChild(theNewScript);

        // jQuery MAY OR MAY NOT be loaded at this stage


    }
};



GDNUtils.searchJsonValue = function (jsonData, keytoSearch, valuetoSearch, keytoGet) {
    GDNUtils.loadJquery();
    alert('here' + jsonData.length.toString());
    GDNUtils.loadJquery();

    $.each(jsonData, function (i, v) {

        if (v[keytoSearch] == valuetoSearch) {
            alert(v[keytoGet].toString());

            return;
        }
    });



};




GDNUtils.searchJson = function (jsonData, keytoSearch, valuetoSearch) {
    GDNUtils.loadJquery();
    alert('here' + jsonData.length.toString());
    GDNUtils.loadJquery();
    var row;
    $.each(jsonData, function (i, v) {

        if (v[keytoSearch] == valuetoSearch) {


            row  = v;
        }
    });

    return row;



}

Removing address bar from browser (to view on Android)

this works on android (at least on stock gingerbread browser):

<body onload="document.body.style.height=(2*window.innerHeight-window.outerHeight)+'px';"></body>

further if you want to disable scrolling you can use

setInterval(function(){window.scrollTo(1,0)},50);

update listview dynamically with adapter

SimpleListAdapter's are primarily used for static data! If you want to handle dynamic data, you're better off working with an ArrayAdapter, ListAdapter or with a CursorAdapter if your data is coming in from the database.

Here's a useful tutorial in understanding binding data in a ListAdapter

As referenced in this SO question

How/when to generate Gradle wrapper files?

If you want to download gradle with source and docs, the default distribution url configured in gradle-wrapper.properites will not satisfy your need.It is https://services.gradle.org/distributions/gradle-2.10-bin.zip, not https://services.gradle.org/distributions/gradle-2.10-all.zip.This full url is suggested by IDE such as Android Studio.If you want to download the full gradle,You can configure the wrapper task like this:

task wrapper(type: Wrapper) {
    gradleVersion = '2.13'
    distributionUrl = distributionUrl.replace("bin", "all")
}

How to convert BigDecimal to Double in Java?

You need to use the doubleValue() method to get the double value from a BigDecimal object.

BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want

How to create a label inside an <input> element?

<input name="searchbox" onfocus="if (this.value=='search') this.value = ''" type="text" value="search">

A better example would be the SO search button! That's where I got this code from. Viewing page source is a valuable tool.

Best way to convert strings to symbols in hash

So many answers here, but the one method rails function is hash.symbolize_keys

how to play video from url

please check this link : http://developer.android.com/guide/appendix/media-formats.html

videoview can't support some codec .

i suggested you to use mediaplayer , when get "sorry , can't play video"

Understanding inplace=True

inplace=True is used depending if you want to make changes to the original df or not.

df.drop_duplicates()

will only make a view of dropped values but not make any changes to df

df.drop_duplicates(inplace  = True)

will drop values and make changes to df.

Hope this helps.:)

What is an idempotent operation?

Just wanted to throw out a real use case that demonstrates idempotence. In JavaScript, say you are defining a bunch of model classes (as in MVC model). The way this is often implemented is functionally equivalent to something like this (basic example):

function model(name) {
  function Model() {
    this.name = name;
  }

  return Model;
}

You could then define new classes like this:

var User = model('user');
var Article = model('article');

But if you were to try to get the User class via model('user'), from somewhere else in the code, it would fail:

var User = model('user');
// ... then somewhere else in the code (in a different scope)
var User = model('user');

Those two User constructors would be different. That is,

model('user') !== model('user');

To make it idempotent, you would just add some sort of caching mechanism, like this:

var collection = {};

function model(name) {
  if (collection[name])
    return collection[name];

  function Model() {
    this.name = name;
  }

  collection[name] = Model;
  return Model;
}

By adding caching, every time you did model('user') it will be the same object, and so it's idempotent. So:

model('user') === model('user');

How to change fonts in matplotlib (python)?

You can also use rcParams to change the font family globally.

 import matplotlib.pyplot as plt
 plt.rcParams["font.family"] = "cursive"
 # This will change to your computer's default cursive font

The list of matplotlib's font family arguments is here.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

In the build.gradle file for your app module, add this to the defaultConfig section (under the android section). This will write out the schema to a schemas subfolder of your project folder.

javaCompileOptions {
    annotationProcessorOptions {
        arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
    }
}

Like this:

// ...

android {
    
    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)
        
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }
   
    // ... (buildTypes, compileOptions, etc)

}

// ...

syntax error, unexpected T_VARIABLE

If that is the entire line, it very well might be because you are missing a ; at the end of the line.

How to change the decimal separator of DecimalFormat from comma to dot/point?

This worked in my case:

DecimalFormat df2 = new DecimalFormat("#.##");           
df2.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH));

Setting multiple attributes for an element at once with JavaScript

You could code an ES5.1 helper function:

function setAttributes(el, attrs) {
    Object.keys(attrs).forEach(key => el.setAttribute(key, attrs[key]));
}

Call it like this:

setAttributes(elem, { src: 'http://example.com/something.jpeg', height: '100%' });

libpthread.so.0: error adding symbols: DSO missing from command line

If using g++, make sure that you are not running gcc instead

Android: Flush DNS

Perform a hard reboot of your phone. The easiest way to do this is to remove the phone's battery. Wait for at least 30 seconds, then replace the battery. The phone will reboot, and upon completing its restart will have an empty DNS cache.

Read more: How to Flush the DNS on an Android Phone | eHow.com http://www.ehow.com/how_10021288_flush-dns-android-phone.html#ixzz1gRJnmiJb

Where does Console.WriteLine go in ASP.NET?

if you happened to use NLog in your ASP.net project, you can add a Debugger target:

<targets>
    <target name="debugger" xsi:type="Debugger"
            layout="${date:format=HH\:mm\:ss}|${pad:padding=5:inner=${level:uppercase=true}}|${message} "/>

and writes logs to this target for the levels you want:

<rules>
    <logger name="*" minlevel="Trace" writeTo="debugger" />

now you have console output just like Jetty in "Output" window of VS, and make sure you are running in Debug Mode(F5).

Linq select object from list depending on objects attribute

I think you are looking for this?

var correctAnswer = Answers.First(a => a.Correct);

You can use single by typing :

var correctAnswer = Answers.Single(a => a.Correct);

Using a .php file to generate a MySQL dump

As long as you are allowed to use exec(), you can execute shell commands through your PHP code.

So assuming you know how to write the mysqldump in the command line, i.e.

mysqldump -u [username] -p [database] > [database].sql

then you can use this as the parameter to exec() function.

exec("mysqldump -u mysqluser -p my_database > my_database_dump.sql");

What is the significance of load factor in HashMap?

What is load factor ?

The amount of capacity which is to be exhausted for the HashMap to increase its capacity ?

Why load factor ?

Load factor is by default 0.75 of the initial capacity (16) therefore 25% of the buckets will be free before there is an increase in the capacity & this makes many new buckets with new hashcodes pointing to them to exist just after the increase in the number of buckets.

Now why should you keep many free buckets & what is the impact of keeping free buckets on the performance ?

If you set the loading factor to say 1.0 then something very interesting might happen.

Say you are adding an object x to your hashmap whose hashCode is 888 & in your hashmap the bucket representing the hashcode is free , so the object x gets added to the bucket, but now again say if you are adding another object y whose hashCode is also 888 then your object y will get added for sure BUT at the end of the bucket (because the buckets are nothing but linkedList implementation storing key,value & next) now this has a performance impact ! Since your object y is no longer present in the head of the bucket if you perform a lookup the time taken is not going to be O(1) this time it depends on how many items are there in the same bucket. This is called hash collision by the way & this even happens when your loading factor is less than 1.

Correlation between performance , hash collision & loading factor ?

Lower load factor = more free buckets = less chances of collision = high performance = high space requirement.

Correct me if i am wrong somewhere.

Django: multiple models in one template using forms

"I want to hide some of the fields and do some complex validation."

I start with the built-in admin interface.

  1. Build the ModelForm to show the desired fields.

  2. Extend the Form with the validation rules within the form. Usually this is a clean method.

    Be sure this part works reasonably well.

Once this is done, you can move away from the built-in admin interface.

Then you can fool around with multiple, partially related forms on a single web page. This is a bunch of template stuff to present all the forms on a single page.

Then you have to write the view function to read and validated the various form things and do the various object saves().

"Is it a design issue if I break down and hand-code everything?" No, it's just a lot of time for not much benefit.

How to convert a string variable containing time to time_t type in c++?

With C++11 you can now do

struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);

see std::get_time and strftime for reference

Making a Windows shortcut start relative to where the folder is?

If you can set a system variable (something like %MyGameFolder%), then you can use that in your paths and shortcuts, and Windows will fill in rest of the path for you (that is, %MyGameFolder%\data\MyGame.exe).

Here is a small primer. You can either set this value via a batch file, or you can probably set it programmatically if you share how you're planning to create your shortcut.

How do you change the size of figures drawn with matplotlib?

This resizes the figure immediately even after the figure has been drawn (at least using Qt4Agg/TkAgg - but not MacOSX - with matplotlib 1.4.0):

matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)

Basic Authentication Using JavaScript

EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.

What is the difference between String.slice and String.substring?

Note: if you're in a hurry, and/or looking for short answer scroll to the bottom of the answer, and read the last two lines.if Not in a hurry read the whole thing.


let me start by stating the facts:

Syntax:
string.slice(start,end)
string.substr(start,length)
string.substring(start,end)
Note #1: slice()==substring()

What it does?
The slice() method extracts parts of a string and returns the extracted parts in a new string.
The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
The substring() method extracts parts of a string and returns the extracted parts in a new string.
Note #2:slice()==substring()

Changes the Original String?
slice() Doesn't
substr() Doesn't
substring() Doesn't
Note #3:slice()==substring()

Using Negative Numbers as an Argument:
slice() selects characters starting from the end of the string
substr()selects characters starting from the end of the string
substring() Doesn't Perform
Note #3:slice()==substr()

if the First Argument is Greater than the Second:
slice() Doesn't Perform
substr() since the Second Argument is NOT a position, but length value, it will perform as usual, with no problems
substring() will swap the two arguments, and perform as usual

the First Argument:
slice() Required, indicates: Starting Index
substr() Required, indicates: Starting Index
substring() Required, indicates: Starting Index
Note #4:slice()==substr()==substring()

the Second Argument:
slice() Optional, The position (up to, but not including) where to end the extraction
substr() Optional, The number of characters to extract
substring() Optional, The position (up to, but not including) where to end the extraction
Note #5:slice()==substring()

What if the Second Argument is Omitted?
slice() selects all characters from the start-position to the end of the string
substr() selects all characters from the start-position to the end of the string
substring() selects all characters from the start-position to the end of the string
Note #6:slice()==substr()==substring()

so, you can say that there's a difference between slice() and substr(), while substring() is basically a copy of slice().

in Summary:
if you know the index(the position) on which you'll stop (but NOT include), Use slice()
if you know the length of characters to be extracted use substr().

How to install Android app on LG smart TV?

Thanks for the research FIRESTICK is a solution for non Android based but there's another one Im using if you guys want to try it let me know...

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP, PHILCO and TOSHIBA.

Sass - Converting Hex to RGBa for background opacity

There is a builtin mixin: transparentize($color, $amount);

background-color: transparentize(#F05353, .3);

The amount should be between 0 to 1;

Official Sass Documentation (Module: Sass::Script::Functions)

Javascript - removing undefined fields from an object

Another Javascript Solution

for(var i=0,keys = Object.keys(obj),len=keys.length;i<len;i++){ 
  if(typeof obj[keys[i]] === 'undefined'){
    delete obj[keys[i]];
  }
}

No additional hasOwnProperty check is required as Object.keys does not look up the prototype chain and returns only the properties of obj.

DEMO

How to remove first 10 characters from a string?

Starting from C# 8, you simply can use Range Operator. It's the more efficient and better way to handle such cases.

string AnString = "Hello World!";
AnString = AnString[10..];

How can I pass a list as a command-line argument with argparse?

Using nargs parameter in argparse's add_argument method

I use nargs='*' as an add_argument parameter. I specifically used nargs='*' to the option to pick defaults if I am not passing any explicit arguments

Including a code snippet as example:

Example: temp_args1.py

Please Note: The below sample code is written in python3. By changing the print statement format, can run in python2

#!/usr/local/bin/python3.6

from argparse import ArgumentParser

description = 'testing for passing multiple arguments and to get list of args'
parser = ArgumentParser(description=description)
parser.add_argument('-i', '--item', action='store', dest='alist',
                    type=str, nargs='*', default=['item1', 'item2', 'item3'],
                    help="Examples: -i item1 item2, -i item3")
opts = parser.parse_args()

print("List of items: {}".format(opts.alist))

Note: I am collecting multiple string arguments that gets stored in the list - opts.alist If you want list of integers, change the type parameter on parser.add_argument to int

Execution Result:

python3.6 temp_agrs1.py -i item5 item6 item7
List of items: ['item5', 'item6', 'item7']

python3.6 temp_agrs1.py -i item10
List of items: ['item10']

python3.6 temp_agrs1.py
List of items: ['item1', 'item2', 'item3']

Convert seconds to HH-MM-SS with JavaScript?

--update 2

Please use @Frank's a one line solution:

new Date(SECONDS * 1000).toISOString().substr(11, 8)

It is by far the best solution.

Procedure expects parameter which was not supplied

I came across this error today when null values were passed to my stored procedure's parameters. I was able easily fix by altering the stored procedure by adding default value = null.

How to check whether java is installed on the computer

command prompt:

C:\Users\admin>java -version (Press Enter>
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)

Purpose of ESI & EDI registers?

SI = Source Index
DI = Destination Index

As others have indicated, they have special uses with the string instructions. For real mode programming, the ES segment register must be used with DI and DS with SI as in

movsb  es:di, ds:si

SI and DI can also be used as general purpose index registers. For example, the C source code

srcp [srcidx++] = argv [j];

compiles into

8B550C         mov    edx,[ebp+0C]
8B0C9A         mov    ecx,[edx+4*ebx]
894CBDAC       mov    [ebp+4*edi-54],ecx
47             inc    edi

where ebp+12 contains argv, ebx is j, and edi has srcidx. Notice the third instruction uses edi mulitplied by 4 and adds ebp offset by 0x54 (the location of srcp); brackets around the address indicate indirection.


Though I can't remember where I saw it, but this confirms most of it, and this (slide 17) others:

AX = accumulator
DX = double word accumulator
CX = counter
BX = base register

They look like general purpose registers, but there are a number of instructions which (unexpectedly?) use one of them—but which one?—implicitly.

Entity Framework: There is already an open DataReader associated with this Command

You get this error, when the collection you are trying to iterate is kind of lazy loading (IQueriable).

foreach (var user in _dbContext.Users)
{    
}

Converting the IQueriable collection into other enumerable collection will solve this problem. example

_dbContext.Users.ToList()

Note: .ToList() creates a new set every-time and it can cause the performance issue if you are dealing with large data.

Java: how to represent graphs?

Time ago I had the same problem and did my own implementation. What I suggest you is to implement another class: Edge. Then, a Vertex will have a List of Edge.

public class Edge {
    private Node a, b;
    private directionEnum direction;     // AB, BA or both
    private int weight;
    ...
}

It worked for me. But maybe is so simple. There is this library that maybe can help you if you look into its code: http://jgrapht.sourceforge.net/

Pip - Fatal error in launcher: Unable to create process using '"'

I got the same error and followed a couple of answers. I have tried to upgrade and install 9.0.0 version of pip using the commands below

python3 -m pip install --upgrade pip
python -m pip install pip==9.0.0

For both the commands I got the warning which looked like this

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None))

Nothing seemed to work. I lost my patients and followed the below steps and got it working

  1. Navigate to the path "C:\Users...Python\Python37-32\Scripts"
  2. Delete the files pip ,pip3 , pip3.7
  3. Then I used the command python -m pip install pip==9.0.0 which then installed pip
  4. Then I entered the required command of pyperclip which I wanted to leverage which was pip install pyperclip

Ignore the 4th step. Adding it only to let people know I was also able to install the required pyperclip seemlessly, if at all anyone is on the same path to install some modules further

How do I simulate a hover with a touch in touch enabled browsers?

One way to do it would be to do the hover effect when the touch starts, then remove the hover effect when the touch moves or ends.

This is what Apple has to say about touch handling in general, since you mention iPhone.

What's the main difference between int.Parse() and Convert.ToInt32

Convert.ToInt32

has 19 overloads or 19 different ways that you can call it. Maybe more in 2010 versions.

It will attempt to convert from the following TYPES;

Object, Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, String, Date

and it also has a number of other methods; one to do with a number base and 2 methods involve a System.IFormatProvider

Parse on the other hand only has 4 overloads or 4 different ways you can call the method.

Integer.Parse( s As String)

Integer.Parse( s As String,  style As System.Globalization.NumberStyles )

Integer.Parse( s As String, provider As System.IFormatProvider )

Integer.Parse( s As String,  style As System.Globalization.NumberStyles, provider As System.IFormatProvider )

What version of Python is on my Mac?

Use below command to see all python installations :

which -a python

Make page to tell browser not to cache/preserve input values

This worked for me in newer browsers:

autocomplete="new-password"

Python, print all floats to 2 decimal places in output

If what you want is to have the print operation automatically change floats to only show 2 decimal places, consider writing a function to replace 'print'. For instance:

def fp(*args):  # fp means 'floating print'
    tmps = []
    for arg in args:
        if type(arg) is float: arg = round(arg, 2)  # transform only floats
        tmps.append(str(arg))
    print(" ".join(tmps)

Use fp() in place of print ...

fp("PI is", 3.14159) ... instead of ... print "PI is", 3.14159

phonegap open link in browser

If you happen to have jQuery around, you can intercept the click on the link like this:

$(document).on('click', 'a', function (event) {
    event.preventDefault();
    window.open($(this).attr('href'), '_system');
    return false;
});

This way you don't have to modify the links in the html, which can save a lot of time. I have set this up using a delegate, that's why you see it being tied to the document object, with the 'a' tag as the second argument. This way all 'a' tags will be handled, regardless of when they are added.

Ofcourse you still have to install the InAppBrowser plug-in:

cordova plugin add org.apache.cordova.inappbrowser

Sending the bearer token with axios

axios by itself comes with two useful "methods" the interceptors that are none but middlewares between the request and the response. so if on each request you want to send the token. Use the interceptor.request.

I made apackage that helps you out:

$ npm i axios-es6-class

Now you can use axios as class

export class UserApi extends Api {
    constructor (config) {
        super(config);

        // this middleware is been called right before the http request is made.
        this.interceptors.request.use(param => {
            return {
                ...param,
                defaults: {
                    headers: {
                        ...param.headers,
                        "Authorization": `Bearer ${this.getToken()}`
                    },
                }
            }
        });

      this.login = this.login.bind(this);
      this.getSome = this.getSome.bind(this);
   }

   login (credentials) {
      return this.post("/end-point", {...credentials})
      .then(response => this.setToken(response.data))
      .catch(this.error);
   }


   getSome () {
      return this.get("/end-point")
      .then(this.success)
      .catch(this.error);
   }
}

I mean the implementation of the middleware depends on you, or if you prefer to create your own axios-es6-class https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a it is the medium post where it came from

Jmeter - get current date and time

Use __time function:

  • ${__time(dd/MM/yyyy,)}

  • ${__time(hh:mm a,)}

Since JMeter 3.3, there are two new functions that let you compute a time:

__timeShift

  "The timeShift function returns a date in the given format with the specified amount of seconds, minutes, hours, days or months added" and 

__RandomDate

  "The RandomDate function returns a random date that lies between the given start date and end date values." 

Since JMeter 4.0:

dateTimeConvert

Convert a date or time from source to target format

If you're looking to learn jmeter correctly, this book will help you.

Get type of all variables

You need to use get to obtain the value rather than the character name of the object as returned by ls:

x <- 1L
typeof(ls())
[1] "character"
typeof(get(ls()))
[1] "integer"

Alternatively, for the problem as presented you might want to use eapply:

eapply(.GlobalEnv,typeof)
$x
[1] "integer"

$a
[1] "double"

$b
[1] "character"

$c
[1] "list"

Jquery submit form

If you have only 1 form in you page, use this. You do not need to know id or name of the form. I just used this code - working:

document.forms[0].submit();

Can I make 'git diff' only the line numbers AND changed file names?

So easy:

git diff --name-only

Go forth and diff!

Is a LINQ statement faster than a 'foreach' loop?

LINQ-to-Objects generally is going to add some marginal overheads (multiple iterators, etc). It still has to do the loops, and has delegate invokes, and will generally have to do some extra dereferencing to get at captured variables etc. In most code this will be virtually undetectable, and more than afforded by the simpler to understand code.

With other LINQ providers like LINQ-to-SQL, then since the query can filter at the server it should be much better than a flat foreach, but most likely you wouldn't have done a blanket "select * from foo" anyway, so that isn't necessarily a fair comparison.

Re PLINQ; parallelism may reduce the elapsed time, but the total CPU time will usually increase a little due to the overheads of thread management etc.

Implementing a simple file download servlet

That depends. If said file is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect().

If it's not, you'll need to manually copy it to response output stream:

OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
    out.write(buffer, 0, length);
}
in.close();
out.flush();

You'll need to handle the appropriate exceptions, of course.

How to insert logo with the title of a HTML page?

Are you referring to the favicon?

Upload a 16x16px ico to your site, and link it in your head section.

<link rel="shortcut icon" href="/favicon.ico" />

There are a multitude of sites that help you convert images into .ico format too. This is just the first one I saw on Google. http://www.favicon.cc/

Executing multiple commands from a Windows cmd script

I don't know the direct answer to your question, but if you do a lot of these scripts, it might be worth learning a more powerful language like perl. Free implementations exist for Windows (e.g. activestate, cygwin). I've found it worth the initial effort for my own tasks.

Edit:

As suggested by @Ferruccio, if you can't install extra software, consider vbscript and/or javascript. They're built into the Windows scripting host.

How to implement debounce in Vue2?

In case you need to apply a dynamic delay with the lodash's debounce function:

props: {
  delay: String
},

data: () => ({
  search: null
}),

created () {
     this.valueChanged = debounce(function (event) {
      // Here you have access to `this`
      this.makeAPIrequest(event.target.value)
    }.bind(this), this.delay)

},

methods: {
  makeAPIrequest (newVal) {
    // ...
  }
}

And the template:

<template>
  //...

   <input type="text" v-model="search" @input="valueChanged" />

  //...
</template>

NOTE: in the example above I made an example of search input which can call the API with a custom delay which is provided in props

Get value of input field inside an iframe

document.getElementById("idframe").contentWindow.document.getElementById("idelement").value;

Remove last item from array

Simply arr.splice(-1) will do.

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

mysql_fetch_array() expects parameter 1 to be resource boolean given in php error on server if you get this error : please select all privileges on your server. u will get the answer..

css 100% width div not taking up full width of parent

html, body{ 
  width:100%;
}

This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.

You may want to set a min width instead.

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

So it will be 100% as a minimum, bot more if needed.

how to release localhost from Error: listen EADDRINUSE

I created 2 servers, listening on same port 8081, running from same code, while learning

1st server creation shud have worked 2nd server creation failed with EADDRINUSE

node.js callback delays might be reason behind neither worked, or 2nd server creation had exception, and program exited, so 1st server is also closed

2 server issue hint, I got from: How to fix Error: listen EADDRINUSE while using nodejs?

How to create radio buttons and checkbox in swift (iOS)?

Check out DLRadioButton. You can add and customize radio buttons directly from the Interface Builder. Also works with Swift perfectly.

Swift Radio Button for iOS

Update: version 1.3.2 added square buttons, also improved performance.

Update: version 1.4.4 added multiple selection option, can be used as checkbox as well.

Update: version 1.4.7 added RTL language support.

vue.js 2 how to watch store values from vuex

_x000D_
_x000D_
====== store =====_x000D_
import Vue from 'vue'_x000D_
import Vuex from 'vuex'_x000D_
import axios from 'axios'_x000D_
_x000D_
Vue.use(Vuex)_x000D_
_x000D_
export default new Vuex.Store({_x000D_
  state: {_x000D_
    showRegisterLoginPage: true,_x000D_
    user: null,_x000D_
    allitem: null,_x000D_
    productShow: null,_x000D_
    userCart: null_x000D_
  },_x000D_
  mutations: {_x000D_
    SET_USERS(state, payload) {_x000D_
      state.user = payload_x000D_
    },_x000D_
    HIDE_LOGIN(state) {_x000D_
      state.showRegisterLoginPage = false_x000D_
    },_x000D_
    SHOW_LOGIN(state) {_x000D_
      state.showRegisterLoginPage = true_x000D_
    },_x000D_
    SET_ALLITEM(state, payload) {_x000D_
      state.allitem = payload_x000D_
    },_x000D_
    SET_PRODUCTSHOW(state, payload) {_x000D_
      state.productShow = payload_x000D_
    },_x000D_
    SET_USERCART(state, payload) {_x000D_
      state.userCart = payload_x000D_
    }_x000D_
  },_x000D_
  actions: {_x000D_
    getUserLogin({ commit }) {_x000D_
      axios({_x000D_
        method: 'get',_x000D_
        url: 'http://localhost:3000/users',_x000D_
        headers: {_x000D_
          token: localStorage.getItem('token')_x000D_
        }_x000D_
      })_x000D_
        .then(({ data }) => {_x000D_
          // console.log(data)_x000D_
          commit('SET_USERS', data)_x000D_
        })_x000D_
        .catch(err => {_x000D_
          console.log(err)_x000D_
        })_x000D_
    },_x000D_
    addItem({ dispatch }, payload) {_x000D_
      let formData = new FormData()_x000D_
      formData.append('name', payload.name)_x000D_
      formData.append('file', payload.file)_x000D_
      formData.append('category', payload.category)_x000D_
      formData.append('price', payload.price)_x000D_
      formData.append('stock', payload.stock)_x000D_
      formData.append('description', payload.description)_x000D_
      axios({_x000D_
        method: 'post',_x000D_
        url: 'http://localhost:3000/products',_x000D_
        data: formData,_x000D_
        headers: {_x000D_
          token: localStorage.getItem('token')_x000D_
        }_x000D_
      })_x000D_
        .then(({ data }) => {_x000D_
          // console.log('data hasbeen created ', data)_x000D_
          dispatch('getAllItem')_x000D_
        })_x000D_
        .catch(err => {_x000D_
          console.log(err)_x000D_
        })_x000D_
    },_x000D_
    getAllItem({ commit }) {_x000D_
      axios({_x000D_
        method: 'get',_x000D_
        url: 'http://localhost:3000/products'_x000D_
      })_x000D_
        .then(({ data }) => {_x000D_
          // console.log(data)_x000D_
          commit('SET_ALLITEM', data)_x000D_
        })_x000D_
        .catch(err => {_x000D_
          console.log(err)_x000D_
        })_x000D_
    },_x000D_
    addUserCart({ dispatch }, { payload, productId }) {_x000D_
      let newCart = {_x000D_
        count: payload_x000D_
      }_x000D_
      // console.log('ini dari store nya', productId)_x000D_
_x000D_
      axios({_x000D_
        method: 'post',_x000D_
        url: `http://localhost:3000/transactions/${productId}`,_x000D_
        data: newCart,_x000D_
        headers: {_x000D_
          token: localStorage.getItem('token')_x000D_
        }_x000D_
      })_x000D_
        .then(({ data }) => {_x000D_
          dispatch('getUserCart')_x000D_
          // console.log('cart hasbeen added ', data)_x000D_
        })_x000D_
        .catch(err => {_x000D_
          console.log(err)_x000D_
        })_x000D_
    },_x000D_
    getUserCart({ commit }) {_x000D_
      axios({_x000D_
        method: 'get',_x000D_
        url: 'http://localhost:3000/transactions/user',_x000D_
        headers: {_x000D_
          token: localStorage.getItem('token')_x000D_
        }_x000D_
      })_x000D_
        .then(({ data }) => {_x000D_
          // console.log(data)_x000D_
          commit('SET_USERCART', data)_x000D_
        })_x000D_
        .catch(err => {_x000D_
          console.log(err)_x000D_
        })_x000D_
    },_x000D_
    cartCheckout({ commit, dispatch }, transactionId) {_x000D_
      let count = null_x000D_
      axios({_x000D_
        method: 'post',_x000D_
        url: `http://localhost:3000/transactions/checkout/${transactionId}`,_x000D_
        headers: {_x000D_
          token: localStorage.getItem('token')_x000D_
        },_x000D_
        data: {_x000D_
          sesuatu: 'sesuatu'_x000D_
        }_x000D_
      })_x000D_
        .then(({ data }) => {_x000D_
          count = data.count_x000D_
          console.log(count, data)_x000D_
_x000D_
          dispatch('getUserCart')_x000D_
        })_x000D_
        .catch(err => {_x000D_
          console.log(err)_x000D_
        })_x000D_
    },_x000D_
    deleteTransactions({ dispatch }, transactionId) {_x000D_
      axios({_x000D_
        method: 'delete',_x000D_
        url: `http://localhost:3000/transactions/${transactionId}`,_x000D_
        headers: {_x000D_
          token: localStorage.getItem('token')_x000D_
        }_x000D_
      })_x000D_
        .then(({ data }) => {_x000D_
          console.log('success delete')_x000D_
_x000D_
          dispatch('getUserCart')_x000D_
        })_x000D_
        .catch(err => {_x000D_
          console.log(err)_x000D_
        })_x000D_
    }_x000D_
  },_x000D_
  modules: {}_x000D_
})
_x000D_
_x000D_
_x000D_

What's a good way to extend Error in JavaScript?

Custom Error Decorator

This is based on George Bailey's answer, but extends and simplifies the original idea. It is written in CoffeeScript, but is easy to convert to JavaScript. The idea is extend Bailey's custom error with a decorator that wraps it, allowing you to create new custom errors easily.

Note: This will only work in V8. There is no support for Error.captureStackTrace in other environments.

Define

The decorator takes a name for the error type, and returns a function that takes an error message, and encloses the error name.

CoreError = (@message) ->

    @constructor.prototype.__proto__ = Error.prototype
    Error.captureStackTrace @, @constructor
    @name = @constructor.name

BaseError = (type) ->

    (message) -> new CoreError "#{ type }Error: #{ message }"

Use

Now it is simple to create new error types.

StorageError   = BaseError "Storage"
SignatureError = BaseError "Signature"

For fun, you could now define a function that throws a SignatureError if it is called with too many args.

f = -> throw SignatureError "too many args" if arguments.length

This has been tested pretty well and seems to work perfectly on V8, maintaing the traceback, position etc.

Note: Using new is optional when constructing a custom error.

How to create a file with a given size in Linux?

Use fallocate if you don't want to wait for disk.

Example:

fallocate -l 100G BigFile

Usage:

Usage:
 fallocate [options] <filename>

Preallocate space to, or deallocate space from a file.

Options:
 -c, --collapse-range remove a range from the file
 -d, --dig-holes      detect zeroes and replace with holes
 -i, --insert-range   insert a hole at range, shifting existing data
 -l, --length <num>   length for range operations, in bytes
 -n, --keep-size      maintain the apparent size of the file
 -o, --offset <num>   offset for range operations, in bytes
 -p, --punch-hole     replace a range with a hole (implies -n)
 -z, --zero-range     zero and ensure allocation of a range
 -x, --posix          use posix_fallocate(3) instead of fallocate(2)
 -v, --verbose        verbose mode

 -h, --help           display this help
 -V, --version        display version

"could not find stored procedure"

Walk of shame:

The connection string was pointing at the live database. The error message was completely accurate - the stored procedure was only present in the dev DB. Thanks to all who provided excellent answers, and my apologies for wasting your time.

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

Following is the solution which worked for me. The files which I updated are as follows:

  1. config.xml (Full Path: /config.xml)
  2. network_security_config.xml (Full Path: /resources/android/xml/network_security_config.xml)

Changes in the corresponding files are as follows:

1. config.xml

I have added <application android:usesCleartextTraffic="true" /> tag within <edit-config> tag in the config.xml file

<platform name="android">
    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
        <application android:usesCleartextTraffic="true" />
        <application android:networkSecurityConfig="@xml/network_security_config" />
    </edit-config>
    ...
<platform name="android">

2. network_security_config.xml

In this file I have added 2 <domain> tag within <domain-config> tag, the main domain and a sub domain as per my project requirement

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">mywebsite.in</domain>
        <domain includeSubdomains="true">api.mywebsite.in</domain>
    </domain-config>
</network-security-config>

Thanks @Ashutosh for the providing the help.

Hope it helps.

filter items in a python dictionary where keys contain a specific string

input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}

Is it possible to find out the users who have checked out my project on GitHub?

I believe this is an old question, and the Traffic was introduced by Github in 2014. Here is the link to the description of Traffic, that tells you the views on your repositories.

How to start automatic download of a file in Internet Explorer?

I checked and found, it will work on button click via writing onclick event to Anchor tag or Input button

onclick='javascript:setTimeout(window.location=[File location], 1000);'

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

WPF: Grid with column/row margin/padding?

Though you can't add margin or padding to a Grid, you could use something like a Frame (or similar container), that you can apply it to.

That way (if you show or hide the control on a button click say), you won't need to add margin on every control that may interact with it.

Think of it as isolating the groups of controls into units, then applying style to those units.

Parsing XML with namespace in Python via 'ElementTree'

Note: This is an answer useful for Python's ElementTree standard library without using hardcoded namespaces.

To extract namespace's prefixes and URI from XML data you can use ElementTree.iterparse function, parsing only namespace start events (start-ns):

>>> from io import StringIO
>>> from xml.etree import ElementTree
>>> my_schema = u'''<rdf:RDF xml:base="http://dbpedia.org/ontology/"
...     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
...     xmlns:owl="http://www.w3.org/2002/07/owl#"
...     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
...     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
...     xmlns="http://dbpedia.org/ontology/">
... 
...     <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
...         <rdfs:label xml:lang="en">basketball league</rdfs:label>
...         <rdfs:comment xml:lang="en">
...           a group of sports teams that compete against each other
...           in Basketball
...         </rdfs:comment>
...     </owl:Class>
... 
... </rdf:RDF>'''
>>> my_namespaces = dict([
...     node for _, node in ElementTree.iterparse(
...         StringIO(my_schema), events=['start-ns']
...     )
... ])
>>> from pprint import pprint
>>> pprint(my_namespaces)
{'': 'http://dbpedia.org/ontology/',
 'owl': 'http://www.w3.org/2002/07/owl#',
 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
 'xsd': 'http://www.w3.org/2001/XMLSchema#'}

Then the dictionary can be passed as argument to the search functions:

root.findall('owl:Class', my_namespaces)

Reload parent window from child window

this will work

window.location.assign(window.location.href);

What is the difference between prefix and postfix operators?

First, note that the function parameter named i and the variable named i in main() are two different variables. I think that doesn't matter that much to the present discussion, but it's important to know.

Second, you use the postincrement operator in fun(). That means the result of the expression is the value before i is incremented; the final value 11 of i is simply discarded, and the function returns 10. The variable i back in main, being a different variable, is assigned the value 10, which you then decrement to get 9.

Easy way to convert Iterable to Collection

I use my custom utility to cast an existing Collection if available.

Main:

public static <T> Collection<T> toCollection(Iterable<T> iterable) {
    if (iterable instanceof Collection) {
        return (Collection<T>) iterable;
    } else {
        return Lists.newArrayList(iterable);
    }
}

Ideally the above would use ImmutableList, but ImmutableCollection does not allow nulls which may provide undesirable results.

Tests:

@Test
public void testToCollectionAlreadyCollection() {
    ArrayList<String> list = Lists.newArrayList(FIRST, MIDDLE, LAST);
    assertSame("no need to change, just cast", list, toCollection(list));
}

@Test
public void testIterableToCollection() {
    final ArrayList<String> expected = Lists.newArrayList(FIRST, null, MIDDLE, LAST);

    Collection<String> collection = toCollection(new Iterable<String>() {
        @Override
        public Iterator<String> iterator() {
            return expected.iterator();
        }
    });
    assertNotSame("a new list must have been created", expected, collection);
    assertTrue(expected + " != " + collection, CollectionUtils.isEqualCollection(expected, collection));
}

I implement similar utilities for all subtypes of Collections (Set,List,etc). I'd think these would already be part of Guava, but I haven't found it.

how to configuring a xampp web server for different root directory

If you are running xampp on linux based image, to change root directory open:

/opt/lampp/etc/httpd.conf

Change default document root: DocumentRoot "/opt/lampp/htdocs" and <Directory "/opt/lampp/htdocs"

to your folder DocumentRoot "/opt/lampp/htdocs/myFolder" and <Directory "/opt/lampp/htdocs/myFolder">

How to split a comma-separated value to columns

ALTER function get_occurance_index(@delimiter varchar(1),@occurence int,@String varchar(100))
returns int
AS Begin
--Declare @delimiter varchar(1)=',',@occurence int=2,@String varchar(100)='a,b,c'
Declare @result int
 ;with T as (
    select 1 Rno,0 as row, charindex(@delimiter, @String) pos,@String st
    union all
    select Rno+1,pos + 1, charindex(@delimiter, @String, pos + 1), @String
    from T
    where pos > 0
)
select  @result=pos 
from T 
where pos > 0   and rno = @occurence 
return isnull(@result,0)
ENd


declare @data as table (data varchar(100))
insert into @data values('1,2,3') 
insert into @data values('aaa,bbbbb,cccc') 
select top  3 Substring (data,0,dbo.get_occurance_index( ',',1,data)) ,--First Record always starts with 0
Substring (data,dbo.get_occurance_index( ',',1,data)+1,dbo.get_occurance_index( ',',2,data)-dbo.get_occurance_index( ',',1,data)-1) ,
Substring (data,dbo.get_occurance_index( ',',2,data)+1,len(data)) , -- Last record cant be more than len of actual data
data 
From @data 

Locate the nginx.conf file my nginx is actually using

Running nginx -t through your commandline will issue out a test and append the output with the filepath to the configuration file (with either an error or success message).

Can I convert a boolean to Yes/No in a ASP.NET GridView

I had the same need as the original poster, except that my client's db schema is a nullable bit (ie, allows for True/False/NULL). Here's some code I wrote to both display Yes/No and handle potential nulls.

Code-Behind:

public string ConvertNullableBoolToYesNo(object pBool)
{
    if (pBool != null)
    {
        return (bool)pBool ? "Yes" : "No";
    }
    else
    {
        return "No";
    }
}

Front-End:

<%# ConvertNullableBoolToYesNo(Eval("YOUR_FIELD"))%>

CAML query with nested ANDs and ORs for multiple fields

Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group (MSDN). The expression A AND B AND C looks like this:

<And>
    A
    <And>
        B
        C
    </And>
</And>

Your SQL like sample translated to CAML (hopefully with matching XML tags ;) ):

<Where>
    <And>
        <Or>
            <Eq>
                <FieldRef Name='FirstName' />
                <Value Type='Text'>John</Value>
            </Eq>
            <Or>
                <Eq>
                    <FieldRef Name='LastName' />
                    <Value Type='Text'>John</Value>
                </Eq>
                <Eq>
                    <FieldRef Name='Profile' />
                    <Value Type='Text'>John</Value>
                </Eq>
            </Or>
        </Or>
        <And>       
            <Or>
                <Eq>
                    <FieldRef Name='FirstName' />
                    <Value Type='Text'>Doe</Value>
                </Eq>
                <Or>
                    <Eq>
                        <FieldRef Name='LastName' />
                        <Value Type='Text'>Doe</Value>
                    </Eq>
                    <Eq>
                        <FieldRef Name='Profile' />
                        <Value Type='Text'>Doe</Value>
                    </Eq>
                </Or>
            </Or>
            <Or>
                <Eq>
                    <FieldRef Name='FirstName' />
                    <Value Type='Text'>123</Value>
                </Eq>
                <Or>
                    <Eq>
                        <FieldRef Name='LastName' />
                        <Value Type='Text'>123</Value>
                    </Eq>
                    <Eq>
                        <FieldRef Name='Profile' />
                        <Value Type='Text'>123</Value>
                    </Eq>
                </Or>
            </Or>
        </And>
    </And>
</Where>

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

After much aggravation, I discovered how to scroll in iframes on my ipad. The secret was to do a vertical finger swipe (single finger was fine) on the LEFT side of the iframe area (and maybe slightly outside of the border). On a laptop or PC, the scroll bar is on the right, so naturally, I spent of lot of time on my ipad experimenting with finger motions on the right side. Only when I tried the left side would the iframe scroll.

How to validate an Email in PHP?

Use:

var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
    new RFCValidation(),
    new DNSCheckValidation()
]);
$validator->isValid("[email protected]", $multipleValidations); //true

An Iframe I need to refresh every 30 seconds (but not the whole page)

You can put a meta refresh Tag in the irc_online.php

<meta http-equiv="refresh" content="30">

OR you can use Javascript with setInterval to refresh the src of the Source...

<script>
window.setInterval("reloadIFrame();", 30000);

function reloadIFrame() {
 document.frames["frameNameHere"].location.reload();
}
</script>

How to create a BKS (BouncyCastle) format Java Keystore that contains a client certificate chain

Your command for creating the BKS keystore looks correct for me.

How do you initialize the keystore.

You need to craeate and pass your own SSLSocketFactory. Here is an example which uses Apache's org.apache.http.conn.ssl.SSLSocketFactory

But I think you can do pretty the same on the javax.net.ssl.SSLSocketFactory

    private SSLSocketFactory newSslSocketFactory() {
    try {
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");
        // Get the raw resource, which contains the keystore with
        // your trusted certificates (root and any intermediate certs)
        InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
        try {
            // Initialize the keystore with the provided trusted certificates
            // Also provide the password of the keystore
            trusted.load(in, "testtest".toCharArray());
        } finally {
            in.close();
        }
        // Pass the keystore to the SSLSocketFactory. The factory is responsible
        // for the verification of the server certificate.
        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

Please let me know if it worked.

.NET Events - What are object sender & EventArgs e?

The sender is the control that the action is for (say OnClick, it's the button).

The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.

What Chris is saying is you can do this:

protected void someButton_Click (object sender, EventArgs ea)
{
    Button someButton = sender as Button;
    if(someButton != null)
    {
        someButton.Text = "I was clicked!";
    }
}

How to list the files in current directory?

Your code gives expected result,if you compile and run your code standalone(from commandline). As in eclipse for each project by default working directory is project directory that's why you are getting this result.

You can set user.dir property in java as:

   System.setProperty("user.dir", "absolute path of src folder");

then it will give expected result.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

CPMSifDlg::EncodeAndSend() method is declared as non-static and thus it must be called using an object of CPMSifDlg. e.g.

CPMSifDlg obj;
return obj.EncodeAndSend(firstName, lastName, roomNumber, userId, userFirstName, userLastName);

If EncodeAndSend doesn't use/relate any specifics of an object (i.e. this) but general for the class CPMSifDlg then declare it as static:

class CPMSifDlg {
...
  static int EncodeAndSend(...);
  ^^^^^^
};

How to get records randomly from the oracle database?

In summary, two ways were introduced

1) using order by DBMS_RANDOM.VALUE clause
2) using sample([%]) function

The first way has advantage in 'CORRECTNESS' which means you will never fail get result if it actually exists, while in the second way you may get no result even though it has cases satisfying the query condition since information is reduced during sampling.

The second way has advantage in 'EFFICIENT' which mean you will get result faster and give light load to your database. I was given an warning from DBA that my query using the first way gives loads to the database

You can choose one of two ways according to your interest!

Swift - How to detect orientation changes

You can use viewWillTransition(to:with:) and tap into animate(alongsideTransition:completion:) to get the interface orientation AFTER the transition is complete. You just have to define and implement a protocol similar to this in order to tap into the event. Note that this code was used for a SpriteKit game and your specific implementation may differ.

protocol CanReceiveTransitionEvents {
    func viewWillTransition(to size: CGSize)
    func interfaceOrientationChanged(to orientation: UIInterfaceOrientation)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        guard
            let skView = self.view as? SKView,
            let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }

        coordinator.animate(alongsideTransition: nil) { _ in
            if let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation {
                canReceiveRotationEvents.interfaceOrientationChanged(to: interfaceOrientation)
            }
        }

        canReceiveRotationEvents.viewWillTransition(to: size)
    }

You can set breakpoints in these functions and observe that interfaceOrientationChanged(to orientation: UIInterfaceOrientation) is always called after viewWillTransition(to size: CGSize) with the updated orientation.

Pointer vs. Reference

Use a reference when you can, use a pointer when you have to. From C++ FAQ: "When should I use references, and when should I use pointers?"

How to make the web page height to fit screen height

you can use css to set the body tag to these settings:

body
{
padding:0px;
margin:0px;
width:100%;
height:100%;
}

Does a valid XML file require an XML declaration?

Xml declaration is optional so your xml is well-formed without it. But it is recommended to use it so that wrong assumptions are not made by the parsers, specifically about the encoding used.

How do I test if a string is empty in Objective-C?

Another option is to check if it is equal to @"" with isEqualToString: like so:

if ([myString isEqualToString:@""]) {
    NSLog(@"myString IS empty!");
} else {
    NSLog(@"myString IS NOT empty, it is: %@", myString);
}

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

I got it working by selecting the original layout I had in the W / H selection. Storyboard is working as expected and the error is gone.

Be also sure that you are developing for iOS 8.0. Check that from the project's general settings.

This is where you should press.

Get the contents of a table row with a button click

Here is the complete code for simple example of delegate

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container">
  <h2>Striped Rows</h2>
  <p>The .table-striped class adds zebra-stripes to a table:</p>            
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>

      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>

    </tbody>
  </table>
  <script>
  $(document).ready(function(){
  $("div").delegate("table tbody tr td:nth-child(4)", "click", function(){
  var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)");
     $.each($tds, function() {
        console.log($(this).text());
        var x = $(this).text();
        alert(x);
    });
    });
});
  </script>
</div>

</body>
</html>

How to recognize vehicle license / number plate (ANPR) from an image?

EDIT: I wrote a Python script for this.

As your objective is blurring (for privacy protection), you basically need a high recall detector as a first step. Here's how to go about doing this. The included code hints use OpenCV with Python.

  1. Convert to Grayscale.
  2. Apply Gaussian Blur.

    img = cv2.imread('input.jpg',1)
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_gray = cv2.GaussianBlur(img_gray, (5,5), 0)  
    

Let the input image be the following.

enter image description here

  1. Apply Sobel Filter to detect vertical edges.
  2. Threshold the resultant image using strict threshold or OTSU's binarization.

    cv2.Sobel(image, -1, 1, 0)
    cv2.threshold() 
    
  3. Apply a Morphological Closing operation using suitable structuring element. (I used 16x4 as structuring element)

    se = cv2.getStructuringElement(cv2.MORPH_RECT,(16,4))
    cv2.morphologyEx(image, cv2.MORPH_CLOSE, se)  
    

Resultant Image after Step 5.

enter image description here

  1. Find external contours of this image.

    cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 
    
  2. For each contour, find the minAreaRect() bounding it.

  3. Select rectangles based on aspect ratio, minimum and maximum area, and angle with the horizontal. (I used 2.2 <= Aspect Ratio <= 8, 500 <= Area <=15000, and angle <= 45 degrees)

All minAreaRect()s are shown in orange and the one which satisfies our criteria is in green.

enter image description here

  1. There may be false positives after this step, to filter it, use edge density. Edge Density is defined as the number of white pixels/total number of pixels in a rectangle. Set a threshold for edge density. (I used 0.5)

enter image description here

  1. Blur the detected regions.

enter image description here

You can apply other filters you deem suitable to increase recall and precision. The detection can also be trained using HOG+SVM to increase precision.

SVN check out linux

There should be svn utility on you box, if installed:

$ svn checkout http://example.com/svn/somerepo somerepo

This will check out a working copy from a specified repository to a directory somerepo on our file system.

You may want to print commands, supported by this utility:

$ svn help

uname -a output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm or the following command:

$ sudo yum install subversion

How to catch and print the full exception traceback without halting/exiting the program?

traceback.format_exception

If you only have the exception object, you can get the traceback as a string from any point of the code in Python 3 with:

import traceback

''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))

Full example:

#!/usr/bin/env python3

import traceback

def f():
    g()

def g():
    raise Exception('asdf')

try:
    g()
except Exception as e:
    exc = e

tb_str = ''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))
print(tb_str)

Output:

Traceback (most recent call last):
  File "./main.py", line 12, in <module>
    g()
  File "./main.py", line 9, in g
    raise Exception('asdf')
Exception: asdf

Documentation: https://docs.python.org/3.7/library/traceback.html#traceback.format_exception

See also: Extract traceback info from an exception object

Tested in Python 3.7.3.

How to iterate through a table rows and get the cell values using jQuery

Hello every one thanks for the help below is the working code for my question

$("#TableView tr.item").each(function() { 
    var quantity1=$(this).find("input.name").val(); 
    var quantity2=$(this).find("input.id").val(); 
});

How do I ignore files in a directory in Git?

The first one. Those file paths are relative from where your .gitignore file is.