Programs & Examples On #Tail call

Tail call is a subroutine call that happens inside another procedure as its final action; it may produce a return value which is then immediately returned by the calling procedure.

What is tail call optimization?

TCO (Tail Call Optimization) is the process by which a smart compiler can make a call to a function and take no additional stack space. The only situation in which this happens is if the last instruction executed in a function f is a call to a function g (Note: g can be f). The key here is that f no longer needs stack space - it simply calls g and then returns whatever g would return. In this case the optimization can be made that g just runs and returns whatever value it would have to the thing that called f.

This optimization can make recursive calls take constant stack space, rather than explode.

Example: this factorial function is not TCOptimizable:

def fact(n):
    if n == 0:
        return 1
    return n * fact(n-1)

This function does things besides call another function in its return statement.

This below function is TCOptimizable:

def fact_h(n, acc):
    if n == 0:
        return acc
    return fact_h(n-1, acc*n)

def fact(n):
    return fact_h(n, 1)

This is because the last thing to happen in any of these functions is to call another function.

What processes are using which ports on unix?

netstat -pln

EDIT: linux only, on other UNIXes netstat may not support all these options.

Importing CSV with line breaks in Excel 2007

Overview

Almost 10 years after the original post, Excel hasn't improved in importing CSV files. However, I found that it is much better in importing HTML tables. So, one can use Python to convert CSV to HTML and then import the resulting HTML to Excel.

The advantages of this approach are: (a) it works reliably, (b) you don't need to send your data to a third party service (e.g. Google sheets), (c) no extra "fat" installations required (LibreOffice, Numbers etc.) for most users, (d) higher level than meddling with CR/LF characters and BOM markers, (e) no need to fiddle with locale settings.

Steps

The following steps can be run on any bash-like shell as long as Python 3 is installed. Although Python can be used to directly read CSV, csvkit is used to do an intermediate conversion to JSON. This allows us to avoid having to deal with CSV intricacies in our Python code.

First, save the following script as json2html.py. The script reads a JSON file from stdin and dumps it as an HTML table:

#!/usr/bin/env python3
import sys, json, html

if __name__ == '__main__':
    header_emitted = False
    make_th = lambda s: "<th>%s</th>" % (html.escape(s if s else ""))
    make_td = lambda s: "<td>%s</td>" % (html.escape(s if s else ""))
    make_tr = lambda l, make_cell: "<tr>%s</tr>" % ( "".join([make_cell(v) for v in l]) )
    print("<html><body>\n<table>")
    for line in json.load(sys.stdin):
        lk, lv = zip(*line.items())
        if not header_emitted:
            print(make_tr(lk, make_th))
            header_emitted = True
        print(make_tr(lv, make_td))
    print("</table\n</body></html>")

Then, install csvkit in a virtual environment and use csvjson to feed the input file to our script. It is a good idea to disable cell type guessing with the -I argument:

$ virtualenv -p python3 pyenv
$ . ./pyenv/bin/activate
$ pip install csvkit
$ csvjson -I input.csv | python3 json2html.py > output.html

Now output.html can be imported in Excel. Line breaks in cells will have been preserved.

Optionally, you may want to cleanup your Python virtual environment:

$ deactivate
$ rm -rf pyenv

How do I use .woff fonts for my website?

After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts subdirectory.

In CSS code:

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font.woff") format('woff');
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-bold.woff") format('woff');
    font-weight: bold;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-boldoblique.woff") format('woff');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-oblique.woff") format('woff');
    font-style: italic;
}

After having that definitions, you can just write, for example,

In HTML code:

<div class="mydiv">
    <b>this will be written with awesome-font-bold.woff</b>
    <br/>
    <b><i>this will be written with awesome-font-boldoblique.woff</i></b>
    <br/>
    <i>this will be written with awesome-font-oblique.woff</i>
    <br/>
    this will be written with awesome-font.woff
</div>

In CSS code:

.mydiv {
    font-family: myfont
}

The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.

size of NumPy array

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape

Android ImageView's onClickListener does not work

Most possible cause of such issues can be some invisible view is on the top of view being clicked, which prevents the click event to trigger. So recheck your xml layout properly before searching anything vigorously online.

PS :- In my case, a recyclerView was totally covering the layout and hence clicking on imageView was restricted.

Ajax using https on an http page

Add the Access-Control-Allow-Origin header from the server

Access-Control-Allow-Origin: https://www.mysite.com

http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing

Select all where [first letter starts with B]

Following your comment posted to ceejayoz's answer, two things are messed up a litte:

  1. $first is not an array, it's a string. Replace $first = $first[0] . "%" by $first .= "%". Just for simplicity. (PHP string operators)

  2. The string being compared with LIKE operator should be quoted. Replace LIKE ".$first."") by LIKE '".$first."'"). (MySQL String Comparison Functions)

C# compiler error: "not all code paths return a value"

Have a look at this one. It is the Ternary operator in C#.

bool BooleanValue = (num % 3 != 0) ? true : false;

This is just to show the principle; you can return True or False (or even integer or string) depending on the outcome of something on the left side of the question mark. Nice operator, this.

Three alternatives together:

      public bool test1()
        {
            int num = 21;
            bool BooleanValue = (num % 3 != 0) ? true : false;
            return BooleanValue;
        }

        public bool test2()
        {
            int num = 20;
            bool test = (num % 3 != 0);
            return test;
        }

Even Shorter:

public bool test3()
{
    int num = 20;
    return (bool)(num % 3 != 0);
}

How to enable core dump in my Linux C++ program

You need to set ulimit -c. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited and check if everything is correct ulimit -a. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>.

#define macro for debug printing in C?

My favourite of the below is var_dump, which when called as:

var_dump("%d", count);

produces output like:

patch.c:150:main(): count = 0

Credit to @"Jonathan Leffler". All are C89-happy:

Code

#define DEBUG 1
#include <stdarg.h>
#include <stdio.h>
void debug_vprintf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
}

/* Call as: (DOUBLE PARENTHESES ARE MANDATORY) */
/* var_debug(("outfd = %d, somefailed = %d\n", outfd, somefailed)); */
#define var_debug(x) do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): ", \
    __FILE__,  __LINE__, __func__); debug_vprintf x; }} while (0)

/* var_dump("%s" variable_name); */
#define var_dump(fmt, var) do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): ", \
    __FILE__,  __LINE__, __func__); debug_vprintf ("%s = " fmt, #var, var); }} while (0)

#define DEBUG_HERE do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): HERE\n", \
    __FILE__,  __LINE__, __func__); }} while (0)

How to convert 2D float numpy array to 2D int numpy array?

Use the astype method.

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> x.astype(int)
array([[1, 2],
       [1, 2]])

Convert a date format in PHP

Note: Because this post's answer sometimes gets upvoted, I came back here to kindly ask people not to upvote it anymore. My answer is ancient, not technically correct, and there are several better approaches right here. I'm only keeping it here for historical purposes.

Although the documentation poorly describes the strtotime function, @rjmunro correctly addressed the issue in his comment: it's in ISO format date "YYYY-MM-DD".

Also, even though my Date_Converter function might still work, I'd like to warn that there may be imprecise statements below, so please do disregard them.

The most voted answer is actually incorrect!

The PHP strtotime manual here states that "The function expects to be given a string containing an English date format". What it actually means is that it expects an American US date format, such as "m-d-Y" or "m/d/Y".

That means that a date provided as "Y-m-d" may get misinterpreted by strtotime. You should provide the date in the expected format.

I wrote a little function to return dates in several formats. Use and modify at will. If anyone does turn that into a class, I'd be glad if that would be shared.

function Date_Converter($date, $locale = "br") {

    # Exception
    if (is_null($date))
        $date = date("m/d/Y H:i:s");

    # Let's go ahead and get a string date in case we've
    # been given a Unix Time Stamp
    if ($locale == "unix")
        $date = date("m/d/Y H:i:s", $date);

    # Separate Date from Time
    $date = explode(" ", $date);

    if ($locale == "br") {
        # Separate d/m/Y from Date
        $date[0] = explode("/", $date[0]);
        # Rearrange Date into m/d/Y
        $date[0] = $date[0][1] . "/" . $date[0][0] . "/" . $date[0][2];
    }

    # Return date in all formats
        # US
        $Return["datetime"]["us"] = implode(" ", $date);
        $Return["date"]["us"]     = $date[0];

        # Universal
        $Return["time"]           = $date[1];
        $Return["unix_datetime"]  = strtotime($Return["datetime"]["us"]);
        $Return["unix_date"]      = strtotime($Return["date"]["us"]);
        $Return["getdate"]        = getdate($Return["unix_datetime"]);

        # BR
        $Return["datetime"]["br"] = date("d/m/Y H:i:s", $Return["unix_datetime"]);
        $Return["date"]["br"]     = date("d/m/Y", $Return["unix_date"]);

    # Return
    return $Return;

} # End Function

SQL Server String or binary data would be truncated

This error is thrown when the column of a table puts constraint [ mostly length ]. . E.g. if database schema for column myColumn is CHAR(2), then when your call from any of your application to insert value, you must pass String of length two.

The error basically says it; string of length three and above is inconsistent to fit the length restriction specified by database schema. That's why SQL Server warns and throws data loss/ Truncation error.

Go to beginning of line without opening new line in VI

You can also use

:-0

This sets the cursor at the present line (blank here) at the 0 column.

Does Hibernate create tables in the database automatically

yes you can use

<property name="hbm2ddl.auto" value="create"/>

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Removing whitespace between HTML elements when using line breaks

Another solution would be to use unconventional line breaks in places of spaces. This is similar to the first couple answers, and is an alternative way of lining up elements. It also is a super-edge-optimization technique because it replaces spaces in your markup with carriage returns.

<img
src="image1.jpg"><img
src="image2.jpg"><img
src="image3.jpg"><img
src="image4.jpg">

Note that there are no spaces in any of that code. Places where spaces are normally used in HTML are replaced with carriage returns. It's less verbose than both using comments and using whitespace like Paul de Vrieze recommended.

Credit to tech.co for this approach.

Xcode Objective-C | iOS: delay function / NSTimer help?

int64_t delayInSeconds = 0.6;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
     do something to the button(s)
});

How do I tell Maven to use the latest version of a dependency?

The truth is even in 3.x it still works, surprisingly the projects builds and deploys. But the LATEST/RELEASE keyword causing problems in m2e and eclipse all over the place, ALSO projects depends on the dependency which deployed through the LATEST/RELEASE fail to recognize the version.

It will also causing problem if you are try to define the version as property, and reference it else where.

So the conclusion is use the versions-maven-plugin if you can.

Laravel 5.2 not reading env file

I had a similar issue in my config/services.php and I solved using config clear and optimize commands:

php artisan config:clear
php artisan optimize

Reading rows from a CSV file in Python

The csv module handles csv files by row. If you want to handle it by column, pandas is a good solution.

Besides, there are 2 ways to get all (or specific) columns with pure simple Python code.

1. csv.DictReader

with open('demo.csv') as file:
    data = {}
    for row in csv.DictReader(file):
        for key, value in row.items():
            if key not in data:
                data[key] = []
            data[key].append(value)

It is easy to understand.

2. csv.reader with zip

with open('demo.csv') as file:
    data = {values[0]: values[1:] for values in zip(*csv.reader(file))}

This is not very clear, but efficient.

zip(x, y, z) transpose (x, y, z), while x, y, z are lists. *csv.reader(file) make (x, y, z) for zip, with column names.

Demo Result

The content of demo.csv:

a,b,c
1,2,3
4,5,6
7,8,9

The result of 1:

>>> print(data)
{'c': ['3', '6', '9'], 'b': ['2', '5', '8'], 'a': ['1', '4', '7']}

The result of 2:

>>> print(data)
{'c': ('3', '6', '9'), 'b': ('2', '5', '8'), 'a': ('1', '4', '7')}

How to check if a line is blank using regex

The most portable regex would be ^[ \t\n]*$ to match an empty string (note that you would need to replace \t and \n with tab and newline accordingly) and [^ \n\t] to match a non-whitespace string.

Disable LESS-CSS Overwriting calc()

Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.

With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:

width: calc(100% - 200px);

Would work as expected with the strict math option enabled.

However, note that Strict Math is applied globally, not only inside calc(). That means, if you have:

font-size: 12px + 2px;

The math will no longer be processed by Less -- it will output font-size: 12px + 2px which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:

font-size: (12px + 2px);

Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.

Run PowerShell command from command prompt (no ps1 script)

Here is the only answer that managed to work for my problem, got it figured out with the help of this webpage (nice reference).

powershell -command "& {&'some-command' someParam}"

Also, here is a neat way to do multiple commands:

powershell -command "& {&'some-command' someParam}"; "& {&'some-command' -SpecificArg someParam}"

For example, this is how I ran my 2 commands:

powershell -command "& {&'Import-Module' AppLocker}"; "& {&'Set-AppLockerPolicy' -XmlPolicy myXmlFilePath.xml}"

How to write an async method with out parameter?

Here's the code of @dcastro's answer modified for C# 7.0 with named tuples and tuple deconstruction, which streamlines the notation:

public async void Method1()
{
    // Version 1, named tuples:
    // just to show how it works
    /*
    var tuple = await GetDataTaskAsync();
    int op = tuple.paramOp;
    int result = tuple.paramResult;
    */

    // Version 2, tuple deconstruction:
    // much shorter, most elegant
    (int op, int result) = await GetDataTaskAsync();
}

public async Task<(int paramOp, int paramResult)> GetDataTaskAsync()
{
    //...
    return (1, 2);
}

For details about the new named tuples, tuple literals and tuple deconstructions see: https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/

How to hide status bar in Android

This is the official documentation about hiding the Status Bar on Android 4.0 and lower and on Android 4.1 and higher

Please, take a look at it:

https://developer.android.com/training/system-ui/status.html

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

How to properly set the 100% DIV height to match document/window height?

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

How to parseInt in Angular.js

Option 1 (via controller):

angular.controller('numCtrl', function($scope, $window) {
   $scope.num = parseInt(num , 10);
}

Option 2 (via custom filter):

app.filter('num', function() {
    return function(input) {
       return parseInt(input, 10);
    }
});

{{(num1 | num) + (num2 | num)}}

Option 3 (via expression):

Declare this first in your controller:

$scope.parseInt = parseInt;

Then:

{{parseInt(num1)+parseInt(num2)}}

Option 4 (from raina77ow)

{{(num1-0) + (num2-0)}}

Turning off auto indent when pasting text into vim

If you are on a mac, macvim seems to handle it well without having to toggle paste.

brew install macvim --override-system-vim

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

I would like to propose a version, which seems to be more robust, since I ran into a lot of problems using quantile() in the breaks option cut() on my dataset. I am using the ntile function of plyr, but it also works with ecdf as input.

temp[, `:=`(quartile = .bincode(x = ntile(value, 100), breaks = seq(0,100,25), right = TRUE, include.lowest = TRUE)
            decile = .bincode(x = ntile(value, 100), breaks = seq(0,100,10), right = TRUE, include.lowest = TRUE)
)]

temp[, `:=`(quartile = .bincode(x = ecdf(value)(value), breaks = seq(0,1,0.25), right = TRUE, include.lowest = TRUE)
            decile = .bincode(x = ecdf(value)(value), breaks = seq(0,1,0.1), right = TRUE, include.lowest = TRUE)
)]

Is that correct?

How do I remove carriage returns with Ruby?

lines2 = lines.split.join("\n")

WPF User Control Parent

How about this:

DependencyObject parent = ExVisualTreeHelper.FindVisualParent<UserControl>(this);

public static class ExVisualTreeHelper
{
    /// <summary>
    /// Finds the visual parent.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sender">The sender.</param>
    /// <returns></returns>
    public static T FindVisualParent<T>(DependencyObject sender) where T : DependencyObject
    {
        if (sender == null)
        {
            return (null);
        }
        else if (VisualTreeHelper.GetParent(sender) is T)
        {
            return (VisualTreeHelper.GetParent(sender) as T);
        }
        else
        {
            DependencyObject parent = VisualTreeHelper.GetParent(sender);
            return (FindVisualParent<T>(parent));
        }
    } 
}

Chmod 777 to a folder and all contents

You can give permission to folder and all its contents using option -R i.e Recursive permissions.

But I would suggest not to give 777 permission to all folder and it's all contents. You should give specific permission to each sub-folder in www directory folders.

Ideally, give 755 permission for security reasons to the web folder.

sudo chmod -R 755 /www/store

Each number has meaning in permission. Do not give full permission.

N   Description                      ls   binary    
0   No permissions at all            ---  000
1   Only execute                     --x  001
2   Only write                       -w-  010
3   Write and execute                -wx  011
4   Only read                        r--  100
5   Read and execute                 r-x  101
6   Read and write                   rw-  110
7   Read, write, and execute         rwx  111
  • First Number 7 - Read, write, and execute for the user.
  • Second Number 5 - Read and execute for the group.
  • Third Number 5 - Read and execute for others.

If your production web folder has multiple users, then you can set permissions and user groups accordingly.

More info :

  1. Understanding File Permissions: What Does “Chmod 777" Mean?
  2. What file permissions should I set on web root?
  3. Why shouldn't /var/www have chmod 777

Show MySQL host via SQL Command

show variables where Variable_name='hostname'; 

That could help you !!

Run Button is Disabled in Android Studio

if you're importing an eclipse project to android studio, you'll also encounter the same issue as above. Double Check if grade>app has apply plugin: 'com.android.application' on the top as sometimes android studio imports it as a library.

Find the most common element in a list

I am doing this using scipy stat module and lambda:

import scipy.stats
lst = [1,2,3,4,5,6,7,5]
most_freq_val = lambda x: scipy.stats.mode(x)[0][0]
print(most_freq_val(lst))

Result:

 most_freq_val = 5

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

How to prevent page scrolling when scrolling a DIV element?

In the solution above there is a little mistake regarding Firefox. In Firefox "DOMMouseScroll" event has no e.detail property,to get this property you should write the following 'e.originalEvent.detail'.

Here is a working solution for Firefox:

$.fn.isolatedScroll = function() {
    this.on('mousewheel DOMMouseScroll', function (e) {
        var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.originalEvent.detail,
            bottomOverflow = (this.scrollTop + $(this).outerHeight() - this.scrollHeight) >= 0,
            topOverflow = this.scrollTop <= 0;

        if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
            e.preventDefault();
        }
    });
    return this;
};

How to copy file from one location to another location?

Using Stream

private static void copyFileUsingStream(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}

Using Channel

private static void copyFileUsingChannel(File source, File dest) throws IOException {
    FileChannel sourceChannel = null;
    FileChannel destChannel = null;
    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destChannel = new FileOutputStream(dest).getChannel();
        destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
       }finally{
           sourceChannel.close();
           destChannel.close();
       }
}

Using Apache Commons IO lib:

private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
    FileUtils.copyFile(source, dest);
}

Using Java SE 7 Files class:

private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}

Or try Googles Guava :

https://github.com/google/guava

docs: https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html

Compare time:

    File source = new File("/Users/sidikov/tmp/source.avi");
    File dest = new File("/Users/sidikov/tmp/dest.avi");


    //copy file conventional way using Stream
    long start = System.nanoTime();
    copyFileUsingStream(source, dest);
    System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
     
    //copy files using java.nio FileChannel
    source = new File("/Users/sidikov/tmp/sourceChannel.avi");
    dest = new File("/Users/sidikov/tmp/destChannel.avi");
    start = System.nanoTime();
    copyFileUsingChannel(source, dest);
    System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));
     
    //copy files using apache commons io
    source = new File("/Users/sidikov/tmp/sourceApache.avi");
    dest = new File("/Users/sidikov/tmp/destApache.avi");
    start = System.nanoTime();
    copyFileUsingApacheCommonsIO(source, dest);
    System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start));
     
    //using Java 7 Files class
    source = new File("/Users/sidikov/tmp/sourceJava7.avi");
    dest = new File("/Users/sidikov/tmp/destJava7.avi");
    start = System.nanoTime();
    copyFileUsingJava7Files(source, dest);
    System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));

How to get the difference between two dictionaries in Python?

Try the following snippet, using a dictionary comprehension:

value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

In the above code we find the difference of the keys and then rebuild a dict taking the corresponding values.

How to check if smtp is working from commandline (Linux)

The only thing about using telnet to test postfix, or other SMTP, is that you have to know the commands and syntax. Instead, just use swaks :)

thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 4 messages
>    1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
? q
Held 4 messages in /home/thufir/Maildir
thufir@dur:~$ 
thufir@dur:~$ swaks --to [email protected]
=== Trying dur.bounceme.net:25...
=== Connected to dur.bounceme.net.
<-  220 dur.bounceme.net ESMTP Postfix (Ubuntu)
 -> EHLO dur.bounceme.net
<-  250-dur.bounceme.net
<-  250-PIPELINING
<-  250-SIZE 10240000
<-  250-VRFY
<-  250-ETRN
<-  250-STARTTLS
<-  250-ENHANCEDSTATUSCODES
<-  250-8BITMIME
<-  250 DSN
 -> MAIL FROM:<[email protected]>
<-  250 2.1.0 Ok
 -> RCPT TO:<[email protected]>
<-  250 2.1.5 Ok
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Mon, 30 Dec 2013 14:33:17 -0800
 -> To: [email protected]
 -> From: [email protected]
 -> Subject: test Mon, 30 Dec 2013 14:33:17 -0800
 -> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 -> 
 -> This is a test mailing
 -> 
 -> .
<-  250 2.0.0 Ok: queued as 52D162C3EFF
 -> QUIT
<-  221 2.0.0 Bye
=== Connection closed with remote host.
thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 5 messages 1 new
     1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
>N   5 [email protected]                   15/581   test Mon, 30 Dec 2013 14:33:17 -0800
? 5
Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from dur.bounceme.net (localhost [127.0.0.1])
    by dur.bounceme.net (Postfix) with ESMTP id 52D162C3EFF
    for <[email protected]>; Mon, 30 Dec 2013 14:33:17 -0800 (PST)
Date: Mon, 30 Dec 2013 14:33:17 -0800
To: [email protected]
From: [email protected]
Subject: test Mon, 30 Dec 2013 14:33:17 -0800
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Message-Id: <[email protected]>

This is a test mailing

New mail has arrived.
? q
Held 5 messages in /home/thufir/Maildir
thufir@dur:~$ 

It's just one easy command.

"psql: could not connect to server: Connection refused" Error when connecting to remote database

I think you are using the machine-name instead of the ip of the host.

I got the same error when i tried with machine's name. Because, It is allowed only when both the client and host are under same network and they have the same Operating system installed.

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

Set Focus After Last Character in Text Box

You should code like this.

var num = $('#Number').val();        
$('#Number').focus().val('').val(num);    

How to open the terminal in Atom?

In current versions of Mac Catalina

  1. go to packages tab --> Settings View ---> Install Packages/Themes ---> +Install button --> add "platformio-ide-terminal"

  2. control ~ to get the terminal

Using PropertyInfo to find out the property type

Use PropertyInfo.PropertyType to get the type of the property.

public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string value = propertyInfo.GetValue(data, null);

            if value is not OK
            {
                return false;
            }
        }
    }            

    return true;
}

Iterate through pairs of items in a Python list

To do that you should do:

a =  [5, 7, 11, 4, 5]
for i in range(len(a)-1):
    print [a[i], a[i+1]]

Hashing with SHA1 Algorithm in C#

You can "compute the value for the specified byte array" using ComputeHash:

var hash = sha1.ComputeHash(temp);

If you want to analyse the result in string representation, then you will need to format the bytes using the {0:X2} format specifier.

VBScript -- Using error handling

Note that On Error Resume Next is not set globally. You can put your unsafe part of code eg into a function, which will interrupted immediately if error occurs, and call this function from sub containing precedent OERN statement.

ErrCatch()

Sub ErrCatch()
    Dim Res, CurrentStep

    On Error Resume Next

    Res = UnSafeCode(20, CurrentStep)
    MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description

End Sub

Function UnSafeCode(Arg, ErrStep)

    ErrStep = 1
    UnSafeCode = 1 / (Arg - 10)

    ErrStep = 2
    UnSafeCode = 1 / (Arg - 20)

    ErrStep = 3
    UnSafeCode = 1 / (Arg - 30)

    ErrStep = 0
End Function

What's the difference between Thread start() and Runnable run()

First example: No multiple threads. Both execute in single (existing) thread. No thread creation.

R1 r1 = new R1();
R2 r2 = new R2();

r1 and r2 are just two different objects of classes that implement the Runnable interface and thus implement the run() method. When you call r1.run() you are executing it in the current thread.

Second example: Two separate threads.

Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);

t1 and t2 are objects of the class Thread. When you call t1.start(), it starts a new thread and calls the run() method of r1 internally to execute it within that new thread.

SSIS Connection Manager Not Storing SQL Password

The designed behavior in SSIS is to prevent storing passwords in a package, because it's bad practice/not safe to do so.

Instead, either use Windows auth, so you don't store secrets in packages or config files, or, if that's really impossible in your environment (maybe you have no Windows domain, for example) then you have to use a workaround as described in http://support.microsoft.com/kb/918760 (Sam's correct, just read further in that article). The simplest answer is a config file to go with the package, but then you have to worry that the config file is stored securely so someone can't just read it and take the credentials.

How can I simulate a click to an anchor tag?

Quoted from https://developer.mozilla.org/en/DOM/element.click

The click method is intended to be used with INPUT elements of type button, checkbox, radio, reset or submit. Gecko does not implement the click method on other elements that might be expected to respond to mouse–clicks such as links (A elements), nor will it necessarily fire the click event of other elements.

Non–Gecko DOMs may behave differently.

Unfortunately it sounds like you have already discovered the best solution to your problem.

As a side note, I agree that your solution seems less than ideal, but if you encapsulate the functionality inside a method (much like JQuery would do) it is not so bad.

SqlDataAdapter vs SqlDataReader

DataReader:

  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database

On the other hand, it:

  • Only has one record in memory at a time rather than an entire result set (this can be HUGE)
  • Is about as fast as you can get for that one iteration
  • Allows you start processing results sooner (once the first record is available). For some query types this can also be a very big deal.

DataAdapter/DataSet

  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database

At the cost of:

  • Much higher memory use
  • You wait until all the data is loaded before using any of it

So really it depends on what you're doing, but I tend to prefer a DataReader until I need something that's only supported by a dataset. SqlDataReader is perfect for the common data access case of binding to a read-only grid.

For more info, see the official Microsoft documentation.

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

boardRepo.deleteByBoardId(id);

Faced the same issue. GOT javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread

I resolved it by adding @Transactional annotation above the controller/service.

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

I stumbled upon another solution, which is quite nice.

Basically, only do step 2 from the blog posted mentioned, and define a custom ObjectMapper as a Spring @Component. (Things started working when I just removed all the AnnotationMethodHandlerAdapter stuff from step 3.)

@Component
@Primary
public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        setSerializationInclusion(JsonInclude.Include.NON_NULL); 
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
    }
}

Works as long as the component is in a package scanned by Spring. (Using @Primary is not mandatory in my case, but why not make things explicit.)

For me there are two benefits compared to the other approach:

  • This is simpler; I can just extend a class from Jackson and don't need to know about highly Spring-specific stuff like Jackson2ObjectMapperBuilder.
  • I want to use the same Jackson configs for deserialising JSON in another part of my app, and this way it's very simple: new CustomObjectMapper() instead of new ObjectMapper().

Read contents of a local file into a variable in Rails

I think you should consider using IO.binread("/path/to/file") if you have a recent ruby interpreter (i.e. >= 1.9.2)

You could find IO class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html

How to draw in JPanel? (Swing/graphics Java)

When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics object outside the paint()/paintComponent()/etc. methods.

However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics() method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel's paintComponent(), you simply need to draw the BufferedImage instance unto the JPanel. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.

Elegant way to check for missing packages and install them?

You can just use the return value of require:

if(!require(somepackage)){
    install.packages("somepackage")
    library(somepackage)
}

I use library after the install because it will throw an exception if the install wasn't successful or the package can't be loaded for some other reason. You make this more robust and reuseable:

dynamic_require <- function(package){
  if(eval(parse(text=paste("require(",package,")")))) return True

  install.packages(package)
  return eval(parse(text=paste("require(",package,")")))
}

The downside to this method is that you have to pass the package name in quotes, which you don't do for the real require.

How we can bold only the name in table td tag not the value

Wrap the name in a span, give it a class and assign a style to that class:

<td><span class="names">Name text you want bold</span> rest of your text</td>

style:

.names { font-weight: bold; }

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

I got same error. Because i used v4 alpha class names like carousel-control-next When i changed with v3, problem solved.

Convert string to datetime in vb.net

You can try with ParseExact method

Sample

Dim format As String  
format = "d" 
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)

Redirect to external URI from ASP.NET MVC controller

If you're talking about ASP.NET MVC then you should have a controller method that returns the following:

return Redirect("http://www.google.com");

Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.

phonegap open link in browser

<a onclick="navigator.app.loadUrl('https://google.com/', { openExternal:true });">Link</a>

Works for me with android & PG 3.0

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

in my case, the problem got solved only by implementing serializable as below:

@Entity @Table(name = "User" , uniqueConstraints = { @UniqueConstraint(columnNames = {"nam"}) }) public class User extends GenericT implements Serializable

What is the difference between dim and set in vba

There's no reason to use set unless referring to an object reference. It's good practice to only use it in that context. For all other simple data types, just use an assignment operator. It's a good idea to dim (dimension) ALL variables however:

Examples of simple data types would be integer, long, boolean, string. These are just data types and do not have their own methods and properties.

Dim i as Integer
i = 5

Dim myWord as String
myWord = "Whatever I want"

An example of an object would be a Range, a Worksheet, or a Workbook. These have their own methods and properties.

Dim myRange as Range
Set myRange = Sheet1.Range("A1")

If you try to use the last line without Set, VB will throw an error. Now that you have an object declared you can access its properties and methods.

myString = myRange.Value

Get index of selected option with jQuery

Good way to solve this in Jquery manner

$("#dropDownMenuKategorie option:selected").index()

store and retrieve a class object in shared preference

we can use Outputstream to output our Object to internal memory. And convert to string then save in preference. For example:

    mPrefs = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor ed = mPrefs.edit();
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

    ObjectOutputStream objectOutput;
    try {
        objectOutput = new ObjectOutputStream(arrayOutputStream);
        objectOutput.writeObject(object);
        byte[] data = arrayOutputStream.toByteArray();
        objectOutput.close();
        arrayOutputStream.close();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT);
        b64.write(data);
        b64.close();
        out.close();

        ed.putString(key, new String(out.toByteArray()));

        ed.commit();
    } catch (IOException e) {
        e.printStackTrace();
    }

when we need to extract Object from Preference. Use the code as below

    byte[] bytes = mPrefs.getString(indexName, "{}").getBytes();
    if (bytes.length == 0) {
        return null;
    }
    ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
    Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT);
    ObjectInputStream in;
    in = new ObjectInputStream(base64InputStream);
    MyObject myObject = (MyObject) in.readObject();

Difference between IISRESET and IIS Stop-Start command

I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:

Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:

  • NET STOP iisadmin /y
  • NET START w3svc

There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.

KB:https://support.microsoft.com/en-ca/help/969864/using-iisreset-exe-to-restart-internet-information-services-iis-result

Simple timeout in java

Use this line of code:

Thread.sleep(1000);

It will sleep for 1 second.

With CSS, use "..." for overflowed block of multi-lines

I've found this css (scss) solution that works quite well. On webkit browsers it shows the ellipsis and on other browsers it just truncates the text. Which is fine for my intended use.

$font-size: 26px;
$line-height: 1.4;
$lines-to-show: 3;

h2 {
  display: block; /* Fallback for non-webkit */
  display: -webkit-box;
  max-width: 400px;
  height: $font-size*$line-height*$lines-to-show; /* Fallback for non-webkit */
  margin: 0 auto;
  font-size: $font-size;
  line-height: $line-height;
  -webkit-line-clamp: $lines-to-show;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

An example by the creator: http://codepen.io/martinwolf/pen/qlFdp

Formatting a number with exactly two decimals in JavaScript

The trouble with floating point values is that they are trying to represent an infinite amount of (continuous) values with a fixed amount of bits. So naturally, there must be some loss in play, and you're going to be bitten with some values.

When a computer stores 1.275 as a floating point value, it won't actually remember whether it was 1.275 or 1.27499999999999993, or even 1.27500000000000002. These values should give different results after rounding to two decimals, but they won't, since for computer they look exactly the same after storing as floating point values, and there's no way to restore the lost data. Any further calculations will only accumulate such imprecision.

So, if precision matters, you have to avoid floating point values from the start. The simplest options are to

  • use a devoted library
  • use strings for storing and passing around the values (accompanied by string operations)
  • use integers (e.g. you could be passing around the amount of hundredths of your actual value, e.g. amount in cents instead of amount in dollars)

For example, when using integers to store the number of hundredths, the function for finding the actual value is quite simple:

function descale(num, decimals) {
    var hasMinus = num < 0;
    var numString = Math.abs(num).toString();
    var precedingZeroes = '';
    for (var i = numString.length; i <= decimals; i++) {
        precedingZeroes += '0';
    }
    numString = precedingZeroes + numString;
    return (hasMinus ? '-' : '') 
        + numString.substr(0, numString.length-decimals) 
        + '.' 
        + numString.substr(numString.length-decimals);
}

alert(descale(127, 2));

With strings, you'll need rounding, but it's still manageable:

function precise_round(num, decimals) {
    var parts = num.split('.');
    var hasMinus = parts.length > 0 && parts[0].length > 0 && parts[0].charAt(0) == '-';
    var integralPart = parts.length == 0 ? '0' : (hasMinus ? parts[0].substr(1) : parts[0]);
    var decimalPart = parts.length > 1 ? parts[1] : '';
    if (decimalPart.length > decimals) {
        var roundOffNumber = decimalPart.charAt(decimals);
        decimalPart = decimalPart.substr(0, decimals);
        if ('56789'.indexOf(roundOffNumber) > -1) {
            var numbers = integralPart + decimalPart;
            var i = numbers.length;
            var trailingZeroes = '';
            var justOneAndTrailingZeroes = true;
            do {
                i--;
                var roundedNumber = '1234567890'.charAt(parseInt(numbers.charAt(i)));
                if (roundedNumber === '0') {
                    trailingZeroes += '0';
                } else {
                    numbers = numbers.substr(0, i) + roundedNumber + trailingZeroes;
                    justOneAndTrailingZeroes = false;
                    break;
                }
            } while (i > 0);
            if (justOneAndTrailingZeroes) {
                numbers = '1' + trailingZeroes;
            }
            integralPart = numbers.substr(0, numbers.length - decimals);
            decimalPart = numbers.substr(numbers.length - decimals);
        }
    } else {
        for (var i = decimalPart.length; i < decimals; i++) {
            decimalPart += '0';
        }
    }
    return (hasMinus ? '-' : '') + integralPart + (decimals > 0 ? '.' + decimalPart : '');
}

alert(precise_round('1.275', 2));
alert(precise_round('1.27499999999999993', 2));

Note that this function rounds to nearest, ties away from zero, while IEEE 754 recommends rounding to nearest, ties to even as the default behavior for floating point operations. Such modifications are left as an exercise for the reader :)

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

How do I make a Docker container start automatically on system boot?

This is what crontab is for:

@reboot sleep 10 ; docker start <container name> 2>&1 | /usr/bin/logger -t 'docker start'

Access your user crontab by crontab -e or show it with crontab -l or edit your system crontab at /etc/crontab

File Upload without Form

Sorry for being that guy but AngularJS offers a simple and elegant solution.

Here is the code I use:

_x000D_
_x000D_
ngApp.controller('ngController', ['$upload',_x000D_
function($upload) {_x000D_
_x000D_
  $scope.Upload = function($files, index) {_x000D_
    for (var i = 0; i < $files.length; i++) {_x000D_
      var file = $files[i];_x000D_
      $scope.upload = $upload.upload({_x000D_
        file: file,_x000D_
        url: '/File/Upload',_x000D_
        data: {_x000D_
          id: 1 //some data you want to send along with the file,_x000D_
          name: 'ABC' //some data you want to send along with the file,_x000D_
        },_x000D_
_x000D_
      }).progress(function(evt) {_x000D_
_x000D_
      }).success(function(data, status, headers, config) {_x000D_
          alert('Upload done');_x000D_
        }_x000D_
      })_x000D_
    .error(function(message) {_x000D_
      alert('Upload failed');_x000D_
    });_x000D_
  }_x000D_
};_x000D_
}]);
_x000D_
.Hidden {_x000D_
  display: none_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div data-ng-controller="ngController">_x000D_
  <input type="button" value="Browse" onclick="$(this).next().click();" />_x000D_
  <input type="file" ng-file-select="Upload($files, 1)" class="Hidden" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

On the server side I have an MVC controller with an action the saves the files uploaded found in the Request.Files collection and returning a JsonResult.

If you use AngularJS try this out, if you don't... sorry mate :-)

warning about too many open figures

If you intend to knowingly keep many plots in memory, but don't want to be warned about it, you can update your options prior to generating figures.

import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})

This will prevent the warning from being emitted without changing anything about the way memory is managed.

Spring MVC Controller redirect using URL parameters instead of in response

Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this

HttpServletRequest request;
request.setAttribute("param", "value")

now your parametrs will not be shown in your url header hope it works :)

Oracle SQL - select within a select (on the same table!)

I'm a bit confused by the quotes, however, below should work for you:

SELECT "Gc_Staff_Number",
       "Start_Date", x.end_date
FROM   "Employment_History" eh,
(SELECT "End_Date"
        FROM   "Employment_History"
        WHERE  "Current_Flag" != 'Y'
               AND ROWNUM = 1
               AND "Employee_Number" = eh.Employee_Number
        ORDER  BY "End_Date" ASC) x
WHERE  "Current_Flag" = 'Y'

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

MrOBrian's answer shows why your current code doesn't work, with the missing trailing ] and quotes, but here's an easier way to make it work:

onchange='mySelectHandler(this)'

And then:

function mySelectHandler(el){
     var mySelect = $(el)
     // get selected value
     alert ("selected " + mySelect.val())
  }

Or better still, remove the inline event handler altogether and bind the event handler with jQuery:

$('select[name="a[b]"]').change(function() {
    var mySelect = $(this);
    alert("selected " mySelect.val());
});

That last would need to be in a document.ready handler or in a script block that appears after the select element. If you want to run the same function for other selects simply change the selector to something that applies to all, e.g., all selects would be $('select'), or all with a particular class would be $('select.someClass').

How can I get the IP address from NIC in Python?

Alternatively, if you want to get the IP address of whichever interface is used to connect to the network without having to know its name, you can use this:

import socket
def get_ip_address():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    return s.getsockname()[0]

I know it's a little different than your question, but others may arrive here and find this one more useful. You do not have to have a route to 8.8.8.8 to use this. All it is doing is opening a socket, but not sending any data.

Angular2 RC6: '<component> is not a known element'

Another possible cause of having the same error message is a mismatch between tag name and selector name. For this case:

<header-area></header-area> tag name must exactly match 'header-area' from the component declaration:

@Component({
  selector: 'header-area',

How to get current user in asp.net core

Most of the answers show how to best handle HttpContext from the documentation, which is also what I went with.

I did want to mention that you'll want to check you project settings when debugging, the default is Enable Anonymous Authentication = true.

How to use ADB to send touch events to device using sendevent command?

You don't need to use

adb shell getevent -l

command, you just need to enable in Developer Options on the device [Show Touch data] to get X and Y.

Some more information can be found in my article here: https://mobileqablog.wordpress.com/2016/08/20/android-automatic-touchscreen-taps-adb-shell-input-touchscreen-tap/

Likelihood of collision using most significant bits of a UUID in Java

You are better off just generating a random long value, then all the bits are random. In Java 6, new Random() uses the System.nanoTime() plus a counter as a seed.

There are different levels of uniqueness.

If you need uniqueness across many machines, you could have a central database table for allocating unique ids, or even batches of unique ids.

If you just need to have uniqueness in one app you can just have a counter (or a counter which starts from the currentTimeMillis()*1000 or nanoTime() depending on your requirements)

What's the best/easiest GUI Library for Ruby?

Try shoes. Unfortunately, I have not had a chance to work with it yet, but I have an upcoming project where I plan to use it. It is cross-platform. Also the API looks very Rubyish so I would give it a try.

Can lambda functions be templated?

I'm not sure why nobody else has suggested this, but you can write a templated function that returns lambda functions. The following solved my problem, the reason I came to this page:

template <typename DATUM>
std::function<double(DATUM)> makeUnweighted() {
  return [](DATUM datum){return 1.0;};
}

Now whenever I want a function that takes a given type of argument (e.g. std::string), I just say

auto f = makeUnweighted<std::string>()

and now f("any string") returns 1.0.

That's an example of what I mean by "templated lambda function." (This particular case is used to automatically provide an inert weighting function when somebody doesn't want to weight their data, whatever their data might be.)

how to display progress while loading a url to webview in android?

You will have to over ride onPageStarted and onPageFinished callbacks

mWebView.setWebViewClient(new WebViewClient() {

        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (progressBar!= null && progressBar.isShowing()) {
                progressBar.dismiss();
            }
            progressBar = ProgressDialog.show(WebViewActivity.this, "Application Name", "Loading...");
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);

            return true;
        }

        public void onPageFinished(WebView view, String url) {
            if (progressBar.isShowing()) {
                progressBar.dismiss();
            }
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            alertDialog.setTitle("Error");
            alertDialog.setMessage(description);
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            });
            alertDialog.show();
        }
    });

How do I read a text file of about 2 GB?

EmEditor works quite well for me. It's shareware IIRC but doesn't stop working after the license expires..

WorksheetFunction.CountA - not working post upgrade to Office 2010

This code works for me:

Sub test()
    Dim myRange As Range
    Dim NumRows As Integer

    Set myRange = Range("A:A")
    NumRows = Application.WorksheetFunction.CountA(myRange)

    MsgBox NumRows
End Sub

C free(): invalid pointer

You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.

There are two main types of memory you seem to be confusing - stack memory and heap memory.

  • Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main, it sets aside some memory for your variables you've declared (p,token, and so on).

  • Heap memory lives from when you malloc it to when you free it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!

You have a few errors:

  • You're trying to free memory that's not heap memory. Don't do that.

  • You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.

For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).

EDIT: The malloc function does allocate heap memory*.

"9.9.1 The malloc and free Functions

The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."

~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011

EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.

Regex matching beginning AND end strings

If you're searching for hits within a larger text, you don't want to use ^ and $ as some other responders have said; those match the beginning and end of the text. Try this instead:

\bdbo\.\w+_fn\b

\b is a word boundary: it matches a position that is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one. This regex will find what you're looking for in any of these strings:

dbo.functionName_fn
foo dbo.functionName_fn bar
(dbo.functionName_fn)

...but not in this one:

foodbo.functionName_fnbar

\w+ matches one or more "word characters" (letters, digits, or _). If you need something more inclusive, you can try \S+ (one or more non-whitespace characters) or .+? (one or more of any characters except linefeeds, non-greedily). The non-greedy +? prevents it from accidentally matching something like dbo.func1_fn dbo.func2_fn as if it were just one hit.

How do I properly 'printf' an integer and a string in C?

Try this code my friend...

#include<stdio.h>
int main(){
   char *s1, *s2;
   char str[10];

   printf("type a string: ");
   scanf("%s", str);

   s1 = &str[0];
   s2 = &str[2];

   printf("%c\n", *s1);   //use %c instead of %s and *s1 which is the content of position 1
   printf("%c\n", *s2);   //use %c instead of %s and *s3 which is the content of position 1

   return 0;
}

Make a link in the Android browser start up my app?

I apologize for promoting myself, but I have a jQuery plugin to launch native apps from web links https://github.com/eusonlito/jquery.applink

You can use it easy:

<script>
$('a[data-applink]').applink();
</script>

<a href="https://facebook.com/me" data-applink="fb://profile">My Facebook Profile</a>

How to improve a case statement that uses two columns

You could do it this way:

-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     ELSE '"DECLINED"'
END

The reason you can do an AND here is that you are not checking the CASE of STATE, but instead you are CASING Conditions.

The key part here is that the STATE condition is a part of the WHEN.

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

From This page, the container dies after running everything correctly but crashes because all the commands ended. Either you make your services run on the foreground, or you create a keep alive script. By doing so, Kubernetes will show that your application is running. We have to note that in the Docker environment, this problem is not encountered. It is only Kubernetes that wants a running app.

Update (an example):

Here's how to avoid CrashLoopBackOff, when launching a Netshoot container:

kubectl run netshoot --image nicolaka/netshoot -- sleep infinity

How can I check if a scrollbar is visible?

I'm going to extend on this even further for those poor souls who, like me, use one of the modern js frameworks and not JQuery and have been wholly abandoned by the people of this thread :

this was written in Angular 6 but if you write React 16, Vue 2, Polymer, Ionic, React-Native, you'll know what to do to adapt it. And it's the whole component so it should be easy.

import {ElementRef, AfterViewInit} from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './app.html',
  styleUrls: ['./app.scss']
})
export class App implements AfterViewInit {
scrollAmount;

constructor(
  private fb: FormBuilder,
  private element: ElementRef 
) {}

ngAfterViewInit(){
  this.scrollAmount = this.element.nativeElement.querySelector('.elem-list');
  this.scrollAmount.addEventListener('wheel', e => { //you can put () instead of e
  // but e is usefull if you require the deltaY amount.
    if(this.scrollAmount.scrollHeight > this.scrollAmount.offsetHeight){
       // there is a scroll bar, do something!
    }else{
       // there is NO scroll bar, do something!
    }
  });
}
}

in the html there would be a div with class "elem-list" which is stylized in the css or scss to have a height and an overflow value that isn't hidden. (so auto or sroll )

I trigger this eval upon a scroll event because my end goal was to have "automatic focus scrolls" which decide whether they are scrolling the whole set of components horizontally if said components have no vertical scroll available and otherwise only scroll the innards of one of the components vertically.

but you can place the eval elsewhere to have it be triggered by something else.

the important thing to remember here, is you're never Forced back into using JQuery, there's always a way to access the same functionalities it has without using it.

Maximum number of threads in a .NET app?

Jeff Richter in CLR via C#:

"With version 2.0 of the CLR, the maximum number of worker threads default to 25 per CPU in the machine and the maximum number of I/O threads defaults to 1000. A limit of 1000 is effectively no limit at all."

Note this is based on .NET 2.0. This may have changed in .NET 3.5.

[Edit] As @Mitch pointed out, this is specific to the CLR ThreadPool. If you're creating threads directly see the @Mitch and others comments.

How to right-align form input boxes?

Try use this:

<html>
<body>
   <input type="text" style="direction: rtl;" value="1">
   <input type="text" style="direction: rtl;" value="10">
   <input type="text" style="direction: rtl;" value="100">
</body>
</html>

How can I execute Python scripts using Anaconda's version of Python?

I know this is an old post, but I recently came across with the same problem. However, adding Anaconda to PYTHONPATH wasn't working for me. What got it fixed was the following:

  1. Added Anaconda to the PYTHONPATH and remove any other distribution of Python from any paths.
  2. Opened the command prompt and started python (Here I had to verify that it was indeed running under the Anaconda dist)
  3. Ran the following lines inside anaconda

    >>> import sys
    >>> sys.path
    ['','C:\\Anaconda','C:\\Anaconda\\Scripts','C:\\Anaconda\\python27.zip','C:\\Anaconda\\DLLs','C:\\Anaconda\\lib','C:\\Anaconda\\lib\\plat-win','C:\\Anaconda\\lib\\lib-tk','C:\\Anaconda\\lib\\site-packages','C:\\Anaconda\\lib\\site-packages\\PIL','C:\\Anaconda\\lib\\site-packages\\Sphinx-1.2.3-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\win32', 'C:\\Anaconda\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda\\lib\\site-packages\\Pythonwin','C:\\Anaconda\\lib\\site-packages\\runipy-0.1.1-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\setuptools-5.8-py2.7.egg']
    
  4. Copied the displayed path

  5. Within the script that I'm trying to execute on double click, changed the path to the previously copied one.

    import sys
    sys.path =['','C:\\Anaconda','C:\\Anaconda\\Scripts','C:\\Anaconda\\python27.zip','C:\\Anaconda\\DLLs','C:\\Anaconda\\lib','C:\\Anaconda\\lib\\plat-win','C:\\Anaconda\\lib\\lib-tk','C:\\Anaconda\\lib\\site-packages','C:\\Anaconda\\lib\\site-packages\\PIL','C:\\Anaconda\\lib\\site-packages\\Sphinx-1.2.3-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\win32', 'C:\\Anaconda\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda\\lib\\site-packages\\Pythonwin','C:\\Anaconda\\lib\\site-packages\\runipy-0.1.1-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\setuptools-5.8-py2.7.egg']
    
  6. Changed the default application for the script to 'python'

After doing this, my scripts are working on double click.

how does Array.prototype.slice.call() work?

Array.prototype.slice.call(arguments) is the old-fashioned way to convert an arguments into an array.

In ECMAScript 2015, you can use Array.from or the spread operator:

let args = Array.from(arguments);

let args = [...arguments];

Difference between hamiltonian path and euler path

Eulerian path must visit each edge exactly once, while Hamiltonian path must visit each vertex exactly once.

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

How do I get the key at a specific index from a Dictionary in Swift?

Swift 3 : Array() can be useful to do this .

Get Key :

let index = 5 // Int Value
Array(myDict)[index].key

Get Value :

Array(myDict)[index].value

Cannot find Microsoft.Office.Interop Visual Studio

If you're using Visual Studio 2015 and you're encountering this problem, you can install MS Office Developer Tools for VS2015 here.

for loop in Python

Here are some example to iterate over integer range and string:

#(initial,final but not included,gap)
for i in range(1,10,2): 
  print(i); 
1,3,5,7,9

# (initial, final but not included)  
# note: 4 not included
for i in range (1,4): 
   print(i);
1,2,3 

#note: 5 not included
for i in range (5):
  print (i);
0,1,2,3,4 

# you can also iterate over strings
myList = ["ml","ai","dl"];  

for i in myList:
  print(i);
output:  ml,ai,dl

Meaning of "487 Request Terminated"

The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.

15.1.2 UAS Behavior==> BYE Handling in RFC 3261

The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.

How to create an empty DataFrame with a specified schema?

This is helpful for testing purposes.

Seq.empty[String].toDF()

How can I use jQuery to move a div across the screen

You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin.

Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence.

To read up on this, check out this thread (from my very first Stackoverflow post no less)!

Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate

Is there a performance difference between i++ and ++i in C?

Please don't let the question of "which one is faster" be the deciding factor of which to use. Chances are you're never going to care that much, and besides, programmer reading time is far more expensive than machine time.

Use whichever makes most sense to the human reading the code.

How to select <td> of the <table> with javascript?

var t = document.getElementById("table"),
    d = t.getElementsByTagName("tr"),
    r = d.getElementsByTagName("td");

needs to be:

var t = document.getElementById("table"),
    tableRows = t.getElementsByTagName("tr"),
    r = [], i, len, tds, j, jlen;

for ( i =0, len = tableRows.length; i<len; i++) {
    tds = tableRows[i].getElementsByTagName('td');
    for( j = 0, jlen = tds.length; j < jlen; j++) {
        r.push(tds[j]);
    }
}

Because getElementsByTagName returns a NodeList an Array-like structure. So you need to loop through the return nodes and then populate you r like above.

Read XML file into XmlDocument

Use XmlDocument.Load() method to load XML from your file. Then use XmlDocument.InnerXml property to get XML string.

XmlDocument doc = new XmlDocument();
doc.Load("path to your file");
string xmlcontents = doc.InnerXml;

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

SET FOREIGN_KEY_CHECKS = 0; 

truncate table "yourTableName";

SET FOREIGN_KEY_CHECKS = 1;

How to round the corners of a button

UIButton* closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 50, 90, 35)];
//Customise this button as you wish then
closeBtn.layer.cornerRadius = 10;
closeBtn.layer.masksToBounds = YES;//Important

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Identifying Exception Type in a handler Catch Block

try
{
}
catch (Exception err)
{
    if (err is Web2PDFException)
        DoWhatever();
}

but there is probably a better way of doing whatever it is you want.

How to fix nginx throws 400 bad request headers on any header testing tools?

When nginx returns 400(bad request) it will log the reason into error log, at "info" level and take a look into error log when testing.

Finding the length of an integer in C

I think I got the most efficient way to find the length of an integer its a very simple and elegant way here it is:

int PEMath::LengthOfNum(int Num)
{
int count = 1;  //count starts at one because its the minumum amount of digits posible
if (Num < 0)
{
    Num *= (-1);
}

for(int i = 10; i <= Num; i*=10)
{
     count++;
}      
return count;
                // this loop will loop until the number "i" is bigger then "Num"
                // if "i" is less then "Num" multiply "i" by 10 and increase count
                // when the loop ends the number of count is the length of "Num".
}

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.

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

This is how did it works like a charm.

CSS

#loader {
position:fixed;
left:1px;
top:1px;
width: 100%;
height: 100%;
z-index: 9999;

background: url('../images/ajax-loader100X100.gif') 50% 50% no-repeat rgb(249,249,249);
}  

in _layout file inside body tag but outside the container div. Every time page loads it shows loading. Once page is loaded JS fadeout(second)


<div id="loader">
</div>

JS at the bottom of _layout file


<script type="text/javascript">
// With the element initially shown, we can hide it slowly:
 $("#loader").fadeOut(1000);
</script>  

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Your cells object is not fully qualified. You need to add a DOT before the cells object. For example

With Worksheets("Cable Cards")
    .Range(.Cells(RangeStartRow, RangeStartColumn), _
           .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

Similarly, fully qualify all your Cells object.

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

jQuery $(".class").click(); - multiple elements, click event once

Hi sorry for bump this post just face this problem and i would like to show my case.

My code look like this.

<button onClick="product.delete('1')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('2')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('3')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('4')" class="btn btn-danger">Delete</button>

Javascript code

<script>
 var product = {
     //  Define your function
     'add':(product_id)=>{
          //  Do some thing here
     },

     'delete':(product_id)=>{
         //  Do some thig here
     }
 }
</script>

CSS : center form in page horizontally and vertically

How about using a grid? it's 2019 and support is reasonable

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: grid;_x000D_
  background-color: bisque;_x000D_
  height: 100vh;_x000D_
  place-items: center;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<div class="content">_x000D_
  <form action="#" method="POST">_x000D_
    <fieldset>_x000D_
      <legend>Information:</legend>_x000D_
      <label for="name">Name:</label>_x000D_
      <input type="text" id="name" name="user_name">_x000D_
    </fieldset>_x000D_
    <button type="button" formmethod="POST" formaction="#">Submit</button>_x000D_
  </form>_x000D_
 </div>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

How to get the correct range to set the value to a cell?

Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')

Explanation :

Setting value in a cell in spreadsheet to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in sheet which is open currently and to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)

SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)

SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);

These are constants, you must define them yourself

SHEET_ID

SHEET_NAME

POSITION

VALUE

RANGE

By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.

How to bring a window to the front?

A possible solution is:

java.awt.EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        myFrame.toFront();
        myFrame.repaint();
    }
});

Detect key input in Python

You could make a little Tkinter app:

import Tkinter as tk

def onKeyPress(event):
    text.insert('end', 'You pressed %s\n' % (event.char, ))

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()

Convert MFC CString to integer

CString s="143";
int x=atoi(s);

or

CString s=_T("143");
int x=_toti(s);

atoi will work, if you want to convert CString to int.

How do I use TensorFlow GPU?

Follow this tutorial Tensorflow GPU I did it and it works perfect.

Attention! - install version 9.0! newer version is not supported by Tensorflow-gpu

Steps:

  1. Uninstall your old tensorflow
  2. Install tensorflow-gpu pip install tensorflow-gpu
  3. Install Nvidia Graphics Card & Drivers (you probably already have)
  4. Download & Install CUDA
  5. Download & Install cuDNN
  6. Verify by simple program

from tensorflow.python.client import device_lib print(device_lib.list_local_devices())

Jquery submit form

Try this :

$('#form1').submit();

or

document.form1.submit();

Removing array item by value

You can use array_splice function for this operation Ref : array_splice

array_splice($array, array_search(58, $array ), 1);

What are the differences between C, C# and C++ in terms of real-world applications?

C is the bare-bones, simple, clean language that makes you do everything yourself. It doesn't hold your hand, it doesn't stop you from shooting yourself in the foot. But it has everything you need to do what you want.

C++ is C with classes added, and then a whole bunch of other things, and then some more stuff. It doesn't hold your hand, but it'll let you hold your own hand, with add-on GC, or RAII and smart-pointers. If there's something you want to accomplish, chances are there's a way to abuse the template system to give you a relatively easy syntax for it. (moreso with C++0x). This complexity also gives you the power to accidentally create a dozen instances of yourself and shoot them all in the foot.

C# is Microsoft's stab at improving on C++ and Java. Tons of syntactical features, but no where near the complexity of C++. It runs in a full managed environment, so memory management is done for you. It does let you "get dirty" and use unsafe code if you need to, but it's not the default, and you have to do some work to shoot yourself.

Is generator.next() visible in Python 3?

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.

Can a CSS class inherit one or more other classes?

In Css file:

p.Title 
{
  font-family: Arial;
  font-size: 16px;
}

p.SubTitle p.Title
{
   font-size: 12px;
}

How to export data as CSV format from SQL Server using sqlcmd?

sqlcmd -S myServer -d myDB -E -o "MyData.txt" ^
    -Q "select bar from foo" ^
    -W -w 999 -s","

The last line contains CSV-specific options.

  • -W   remove trailing spaces from each individual field
  • -s","   sets the column seperator to the comma (,)
  • -w 999   sets the row width to 999 chars

scottm's answer is very close to what I use, but I find the -W to be a really nice addition: I needn't trim whitespace when I consume the CSV elsewhere.

Also see the MSDN sqlcmd reference. It puts the /? option's output to shame.

Java TreeMap Comparator

The comparator should be only for the key, not for the whole entry. It sorts the entries based on the keys.

You should change it to something as follows

SortedMap<String, Double> myMap = 
    new TreeMap<String, Double>(new Comparator<String>()
    {
        public int compare(String o1, String o2)
        {
            return o1.compareTo(o2);
        } 
});

Update

You can do something as follows (create a list of entries in the map and sort the list base on value, but note this not going to sort the map itself) -

List<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(myMap.entrySet());
    Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() {
        @Override
        public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    });

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

As this post gets a bit of popularity I edited it a bit. Spring Boot 2.x.x changed default JDBC connection pool from Tomcat to faster and better HikariCP. Here comes incompatibility, because HikariCP uses different property of jdbc url. There are two ways how to handle it:

OPTION ONE

There is very good explanation and workaround in spring docs:

Also, if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari has no url property (but does have a jdbcUrl property). In that case, you must rewrite your configuration as follows:

app.datasource.jdbc-url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass

OPTION TWO

There is also how-to in the docs how to get it working from "both worlds". It would look like below. ConfigurationProperties bean would do "conversion" for jdbcUrl from app.datasource.url

@Configuration
public class DatabaseConfig {
    @Bean
    @ConfigurationProperties("app.datasource")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("app.datasource")
    public HikariDataSource dataSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
                .build();
    }
}

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

For the equivalent of NVL() and ISNULL() use:

IFNULL(column, altValue)

column : The column you are evaluating.

altValue : The value you want to return if 'column' is null.

Example:

SELECT IFNULL(middle_name, 'N/A') FROM person;

*Note: The COALESCE() function works the same as it does for other databases.

Sources:

How to view the contents of an Android APK file?

There is a online decompiler for android apks

http://www.decompileandroid.com/

Upload apk from local machine

Wait some moments

download source code in zip format.

Unzip it, you can view all resources correctly but all java files are not correctly decompiled.

For full detail visit this answer

How do I use Apache tomcat 7 built in Host Manager gui?

Host Manager is a web application inside of Tomcat that creates/removes Virtual Hosts within Tomcat.

A Virtual Host allows you to define multiple hostnames on a single server, so you can use the same server to handles requests to, for example, ren.myserver.com and stimpy.myserver.com.

Unfortunately documentation on the GUI side of the Host Manager doesn't appear to exist, but documentation on configuring the virtual hosts manually in context.xml is here:

http://tomcat.apache.org/tomcat-7.0-doc/virtual-hosting-howto.html.

The full explanation of the Host parameters you can find here:

http://tomcat.apache.org/tomcat-7.0-doc/config/host.html.

Adding a virtual host

Once you have access to the host-manager (see other answers on setting up the permissions, the GUI will let you add a (temporary - see edit at the end of this post) virtual host.

Tomcat Host Manager - Add Virtual Host Panel

At a minimum you need the Name and App Base fields defined. Tomcat will then create the following directories:

{CATALINA_HOME}\conf\Catalina\{Name}
{CATALINA_HOME}\{App Base}
  • App Base will be where web applications will be deployed to the virtual host. Can be relative or absolute.
  • Name is usually the fully-qualified domain name (e.g. ren.myserver.com)
  • Alias can be used to extend the Name also where two addresses should resolve to the same host (e.g. www.ren.myserver.com). Note that this needs to be reflected in DNS records.

The checkboxes are as follows:

  • Auto Deploy: Automatically redeploy applications placed into App Base. Dangerous for Production environments!
  • Deploy On Startup: Automatically boot up applications under App Base when Tomcat starts
  • Deploy XML: Determines whether to parse the application's /META-INF/context.xml
  • Unpack WARs: Unpack WAR files placed or uploaded to the App Base, as opposed to running them directly from the WAR.
  • Tomcat 8 Copy XML: Copy an application's META-INF/context.xml to the App Base/XML Base on deployment, and use that exclusively, regardless of whether the application is updated. Irrelevant if Deploy XML is false.
  • Manager App: Add the manager application to the Virtual Host (Useful for controlling the applications you might have underneath ren.myserver.com)

Update: After playing around with this same process on Tomcat8, the behaviour I'm seeing is that adding a virtual host via the GUI isn't persistent - it doesn't get written to server.xml, even on shutdown. Therefore (unless I'm doing something terribly wrong), you can create it in the GUI, but you'll need to edit server.xml anyway, as per the first link above, to make it stick.

How to redirect to the same page in PHP

header('Location: '.$_SERVER['PHP_SELF']);  

will also work

Cannot checkout, file is unmerged

i resolved by doing below 2 easy steps :

step 1: git reset Head step 2: git add .

Count number of occurrences by month

For anyone finding this post through Google (as I did) here's the correct formula for cell F5 in the above example:

=SUMPRODUCT((MONTH(Sheet1!$A$1:$A$50)=MONTH(DATEVALUE(E5&" 1")))*(Sheet1!$A$1:$A$50<>""))

Formula assumes a list of dates in Sheet1!A1:A50 and a month name or abbr ("April" or "Apr") in cell E5.

How to save an HTML5 Canvas as an image on a server?

If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decocedData = base64_decode($encodedData);
?>

http://php.net/manual/ro/function.base64-decode.php

jquery background-color change on focus and blur

Even easier, just CSS can resolve the problem:

input[type="text"], input[type="password"], textarea, select { 
    width: 200px;
    border: 1px solid;
    border-color: #C0C0C0 #E4E4E4 #E4E4E4 #C0C0C0;
    background: #FFF;
    padding: 8px 5px;
    font: 16px Arial, Tahoma, Helvetica, sans-serif;
    -moz-box-shadow: 0 0 5px #C0C0C0;
    -moz-border-radius: 5px;
    -webkit-box-shadow: 0 0 5px #C0C0C0;
    -webkit-border-radius: 5px;
    box-shadow: 0 0 5px #C0C0C0;
    border-radius: 5px;
}
input[type="text"]:focus, input[type="password"]:focus, textarea:focus, select:focus { 
    border-color: #B6D5F7 #B6D5F7 #B6D5F7 #B6D5F7;
    outline: none;
    -moz-box-shadow: 0 0 10px #B6D5F7;
    -webkit-box-shadow: 0 0 10px #B6D5F7;
    box-shadow: 0 0 10px #B6D5F7;
}

How to resolve the error on 'react-native start'

I just got a similar error for the first time today. It appears in \node_modules\metro-config\src\defaults\blacklist.js, there is an invalid regular expression that needed changed. I changed the first expression under sharedBlacklist from:

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

to:

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

ERROR 1044 (42000): Access denied for 'root' With All Privileges

Try to comment string "sql-mode=..." in file my.cnf and than restart mysql.

How to keep an iPhone app running on background fully operational

May be the link will Help bcz u might have to implement the code in Appdelegate in app run in background method .. Also consult the developer.apple.com site for application class Here is link for runing app in background

How to check size of a file using Bash?

I would use du's --threshold for this. Not sure if this option is available in all versions of du but it is implemented in GNU's version.

Quoting from du(1)'s manual:

-t, --threshold=SIZE
       exclude entries smaller than SIZE if positive, or entries greater
       than SIZE if negative

Here's my solution, using du --threshold= for OP's use case:

THRESHOLD=90k
if [[ -z "$(du --threshold=${THRESHOLD} file.txt)" ]]; then
    mail -s "file.txt size is below ${THRESHOLD}, please fix. " [email protected] < /dev/null
    mv -f /root/tmp/file.txt /var/www/file.txt
fi

The advantage of that, is that du can accept an argument to that option in a known format - either human as in 10K, 10MiB or what ever you feel comfortable with - you don't need to manually convert between formats / units since du handles that.

For reference, here's the explanation on this SIZE argument from the man page:

The SIZE argument is an integer and optional unit (example: 10K is 
10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers
of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on.

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

You can use Database Engine Tuning Advisor.

This tool is for improving the query performances by examining the way queries are processed and recommended enhancements by specific indexes.

How to use the Database Engine Tuning Advisor?

1- Copy the select statement that you need to speed up into the new query.

2- Parse (Ctrl+F5).

3- Press The Icon of the (Database Engine Tuning Advisor).

Show loading image while $.ajax is performed

HTML Code :

<div class="ajax-loader">
  <img src="{{ url('guest/images/ajax-loader.gif') }}" class="img-responsive" />
</div>

CSS Code:

.ajax-loader {
  visibility: hidden;
  background-color: rgba(255,255,255,0.7);
  position: absolute;
  z-index: +100 !important;
  width: 100%;
  height:100%;
}

.ajax-loader img {
  position: relative;
  top:50%;
  left:50%;
}

JQUERY Code:

$.ajax({
  type:'POST',
  beforeSend: function(){
    $('.ajax-loader').css("visibility", "visible");
  },
  url:'/quantityPlus',
  data: {
   'productId':p1,
   'quantity':p2,
   'productPrice':p3},
   success:function(data){
     $('#'+p1+'value').text(data.newProductQuantity);
     $('#'+p1+'amount').text("? "+data.productAmount);
     $('#totalUnits').text(data.newNoOfUnits);
     $('#totalAmount').text("? "+data.newTotalAmount);
  },
  complete: function(){
    $('.ajax-loader').css("visibility", "hidden");
  }
});

}

Remove characters after specific character in string, then remove substring?

For string manipulation, if you just want to kill everything after the ?, you can do this

string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.IndexOf("?");
if (index > 0)
   input = input.Substring(0, index);

Edit: If everything after the last slash, do something like

string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.LastIndexOf("/");
if (index > 0)
    input = input.Substring(0, index); // or index + 1 to keep slash

Alternately, since you're working with a URL, you can do something with it like this code

System.Uri uri = new Uri("http://www.somesite.com/what/test.aspx?hello=1");
string fixedUri = uri.AbsoluteUri.Replace(uri.Query, string.Empty);

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

You can enable NuGet packages and update you dlls. so that it work. or you can update the package manually by going through the package manager in your vs if u know which version you require for your solution.

Use a LIKE statement on SQL Server XML Datatype

This is what I am going to use based on marc_s answer:

SELECT 
SUBSTRING(DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)'),PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')) - 20,999)

FROM WEBPAGECONTENT 
WHERE COALESCE(PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')),0) > 0

Return a substring on the search where the search criteria exists

pip install access denied on Windows

In my case, it didn't even work with python -m pip install

What I have done is, from a cmd as administrator:

PsExec.exe -i -s -d cmd.exe

In order to spawn a SYSTEM cmd, then pip install mitmproxy

;)

Characters allowed in GET parameter

There are reserved characters, that have a reserved meanings, those are delimiters — :/?#[]@ — and subdelimiters — !$&'()*+,;=

There is also a set of characters called unreserved characters — alphanumerics and -._~ — which are not to be encoded.

That means, that anything that doesn't belong to unreserved characters set is supposed to be %-encoded, when they do not have special meaning (e.g. when passed as a part of GET parameter).

See also RFC3986: Uniform Resource Identifier (URI): Generic Syntax

Programmatically Check an Item in Checkboxlist where text is equal to what I want

I tried adding dynamically created ListItem and assigning the selected value.

foreach(var item in yourListFromDB)
{
 ListItem listItem = new ListItem();
 listItem.Text = item.name;
 listItem.Value = Convert.ToString(item.value);
 listItem.Selected=item.isSelected;                 
  checkedListBox1.Items.Add(listItem);
}
checkedListBox1.DataBind();

avoid using binding the DataSource as it will not bind the checked/unchecked from DB.

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

Bash Shell Script - Check for a flag and grab its value

Try shFlags -- Advanced command-line flag library for Unix shell scripts.

http://code.google.com/p/shflags/

It is very good and very flexible.

FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag.

DEFINE_string: takes any input, and intreprets it as a string.

DEFINE_boolean: typically does not take any argument: say --myflag to set FLAGS_myflag to true, or --nomyflag to set FLAGS_myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=0 or --myflag=false or --myflag=f or --myflag=1 Passing an option has the same affect as passing the option once.

DEFINE_float: takes an input and intreprets it as a floating point number. As shell does not support floats per-se, the input is merely validated as being a valid floating point value.

DEFINE_integer: takes an input and intreprets it as an integer.

SPECIAL FLAGS: There are a few flags that have special meaning: --help (or -?) prints a list of all the flags in a human-readable fashion --flagfile=foo read flags from foo. (not implemented yet) -- as in getopt(), terminates flag-processing

EXAMPLE USAGE:

-- begin hello.sh --
 ! /bin/sh
. ./shflags
DEFINE_string name 'world' "somebody's name" n
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"
echo "Hello, ${FLAGS_name}."
-- end hello.sh --

$ ./hello.sh -n Kate
Hello, Kate.

Note: I took this text from shflags documentation

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Try:

cl /v

Actually, any time I give cl an argument, it prints out the version number on the first line.

You could just feed it a garbage argument and then parse the first line of the output, which contains the verison number.

How to sort a list/tuple of lists/tuples by the element at a given index?

sorted_by_second = sorted(data, key=lambda tup: tup[1])

or:

data.sort(key=lambda tup: tup[1])  # sorts in place

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

Loop through JSON in EJS

in my case, datas is an objects of Array for more information please Click Here

<% for(let [index,data] of datas.entries() || []){  %>
 Index : <%=index%>
 Data : <%=data%>
<%} %>

Read file line by line in PowerShell

I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.

[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
    $line = $sr.ReadLine()
}
$sr.Close() 

String comparison in bash. [[: not found

As @Ansgar mentioned, [[ is a bashism, ie built into Bash and not available for other shells. If you want your script to be portable, use [. Comparisons will also need a different syntax: change == to =.

Setting button text via javascript

Set the text of the button by setting the innerHTML

var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.innerHTML = 'test value';

var wrapper = document.getElementById('divWrapper');
wrapper.appendChild(b);

http://jsfiddle.net/jUVpE/

Remove all occurrences of a value from a list?

What's wrong with:

Motor=['1','2','2']
For i in Motor:
       If i  != '2':
       Print(i)
Print(motor)

Using anaconda

Release generating .pdb files, why?

Also, you can utilize crash dumps to debug your software. The customer sends it to you and then you can use it to identify the exact version of your source - and Visual Studio will even pull the right set of debugging symbols (and source if you're set up correctly) using the crash dump. See Microsoft's documentation on Symbol Stores.

Convert iterator to pointer?

The direct answer to your question is yes. If foo is a vector, you can do this: &foo[1].

This only works for vectors however, because the standard says that vectors implement storage by using contigious memory.

But you still can (and probably should) pass iterators instead of raw pointers because it is more expressive. Passing iterators does not make a copy of the vector.

Getting the Facebook like/share count for a given URL

As of August 8th, 2016, FQLs are deprecated.


Update 10/2017 (v2.10):

Here's a non-deprecated way to get a given URL's like and share count (no access token required):

https://graph.facebook.com/?fields=og_object{likes.summary(total_count).limit(0)},share&id=https://www.stackoverflow.com


Result:

{
   "og_object": {
      "likes": {
         "data": [

         ],
         "summary": {
            "total_count": 83
         }
      },
      "id": "10151023731873397"
   },
   "share": {
      "comment_count": 0,
      "share_count": 2915
   },
   "id": "https://www.stackoverflow.com"
}

JQuery Example:

$.get('https://graph.facebook.com/'
    + '?fields=og_object{likes.summary(total_count).limit(0)},share&id='
    + url-goes-here,
    function (data) {
        if (data) {
            var like_count = data.og_object.likes.summary.total_count;
            var share_count = data.share.share_count;
        }
    });

Reference:

https://developers.facebook.com/docs/graph-api/reference/url

Linux Script to check if process is running and act on the result

The 'pidof' command will not display pids of shell/perl/python scripts. So to find the process id’s of my Perl script I had to use the -x option i.e. 'pidof -x perlscriptname'

What are callee and caller saved registers?

Callee vs caller saved is a convention for who is responsible for saving and restoring the value in a register across a call. ALL registers are "global" in that any code anywhere can see (or modify) a register and those modifications will be seen by any later code anywhere. The point of register saving conventions is that code is not supposed to modify certain registers, as other code assumes that the value is not modified.

In your example code, NONE of the registers are callee save, as it makes no attempt to save or restore the register values. However, it would seem to not be an entire procedure, as it contains a branch to an undefined label (l$loop). So it might be a fragment of code from the middle of a procedure that treats some registers as callee save; you're just missing the save/restore instructions.

Create a dropdown component

Hope this will help to someone. Works fine in Angular 6 with reactive forms. Can operate by keyboard too.

dropdown.component.html

<div class="dropdown-wrapper {{className}} {{isFocused ? 'focus':''}}" [ngClass]="{'is-open':isOpen, 'disabled':isReadOnly}" *ngIf="options" (contextmenu)="$event.stopPropagation();">
  <div class="box" (click)="toggle($event)">
    <ng-container>
      <div class="dropdown-selected" *ngIf="isSelectedValue" l10nTranslate><span>{{options[selected]}}</span></div>
      <div class="dropdown-selected" *ngIf="!isSelectedValue" l10nTranslate><span>{{placeholder}}</span></div>
    </ng-container>
  </div>

  <ul class="dropdown-options" *ngIf="options">
    <li *ngIf="placeholder" (click)="$event.stopPropagation()">{{placeholder}}</li>
    <ng-container>
      <li id="li{{i}}"
        *ngFor="let option of options; let i = index"
        [class.active]="selected === i"
        (click)="optionSelect(option, i, $event)"
        l10nTranslate
      >
        {{option}}
      </li>
    </ng-container>

  </ul>
</div>

dropdown.component.scss

@import "../../../assets/scss/variables";

// DROPDOWN STYLES
.dropdown-wrapper {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    border: 1px solid #DDDDDD;
    border-radius: 3px;
    cursor: pointer;
    position: relative;
    &.focus{
        border: 1px solid #a8a8a8;
    }
    .box {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        width: 100%;
    } 

    // SELECTED
    .dropdown-selected {
        height: 30px;
        position: relative;
        padding: 10px 30px 10px 10px;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-align: center;
            -ms-flex-align: center;
                align-items: center;
        width: 100%;
        font-size: 12px;
        color: #666666;
        overflow: hidden;
        background-color: #fff;
        &::before {
            content: "";
            position: absolute;
            top: 50%;
            right: 5px;
            -webkit-transform: translateY(-50%);
                    transform: translateY(-50%);
            width: 22px;
            height: 22px;
            background: url('/assets/i/dropdown-open-selector.svg');
            background-size: 22px 22px;
        }
        span {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    } 

    // DROPDOWN OPTIONS
    .dropdown-options {
        display: none;
        position: absolute;
        padding: 8px 6px 9px 5px;
        max-height: 261px;
        overflow-y: auto;
        z-index: 999;
        li {
            padding: 10px 25px 10px 10px;
            font-size: $regular-font-size;
            color: $content-text-black;
            position: relative;
            line-height: 10px;
            &:last-child {
                border-bottom: none;
            }
            &:hover {
                background-color: #245A88;
                border-radius: 3px;
                color: #fff;
                border-bottom-color: transparent;
            }
            &:focus{
                background-color: #245A88;
                border-radius: 3px;
                color: #fff;
            }
            &.active {
                background-color: #245A88;
                border-radius: 3px;
                color: #fff;
                border-bottom-color: transparent;
            }
            &:hover {
                background-color: #7898B3
            }
            &.active {
                font-weight: 600;
            }
        }
    }
    &.is-open {
        .dropdown-selected {
            &::before {
                content: "";
                position: absolute;
                top: 50%;
                right: 5px;
                -webkit-transform: translateY(-50%);
                        transform: translateY(-50%);
                width: 22px;
                height: 22px;
                background: url('/assets/i/dropdown-close-selector.svg');
                background-size: 22px 22px;
            }
        }
        .dropdown-options {
            display: -webkit-box;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-orient: vertical;
            -webkit-box-direction: normal;
                -ms-flex-direction: column;
                    flex-direction: column;
            width: 100%;
            top: 32px;
            border-radius: 3px;
            background-color: #ffffff;
            border: 1px solid #DDDDDD;
            -webkit-box-shadow: 0px 3px 11px 0 rgba(1, 2, 2, 0.14);
                    box-shadow: 0px 3px 11px 0 rgba(1, 2, 2, 0.14);
        }
    }
    &.data-input-fields {
        .box {
            height: 35px;
        }
    }
    &.send-email-table-select {
        min-width: 140px;
        border: none;
    }
    &.persoanal-settings {
        width: 80px;
    }
}

div.dropdown-wrapper.disabled
{
  pointer-events: none;
  background-color: #F1F1F1;
  opacity: 0.7;
}

dropdown.component.ts

import { Component, OnInit, Input, Output, EventEmitter, HostListener, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

const noop = () => {
};

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => DropdownComponent),
  multi: true
};

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss'],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class DropdownComponent implements OnInit, ControlValueAccessor {

  @Input() options: Array<string>;
  @Input() selected: number;
  @Input() className: string;
  @Input() placeholder: string;
  @Input() isReadOnly = false;
  @Output() optSelect = new EventEmitter();
  isOpen = false;
  selectedOption;


  private onTouchedCallback: () => void = noop;
  private onChangeCallback: (_: any) => void = noop;
  isSelectedValue: boolean;
  key: string;
  isFocused: boolean;

  /**
   *Creates an instance of DropdownComponent.
   * @memberof DropdownComponent
   */

  ngOnInit() {
    // Place default value in dropdown
    if (this.selected) {
      this.placeholder = '';
      this.isOpen = false;
    }
  }

  @HostListener('focus')
  focusHandler() {
    this.selected = 0;
    this.isFocused = true;
  }

  @HostListener('focusout')
  focusOutHandler() {
    this.isFocused = false;
  }

  @HostListener('document:keydown', ['$event'])
  keyPressHandle(event: KeyboardEvent) {

    if (this.isFocused) {
      this.key = event.code;
      switch (this.key) {
        case 'Space':
          this.isOpen = true;
          break;
        case 'ArrowDown':
          if (this.options.length - 1 > this.selected) {
            this.selected = this.selected + 1;
          }
          break;
        case 'ArrowUp':
          if (this.selected > 0) {
            this.selected = this.selected - 1;
          }
          break;
        case 'Enter':
          if (this.selected > 0) {
            this.isSelectedValue = true;
            this.isOpen = false;
            this.onChangeCallback(this.selected);
            this.optSelect.emit(this.options[this.selected]);
          }
          break;
      }
    }

  }

  /**
  * option selection
  * @param {string} selectedOption - text
  * @param {number} idx - current index of item
  * @param {any} event - object
  */
  optionSelect(selectedOption: string, idx, e: any) {
    e.stopPropagation();
    this.selected = idx;
    this.isSelectedValue = true;
    // this.placeholder = '';
    this.isOpen = false;
    this.onChangeCallback(this.selected);
    this.optSelect.emit(selectedOption);
  }

  /**
  * toggle the dropdown
  * @param {any} event object
  */
  toggle(e: any) {
    e.stopPropagation();
    // close all previously opened dropdowns, before open
    const allElems = document.querySelectorAll('.dropdown-wrapper');
    for (let i = 0; i < allElems.length; i++) {
      allElems[i].classList.remove('is-open');
    }
    this.isOpen = !this.isOpen;
    if (this.selected >= 0) {
      document.querySelector('#li' + this.selected).scrollIntoView(true);
    }
  }

  /**
  * dropdown click on outside
  */
  @HostListener('document: click', ['$event'])
  onClick() {
    this.isOpen = false;
  }

  /**
   * Method implemented from ControlValueAccessor and set default selected value
   * @param {*} obj
   * @memberof DropdownComponent
   */
  writeValue(obj: any): void {
    if (obj && obj !== '') {
      this.isSelectedValue = true;
      this.selected = obj;
    } else {
      this.isSelectedValue = false;
    }
  }

  // From ControlValueAccessor interface
  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  // From ControlValueAccessor interface
  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }

  setDisabledState?(isDisabled: boolean): void {

  }

}

Usage

<app-dropdown formControlName="type" [options]="types" [placeholder]="captureData.type" [isReadOnly]="isReadOnly">
</app-dropdown>

Options must bind an array as follows. It can change based on the requirement.

types= [
        {
            "id": "1",
            "value": "Type 1"
        },
        {
             "id": "2",
             "value": "Type 2"
        },
        {
              "id": "3",
              "value": "Type 3"
        }] 

parse html string with jquery

I'm not a 100% sure, but won't

$(data)

produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.

EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)

$("img", data).attr ("src")

if you want to access the src-attribute. If your data is just text, it would probably work to do

$("img", $(data)).attr ("src")

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

OPTIONS request are by no means an AngularJS bug, this is how Cross-Origin Resource Sharing standard mandates browsers to behave. Please refer to this document: https://developer.mozilla.org/en-US/docs/HTTP_access_control, where in the "Overview" section it says:

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally, for HTTP request methods that can cause side-effects on user data (in particular; for HTTP methods other than GET, or for POST usage with certain MIME types). The specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request header, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests.

It is very hard to provide a generic solution that would work for all the WWW servers as setup will vary depending on the server itself and HTTP verbs that you intend to support. I would encourage you to get over this excellent article (http://www.html5rocks.com/en/tutorials/cors/) that has much more details on the exact headers that needs to be sent by a server.

Is it possible to use 'else' in a list comprehension?

To use the else in list comprehensions in python programming you can try out the below snippet. This would resolve your problem, the snippet is tested on python 2.7 and python 3.5.

obj = ["Even" if i%2==0 else "Odd" for i in range(10)]

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

TL;DR;

Use let...of instead of let...in !!


If you're new to Angular (>2.x) and possibly migrating from Angular1.x, most likely you're confusing in with of. As andreas has mentioned in the comments below for ... of iterates over values of an object while for ... in iterates over properties in an object. This is a new feature introduced in ES2015.

Simply replace:

<!-- Iterate over properties (incorrect in our case here) -->
<div *ngFor="let talk in talks">

with

<!-- Iterate over values (correct way to use here) -->
<div *ngFor="let talk of talks">

So, you must replace in with of inside ngFor directive to get the values.

How can I debug a Perl script?

To run your script under the Perl debugger you should use the -d switch:

perl -d script.pl

But Perl is flexible. It supplies some hooks, and you may force the debugger to work as you want

So to use different debuggers you may do:

perl -d:DebugHooks::Terminal script.pl
# OR
perl -d:Trepan script.pl

Look these modules here and here.

There are several most interesting Perl modules that hook into Perl debugger internals: Devel::NYTProf and Devel::Cover

And many others.

Creating temporary files in Android

This is what I typically do:

File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);

As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

What is the difference between join and merge in Pandas?

I believe that join() is just a convenience method. Try df1.merge(df2) instead, which allows you to specify left_on and right_on:

In [30]: left.merge(right, left_on="key1", right_on="key2")
Out[30]: 
  key1  lval key2  rval
0  foo     1  foo     4
1  bar     2  bar     5

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

SQL Server Linked Server Example Query

right click on a table and click script table as select

enter image description here

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

For those who didn't follow the MS proscribed order (see Xv's answer) you can still fix the problem.

MSBuild uses the VCTargetsPath to locate default cpp properties but cannot because the registry lacks this String Value.

Check for the String Value

  • Launch regedit
  • Navigator to HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0
  • Inspect VCTargetsPath key. The value should = "$(MSBuildExtensionsPath32)\Microsoft.Cpp\v4.0\"

To fix

  • Launch regedit Navigator to HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0
  • Add String Value VCTargetsPath
  • Set Value to "$(MSBuildExtensionsPath32)\Microsoft.Cpp\v4.0\"

Note: HKLM stands for HKEY_LOCAL_MACHINE.

Kill python interpeter in linux from the terminal

pkill with script path

pkill -9 -f path/to/my_script.py

is a short and selective method that is more likely to only kill the interpreter running a given script.

See also: https://unix.stackexchange.com/questions/31107/linux-kill-process-based-on-arguments

How to prevent IFRAME from redirecting top-level window

Since the page you load inside the iframe can execute the "break out" code with a setInterval, onbeforeunload might not be that practical, since it could flud the user with 'Are you sure you want to leave?' dialogs.

There is also the iframe security attribute which only works on IE & Opera

:(

How to install PHP intl extension in Ubuntu 14.04

For php5 on Ubuntu 14.04

sudo apt-get install php5-intl

For php7 on Ubuntu 16.04

sudo apt-get install php7.0-intl

For php7.2 on Ubuntu 18.04

sudo apt-get install php7.2-intl

Anyway restart your apache after

sudo service apache2 restart

IMPORTANT NOTE: Keep in mind that your php in your terminal/command line has NOTHING todo with the php used by the apache webserver!

If the extension is already installed you should try to enable it. Either in the php.ini file or from command line.

Syntax:

php:

phpenmod [mod name]

apache:

a2enmod [mod name]

DataGridView.Clear()

Basically below code line is only useful in data binding scenarios

datagridview.DataSource = null; 

otherwise below is the used when no data binding and datagridview is populated manually

dataGridView1.Rows.Clear();
dataGridView1.Refresh();

So, check first what you are doing.

How to run or debug php on Visual Studio Code (VSCode)

There is a much easier way to run PHP, no configuration needed:

  1. Install the Code Runner Extension
  2. Open the PHP code file in Text Editor
    • use shortcut Ctrl+Alt+N
    • or press F1 and then select/type Run Code,
    • or right click the Text Editor and then click Run Code in editor context menu
    • or click Run Code button in editor title menu
    • or click Run Code button in context menu of file explorer

Besides, you could select part of the PHP code and run the code snippet. Very convenient!

URLEncoder not able to translate space character

Although quite old, nevertheless a quick response:

Spring provides UriUtils - with this you can specify how to encoded and which part is it related from an URI, e.g.

encodePathSegment
encodePort
encodeFragment
encodeUriVariables
....

I use them cause we already using Spring, i.e. no additonal library is required!

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

How to state in requirements.txt a direct github source

Since pip v1.5, (released Jan 1 2014: CHANGELOG, PR) you may also specify a subdirectory of a git repo to contain your module. The syntax looks like this:

pip install -e git+https://git.repo/some_repo.git#egg=my_subdir_pkg&subdirectory=my_subdir_pkg # install a python package from a repo subdirectory

Note: As a pip module author, ideally you'd probably want to publish your module in it's own top-level repo if you can. Yet this feature is helpful for some pre-existing repos that contain python modules in subdirectories. You might be forced to install them this way if they are not published to pypi too.

PHP: convert spaces in string into %20?

The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode() function.

That same page contains the answer you need - use rawurlencode() instead to get RFC 3986 compatible encoding.

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

  1. Go to properties of Project which your working
  2. Choose the Deployment Assembly menu and Click on add button
  3. opt the Java Build Path Entries and Click on Maven Dependencies
  4. Build the project and run

enter image description here

Plot a bar using matplotlib using a dictionary

The best way to implement it using matplotlib.pyplot.bar(range, height, tick_label) where the range provides scalar values for the positioning of the corresponding bar in the graph. tick_label does the same work as xticks(). One can replace it with an integer also and use multiple plt.bar(integer, height, tick_label). For detailed information please refer the documentation.

import matplotlib.pyplot as plt

data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())

#tick_label does the some work as plt.xticks()
plt.bar(range(len(data)),values,tick_label=names)
plt.savefig('bar.png')
plt.show()

enter image description here

Additionally the same plot can be generated without using range(). But the problem encountered was that tick_label just worked for the last plt.bar() call. Hence xticks() was used for labelling:

data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())
plt.bar(0,values[0],tick_label=names[0])
plt.bar(1,values[1],tick_label=names[1])
plt.bar(2,values[2],tick_label=names[2])
plt.xticks(range(0,3),names)
plt.savefig('fruit.png')
plt.show()

enter image description here

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

By executing your .bat you are setting config for only that session not globally. When you open and another cmd prompt and run npm install that config will not set for this session so modify your .bat file as

@echo off
npm config set registry https://registry.npmjs.org/
@cmd.exe /K

JavaScript, get date of the next day

You can use:

var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.