Programs & Examples On #Trail

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Why do I keep getting Delete 'cr' [prettier/prettier]?

I know this is old but I just encountered the issue in my team (some mac, some linux, some windows , all vscode).

solution was to set the line ending in vscode's settings:

.vscode/settings.json

{
    "files.eol": "\n",
}

https://qvault.io/2020/06/18/how-to-get-consistent-line-breaks-in-vs-code-lf-vs-crlf/

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

Your firewall blocked port 27017 which used to connect to MongoDB.

Try to find which firewall is being used in your system, e.g. in my case is csf, config file placed at

/etc/csf/csf.conf

find TCP_IN & TCP_OUT as follow and add port 27017 to allowed incoming and outgoing ports

# Allow incoming TCP ports
TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995,2222,27017"

# Allow outgoing TCP ports
TCP_OUT = "20,21,22,25,53,80,110,113,443,587,993,995,2222,27017"

Save config file and restart csf to apply it:

csf -r

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

As I have noticed this error occurs under two circumstances,

  1. If you have used train_test_split() to split your data, you have to make sure that you reset the index of the data (specially when taken using a pandas series object): y_train, y_test indices should be resetted. The problem is when you try to use one of the scores from sklearn.metrics such as; precision_score, this will try to match the shuffled indices of the y_test that you got from train_test_split().

so use, either np.array(y_test) for y_true in scores or y_test.reset_index(drop=True)

  1. Then again you can still have this error if your predicted 'True Positives' is 0, which is used for precision, recall and f1_scores. You can visualize this using a confusion_matrix. If the classification is multilabel and you set param: average='weighted'/micro/macro you will get an answer as long as the diagonal line in the matrix is not 0

Hope this helps.

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I ran into the same problem.

My app uses Navigation components with a fragment containing my recyclerView. My list displayed fine the first time the fragment was loaded ... but upon navigating away and coming back this error occurred.

When navigating away the fragment lifecycle went only through onDestroyView and upon returning it started at onCreateView. However, my adapter was initialized in the fragment's onCreate and did not reinitialize when returning.

The fix was to initialize the adapter in onCreateView.

Hope this may help someone.

Remove trailing spaces automatically or with a shortcut

<Ctr>-<Shift>-<F> 

Format, does it as well.

This removes trailing whitespace and formats/indents your code.

Parse XLSX with Node and create json

Improved Version of "Josh Marinacci" answer , it will read beyond Z column (i.e. AA1).

var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function(y) {
    var worksheet = workbook.Sheets[y];
    var headers = {};
    var data = [];
    for(z in worksheet) {
        if(z[0] === '!') continue;
        //parse out the column, row, and value
        var tt = 0;
        for (var i = 0; i < z.length; i++) {
            if (!isNaN(z[i])) {
                tt = i;
                break;
            }
        };
        var col = z.substring(0,tt);
        var row = parseInt(z.substring(tt));
        var value = worksheet[z].v;

        //store header names
        if(row == 1 && value) {
            headers[col] = value;
            continue;
        }

        if(!data[row]) data[row]={};
        data[row][headers[col]] = value;
    }
    //drop those first two rows which are empty
    data.shift();
    data.shift();
    console.log(data);
});

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

hope this may help you:

SELECT  CAST(LoginTime AS DATE)
         FROM    AuditTrail 

If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

I had the same problem and finally resolved it by changing the order of pem blocks in certificate file.

The cert block should be put in the beginning of the file, then intermediate blocks, then root block.

I realized this problem by comparing a problematic certificate file with a working certificate file.

Trim whitespace from a String

I think that substr() throws an exception if str only contains the whitespace.

I would modify it to the following code:

string trim(string& str)
{
    size_t first = str.find_first_not_of(' ');
    if (first == std::string::npos)
        return "";
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last-first+1));
}

How Can I Remove “public/index.php” in the URL Generated Laravel?

You have to perform following steps to do this, which are as follows

  • Map your domain upto public folder of your project (i.e. /var/www/html/yourproject/public) (if using linux)

  • Go to your public folder edit your .htaccess file there

AddHandler application/x-httpd-php72 .php
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect non-www to www
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # Redirect non-http to https
    RewriteCond %{HTTPS} off
    RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Remove index.php
    RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
    RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
</IfModule>


  • The last three rules are for if you are directly accessing any route without https, it protect that.

Best way to check for "empty or null value"

A lot of the answers are the shortest way, not the necessarily the best way if the column has lots of nulls. Breaking the checks up allows the optimizer to evaluate the check faster as it doesn't have to do work on the other condition.

(stringexpression IS NOT NULL AND trim(stringexpression) != '')

The string comparison doesn't need to be evaluated since the first condition is false.

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

Solved this by adding following

RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^ - [L]

How to trim leading and trailing white spaces of a string?

@peterSO has correct answer. I am adding more examples here:

package main

import (
    "fmt"
    strings "strings"
)

func main() { 
    test := "\t pdftk 2.0.2  \n"
    result := strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\n\r pdftk 2.0.2 \n\r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\n\r\n\r pdftk 2.0.2 \n\r\n\r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\r pdftk 2.0.2 \r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))   
}

You can find this in Go lang playground too.

Sublime Text 3, convert spaces to tabs

As you might already know, you can customize your indention settings in Preferences.sublime-settings, for example:

"detect_indentation": true,
"tab_size": 4,
"translate_tabs_to_spaces": false

This will set your editor to use tabs that are 4 spaces wide and will override the default behavior that causes Sublime to match the indention of whatever file you're editing. With these settings, re-indenting the file will cause any spaces to be replaced with tabs.

As far as automatically re-indenting when opening a file, that's not quite as easy (but probably isn't a great idea since whitespace changes wreak havoc on file diffs). What might be a better course of action: you can map a shortcut for re-indention and just trigger that when you open a new file that needs fixing.

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

Htaccess: add/remove trailing slash from URL

Right below the RewriteEngine On line, add:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R] # <- for test, for prod use [L,R=301]

to enforce a no-trailing-slash policy.

To enforce a trailing-slash policy:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R] # <- for test, for prod use [L,R=301]

EDIT: commented the R=301 parts because, as explained in a comment:

Be careful with that R=301! Having it there makes many browsers cache the .htaccess-file indefinitely: It somehow becomes irreversible if you can't clear the browser-cache on all machines that opened it. When testing, better go with simple R or R=302

After you've completed your tests, you can use R=301.

what is trailing whitespace and how can I handle this?

Trailing whitespace:

It is extra spaces (and tabs) at the end of line      
                                                 ^^^^^ here

Strip them:

#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""

import sys

if len(sys.argv[1:]) != 1:
  sys.exit(__doc__)

content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
  content = infile.read()
with open(outp, 'wb') as output:
  for line in content.splitlines():
    newline = line.rstrip(" \t")
    outsize += len(newline) + 1
    output.write(newline + '\n')

print("Done. Stripped %s bytes." % (len(content)-outsize))

https://gist.github.com/techtonik/c86f0ea6a86ed3f38893

Laravel blank white screen

I also faced same issue after doing composer update

I tried installing composer required monolog/monolog too but didn't work.

Then I removed the /vendor directory and ran composer install and worked as per normal.

basically it must have reverted my monolog and other stable packages version back to previous. so better not to composer update

what I noticed comparing both the /vendor folders and found those classes files under /vendor/monolog/monolog/src/Handler were missing after composer updated.

Trim leading and trailing spaces from a string in awk

Warning by @Geoff: see my note below, only one of the suggestions in this answer works (though on both columns).

I would use sed:

sed 's/, /,/' input.txt

This will remove on leading space after the , . Output:

Name,Order
Trim,working
cat,cat1

More general might be the following, it will remove possibly multiple spaces and/or tabs after the ,:

sed 's/,[ \t]\?/,/g' input.txt

It will also work with more than two columns because of the global modifier /g


@Floris asked in discussion for a solution that removes trailing and and ending whitespaces in each colum (even the first and last) while not removing white spaces in the middle of a column:

sed 's/[ \t]\?,[ \t]\?/,/g; s/^[ \t]\+//g; s/[ \t]\+$//g' input.txt

*EDIT by @Geoff, I've appended the input file name to this one, and now it only removes all leading & trailing spaces (though from both columns). The other suggestions within this answer don't work. But try: " Multiple spaces , and 2 spaces before here " *


IMO sed is the optimal tool for this job. However, here comes a solution with awk because you've asked for that:

awk -F', ' '{printf "%s,%s\n", $1, $2}' input.txt

Another simple solution that comes in mind to remove all whitespaces is tr -d:

cat input.txt | tr -d ' '

PHP display image BLOB from MySQL

Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:

echo "data: $mime" $result['$data']";

where: mime can be an image of any kind, text, word document, text document, PDF document, etc... content datatype is blob in database.

Add left/right horizontal padding to UILabel

#define PADDING 5

@interface MyLabel : UILabel

@end

@implementation MyLabel

- (void)drawTextInRect:(CGRect)rect {
    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(0, PADDING, 0, PADDING))];
}

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
    return CGRectInset([self.attributedText boundingRectWithSize:CGSizeMake(999, 999)
                                                         options:NSStringDrawingUsesLineFragmentOrigin
                                                         context:nil], -PADDING, 0);
}

@end

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

Remove .pyc files

Ubuntu terminal command for deleting .pyc : find . -name "*.pyc" -exec rm -rf {} \;

I have got same error when I did python manage.py runserver. It was because .pyc file. I deleted .pyc file from project directory then it was working.

UIScrollView Scrollable Content Size Ambiguity

all the subviews inside a scrollview must have constraints touching all the edges of the scroll view, as its explained in the documentation, the height and width of a scroll view is calculated automatically by the measures in of the subviews, this means you need to have Trailing and leading constraints for width and Top and Bottom constraints for height.

How to set HTML5 required attribute in Javascript?

Short version

element.setAttribute("required", "");    //turns required on
element.required = true;                 //turns required on through reflected attribute
jQuery(element).attr('required', '');    //turns required on
$("#elementId").attr('required', '');    //turns required on

element.removeAttribute("required");     //turns required off
element.required = false;                //turns required off through reflected attribute
jQuery(element).removeAttr('required');  //turns required off
$("#elementId").removeAttr('required');  //turns required off

if (edName.hasAttribute("required")) { }  //check if required
if (edName.required) { }                 //check if required using reflected attribute

Long Version

Once T.J. Crowder managed to point out reflected properties, i learned that following syntax is wrong:

element.attributes["name"] = value; //bad! Overwrites the HtmlAttribute object
element.attributes.name = value;    //bad! Overwrites the HtmlAttribute object
value = element.attributes.name;    //bad! Returns the HtmlAttribute object, not its value
value = element.attributes["name"]; //bad! Returns the HtmlAttribute object, not its value

You must go through element.getAttribute and element.setAttribute:

element.getAttribute("foo");         //correct
element.setAttribute("foo", "test"); //correct

This is because the attribute actually contains a special HtmlAttribute object:

element.attributes["foo"];           //returns HtmlAttribute object, not the value of the attribute
element.attributes.foo;              //returns HtmlAttribute object, not the value of the attribute

By setting an attribute value to "true", you are mistakenly setting it to a String object, rather than the HtmlAttribute object it requires:

element.attributes["foo"] = "true";  //error because "true" is not a HtmlAttribute object
element.setAttribute("foo", "true"); //error because "true" is not an HtmlAttribute object

Conceptually the correct idea (expressed in a typed language), is:

HtmlAttribute attribute = new HtmlAttribute();
attribute.value = "";
element.attributes["required"] = attribute;

This is why:

  • getAttribute(name)
  • setAttribute(name, value)

exist. They do the work on assigning the value to the HtmlAttribute object inside.

On top of this, some attribute are reflected. This means that you can access them more nicely from Javascript:

//Set the required attribute
//element.setAttribute("required", ""); 
element.required = true;

//Check the attribute
//if (element.getAttribute("required")) {...}
if (element.required) {...}

//Remove the required attribute
//element.removeAttribute("required");
element.required = false;

What you don't want to do is mistakenly use the .attributes collection:

element.attributes.required = true;     //WRONG!
if (element.attributes.required) {...}  //WRONG!
element.attributes.required = false;    //WRONG!

Testing Cases

This led to testing around the use of a required attribute, comparing the values returned through the attribute, and the reflected property

document.getElementById("name").required;
document.getElementById("name").getAttribute("required");

with results:

HTML                         .required        .getAttribute("required")
==========================   ===============  =========================
<input>                      false (Boolean)  null (Object)
<input required>             true  (Boolean)  "" (String)
<input required="">          true  (Boolean)  "" (String)
<input required="required">  true  (Boolean)  "required" (String)
<input required="true">      true  (Boolean)  "true" (String)
<input required="false">     true  (Boolean)  "false" (String)
<input required="0">         true  (Boolean)  "0" (String)

Trying to access the .attributes collection directly is wrong. It returns the object that represents the DOM attribute:

edName.attributes["required"] => [object Attr]
edName.attributes.required    => [object Attr]

This explains why you should never talk to the .attributes collect directly. You're not manipulating the values of the attributes, but the objects that represent the attributes themselves.

How to set required?

What's the correct way to set required on an attribute? You have two choices, either the reflected property, or through correctly setting the attribute:

element.setAttribute("required", "");         //Correct
edName.required = true;                       //Correct

Strictly speaking, any other value will "set" the attribute. But the definition of Boolean attributes dictate that it should only be set to the empty string "" to indicate true. The following methods all work to set the required Boolean attribute,

but do not use them:

element.setAttribute("required", "required"); //valid, but not preferred
element.setAttribute("required", "foo");      //works, but silly
element.setAttribute("required", "true");     //Works, but don't do it, because:
element.setAttribute("required", "false");    //also sets required boolean to true
element.setAttribute("required", false);      //also sets required boolean to true
element.setAttribute("required", 0);          //also sets required boolean to true

We already learned that trying to set the attribute directly is wrong:

edName.attributes["required"] = true;       //wrong
edName.attributes["required"] = "";         //wrong
edName.attributes["required"] = "required"; //wrong
edName.attributes.required = true;          //wrong
edName.attributes.required = "";            //wrong
edName.attributes.required = "required";    //wrong

How to clear required?

The trick when trying to remove the required attribute is that it's easy to accidentally turn it on:

edName.removeAttribute("required");     //Correct
edName.required = false;                //Correct

With the invalid ways:

edName.setAttribute("required", null);    //WRONG! Actually turns required on!
edName.setAttribute("required", "");      //WRONG! Actually turns required on!
edName.setAttribute("required", "false"); //WRONG! Actually turns required on!
edName.setAttribute("required", false);   //WRONG! Actually turns required on!
edName.setAttribute("required", 0);       //WRONG! Actually turns required on!

When using the reflected .required property, you can also use any "falsey" values to turn it off, and truthy values to turn it on. But just stick to true and false for clarity.

How to check for required?

Check for the presence of the attribute through the .hasAttribute("required") method:

if (edName.hasAttribute("required"))
{
}

You can also check it through the Boolean reflected .required property:

if (edName.required)
{
}

How to draw interactive Polyline on route google maps v2 android

Instead of creating too many short Polylines just create one like here:

PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
    LatLng point = list.get(z);
    options.add(point);
}
line = myMap.addPolyline(options);

I'm also not sure you should use geodesic when your points are so close to each other.

Best way to remove the last character from a string built with stringbuilder

Just use

string.Join(",", yourCollection)

This way you don't need the StringBuilder and the loop.




Long addition about async case. As of 2019, it's not a rare setup when the data are coming asynchronously.

In case your data are in async collection, there is no string.Join overload taking IAsyncEnumerable<T>. But it's easy to create one manually, hacking the code from string.Join:

public static class StringEx
{
    public static async Task<string> JoinAsync<T>(string separator, IAsyncEnumerable<T> seq)
    {
        if (seq == null)
            throw new ArgumentNullException(nameof(seq));

        await using (var en = seq.GetAsyncEnumerator())
        {
            if (!await en.MoveNextAsync())
                return string.Empty;

            string firstString = en.Current?.ToString();

            if (!await en.MoveNextAsync())
                return firstString ?? string.Empty;

            // Null separator and values are handled by the StringBuilder
            var sb = new StringBuilder(256);
            sb.Append(firstString);

            do
            {
                var currentValue = en.Current;
                sb.Append(separator);
                if (currentValue != null)
                    sb.Append(currentValue);
            }
            while (await en.MoveNextAsync());
            return sb.ToString();
        }
    }
}

If the data are coming asynchronously but the interface IAsyncEnumerable<T> is not supported (like the mentioned in comments SqlDataReader), it's relatively easy to wrap the data into an IAsyncEnumerable<T>:

async IAsyncEnumerable<(object first, object second, object product)> ExtractData(
        SqlDataReader reader)
{
    while (await reader.ReadAsync())
        yield return (reader[0], reader[1], reader[2]);
}

and use it:

Task<string> Stringify(SqlDataReader reader) =>
    StringEx.JoinAsync(
        ", ",
        ExtractData(reader).Select(x => $"{x.first} * {x.second} = {x.product}"));

In order to use Select, you'll need to use nuget package System.Interactive.Async. Here you can find a compilable example.

Relative URLs in WordPress

Under Settings => Media, there's an option for 'Full URL-path for files'. If you set this to the default media directory path '/wp-content/uploads' instead of blank, it will insert relative paths e.g. '/wp-content/uploads/2020/06/document.pdf'.

I'm not sure if it makes all links relative, e.g. to posts, but at least it handles media, which probably is what most people are worried about.

Overlaying a DIV On Top Of HTML 5 Video

Here's an example that will center the content within the parent div. This also makes sure the overlay starts at the edge of the video, even when centered.

<div class="outer-container">
    <div class="inner-container">
        <div class="video-overlay">Bug Buck Bunny - Trailer</div>
        <video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" controls autoplay loop></video>
    </div>
</div>

with css as

.outer-container {
    border: 1px dotted black;
    width: 100%;
    height: 100%;
    text-align: center;
}
.inner-container {
    border: 1px solid black;
    display: inline-block;
    position: relative;
}
.video-overlay {
    position: absolute;
    left: 0px;
    top: 0px;
    margin: 10px;
    padding: 5px 5px;
    font-size: 20px;
    font-family: Helvetica;
    color: #FFF;
    background-color: rgba(50, 50, 50, 0.3);
}
video {
    width: 100%;
    height: 100%;
}

here's the jsfiddle https://jsfiddle.net/dyrepk2x/2/

Hope that helps :)

Reading file line by line (with space) in Unix Shell scripting - Issue

Try this,

IFS=''
while read line
do
    echo $line
done < file.txt

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

To remove spaces from left/right, use LTRIM/RTRIM. What you had

UPDATE *tablename*
   SET *columnname* = LTRIM(RTRIM(*columnname*));

would have worked on ALL the rows. To minimize updates if you don't need to update, the update code is unchanged, but the LIKE expression in the WHERE clause would have been

UPDATE [tablename]
   SET [columnname] = LTRIM(RTRIM([columnname]))
 WHERE 32 in (ASCII([columname]), ASCII(REVERSE([columname])));

Note: 32 is the ascii code for the space character.

Permission denied on CopyFile in VBS

for me adding / worked at the end of location of folder. Hence, if you are copying into folder, don't forget to put /

SQL Server : converting varchar to INT

You could try updating the table to get rid of these characters:

UPDATE dbo.[audit]
  SET UserID = REPLACE(UserID, CHAR(0), '')
  WHERE CHARINDEX(CHAR(0), UserID) > 0;

But then you'll also need to fix whatever is putting this bad data into the table in the first place. In the meantime perhaps try:

SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
  FROM dbo.[audit];

But that is not a long term solution. Fix the data (and the data type while you're at it). If you can't fix the data type immediately, then you can quickly find the culprit by adding a check constraint:

ALTER TABLE dbo.[audit]
  ADD CONSTRAINT do_not_allow_stupid_data
  CHECK (CHARINDEX(CHAR(0), UserID) = 0);

EDIT

Ok, so that is definitely a 4-digit integer followed by six instances of CHAR(0). And the workaround I posted definitely works for me:

DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;

-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;

-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;

Please confirm that this code on its own (well, the first SELECT, anyway) works for you. If it does then the error you are getting is from a different non-numeric character in a different row (and if it doesn't then perhaps you have a build where a particular bug hasn't been fixed). To try and narrow it down you can take random values from the following query and then loop through the characters:

SELECT UserID, CONVERT(VARBINARY(32), UserID)
  FROM dbo.[audit]
  WHERE UserID LIKE '%[^0-9]%';

So take a random row, and then paste the output into a query like this:

DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
  PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
  SET @i = @i + 1;
END

This may take some trial and error before you encounter a row that fails for some other reason than CHAR(0) - since you can't really filter out the rows that contain CHAR(0) because they could contain CHAR(0) and CHAR(something else). For all we know you have values in the table like:

SELECT '15' + CHAR(9) + '23' + CHAR(0);

...which also can't be converted to an integer, whether you've replaced CHAR(0) or not.

I know you don't want to hear it, but I am really glad this is painful for people, because now they have more war stories to push back when people make very poor decisions about data types.

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

Setting DEBUG = False causes 500 Error

I had a problem similar to this and I will report how I solved mine because it could be that someone is also experiencing the same.

In my case, the error was caused because the server was not finding some static files from the homepage.

So make sure the error only occurs in the index or occurs on another page. If the problem is only occurring in the index very probably you need to check the static files. I recommend opening the Chrome preview console and checking for any errors.

In my case, the server couldn't find favicon.ico and two other CSS.

To fix this I passed python manage.py collectstatic and it worked.

Remove Trailing Spaces and Update in Columns in SQL Server

Well, it depends on which version of SQL Server you are using.

In SQL Server 2008 r2, 2012 And 2014 you can simply use TRIM(CompanyName)

SQL Server TRIM Function

In other versions you have to use set CompanyName = LTRIM(RTRIM(CompanyName))

JAVA How to remove trailing zeros from a double

You should use DecimalFormat("0.#")


For 4.3000

Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

output is:

4.3

In case of 5.000 we have

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

And the output is:

5

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

You're probably setting a value for a key in the alertView, which is not allowed. The key is in this case LoginScreen. I don't see any call to setValue(), so I assume it's somewhere else in the code.

plot data from CSV file with matplotlib

I'm guessing

x= data[:,0]
y= data[:,1]

How to remove leading and trailing zeros in a string? Python

Assuming you have other data types (and not only string) in your list try this. This removes trailing and leading zeros from strings and leaves other data types untouched. This also handles the special case s = '0'

e.g

a = ['001', '200', 'akdl00', 200, 100, '0']

b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]

b
>>>['1', '2', 'akdl', 200, 100, '0']

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

Bash: Strip trailing linebreak from output

If you want to remove only the last newline, pipe through:

sed -z '$ s/\n$//'

sed won't add a \0 to then end of the stream if the delimiter is set to NUL via -z, whereas to create a POSIX text file (defined to end in a \n), it will always output a final \n without -z.

Eg:

$ { echo foo; echo bar; } | sed -z '$ s/\n$//'; echo tender
foo
bartender

And to prove no NUL added:

$ { echo foo; echo bar; } | sed -z '$ s/\n$//' | xxd
00000000: 666f 6f0a 6261 72                        foo.bar

To remove multiple trailing newlines, pipe through:

sed -Ez '$ s/\n+$//'

Convert text to columns in Excel using VBA

Try this

Sub Txt2Col()
    Dim rng As Range

    Set rng = [C7]
    Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))

    rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings

Update: button click event to act on another sheet

Private Sub CommandButton1_Click()
    Dim rng As Range
    Dim sh As Worksheet

    Set sh = Worksheets("Sheet2")
    With sh
        Set rng = .[C7]
        Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))

        rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote,  _
        ConsecutiveDelimiter:=False, _
        Tab:=False, _
        Semicolon:=False, _
        Comma:=True, 
        Space:=False, 
        Other:=False, _
        FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
        TrailingMinusNumbers:=True
    End With
End Sub

Note the .'s (eg .Range) they refer to the With statement object

git rebase merge conflict

Note: with Git 2.14.x/2.15 (Q3 2017), the git rebase message in case of conflicts will be clearer.

See commit 5fdacc1 (16 Jul 2017) by William Duclot (williamdclt).
(Merged by Junio C Hamano -- gitster -- in commit 076eeec, 11 Aug 2017)

rebase: make resolve message clearer for inexperienced users

Before:

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort"

After:

Resolve all conflicts manually, 
mark them as resolved with git add/rm <conflicted_files>
then run "git rebase --continue".

You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".')

The git UI can be improved by addressing the error messages to those they help: inexperienced and casual git users.
To this intent, it is helpful to make sure the terms used in those messages can be understood by this segment of users, and that they guide them to resolve the problem.

In particular, failure to apply a patch during a git rebase is a common problem that can be very destabilizing for the inexperienced user.
It is important to lead them toward the resolution of the conflict (which is a 3-steps process, thus complex) and reassure them that they can escape a situation they can't handle with "--abort".
This commit answer those two points by detailing the resolution process and by avoiding cryptic git linguo.

Error message "Forbidden You don't have permission to access / on this server"

This article Creating virtual hosts on Apache 2.2 helps me (point 9) permissions to the top virtual hosts directory.

I simply add this lines to my vhosts.conf file:

<Directory I:/projects/webserver>
    Order Deny,Allow
    Allow from all
</Directory>

Remove whitespaces inside a string in javascript

For space-character removal use

"hello world".replace(/\s/g, "");

for all white space use the suggestion by Rocket in the comments below!

Nginx -- static file serving confusion with root & alias

as say as @treecoder

In case of the root directive, full path is appended to the root including the location part, whereas in case of the alias directive, only the portion of the path NOT including the location part is appended to the alias.

A picture is worth a thousand words

for root:

enter image description here

for alias:

enter image description here

Remove leading and trailing spaces?

You can use the strip() to remove trailing and leading spaces.

>>> s = '   abd cde   '
>>> s.strip()
'abd cde'

Note: the internal spaces are preserved

How to remove leading and trailing white spaces from a given html string?

01). If you need to remove only leading and trailing white space use this:

var address = "  No.255 Colombo  "
address.replace(/^[ ]+|[ ]+$/g,'');

this will return string "No.255 Colombo"

02). If you need to remove all the white space use this:

var address = "  No.255 Colombo  "
address.replace(/\s/g,"");

this will return string "No.255Colombo"

Appending a line break to an output file in a shell script

You can do that without an I/O redirection:

sed -i 's/$/\n/' filename

You can also use this command to append a newline to a list of files:

find dir -name filepattern | xargs sed -i 's/$/\n/' filename

For echo, some shells implement it as a shell builtin command. It might not accept the -e option. If you still want to use echo, try to find where the echo binary file is, using which echo. In most cases, it is located in /bin/echo, so you can use /bin/echo -e "\n" to echo a new line.

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

You are correct in that static files are copied to the application at link-time, and that shared files are just verified at link time and loaded at runtime.

The dlopen call is not only for shared objects, if the application wishes to do so at runtime on its behalf, otherwise the shared objects are loaded automatically when the application starts. DLLS and .so are the same thing. the dlopen exists to add even more fine-grained dynamic loading abilities for processes. You dont have to use dlopen yourself to open/use the DLLs, that happens too at application startup.

Remove leading or trailing spaces in an entire column of data

If you would like to use a formula, the TRIM function will do exactly what you're looking for:

+----+------------+---------------------+
|    |     A      |           B         |
+----+------------+---------------------+
| 1  | =TRIM(B1)  |  value to trim here |
+----+------------+---------------------+

So to do the whole column...
1) Insert a column
2) Insert TRIM function pointed at cell you are trying to correct.
3) Copy formula down the page
4) Copy inserted column
5) Paste as "Values"

Should be good to go from there...

How do I remove trailing whitespace using a regular expression?

To remove any blank trailing spaces use this:

\n|^\s+\n

I tested in the Atom and Xcode editors.

How to format a floating number to fixed width in Python

You can also left pad with zeros. For example if you want number to have 9 characters length, left padded with zeros use:

print('{:09.3f}'.format(number))

Thus, if number = 4.656, the output is: 00004.656

For your example the output will look like this:

numbers  = [23.2300, 0.1233, 1.0000, 4.2230, 9887.2000]
for x in numbers: 
    print('{:010.4f}'.format(x))

prints:

00023.2300
00000.1233
00001.0000
00004.2230
09887.2000

One example where this may be useful is when you want to properly list filenames in alphabetical order. I noticed in some linux systems, the number is: 1,10,11,..2,20,21,...

Thus if you want to enforce the necessary numeric order in filenames, you need to left pad with the appropriate number of zeros.

Turning multi-line string into single comma-separated

Well the hardest part probably is selecting the second "column" since I wouldn't know of an easy way to treat multiple spaces as one. For the rest it's easy. Use bash substitutions.

# cat bla.txt
something1:    +12.0   (some unnecessary trailing data (this must go))
something2:    +15.5   (some more unnecessary trailing data)
something4:    +9.0   (some other unnecessary data)
something1:    +13.5  (blah blah blah)

# cat bla.sh
OLDIFS=$IFS
IFS=$'\n'
for i in $(cat bla.txt); do
  i=$(echo "$i" | awk '{print $2}')
  u="${u:+$u, }$i"
done
IFS=$OLDIFS
echo "$u"

# bash ./bla.sh
+12.0, +15.5, +9.0, +13.5

How to print float to n decimal places including trailing 0s?

The cleanest way in modern Python >=3.6, is to use an f-string with string formatting:

>>> var = 1.6
>>> f"{var:.15f}"
'1.600000000000000'

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

Horizontal swipe slider with jQuery and touch devices support?

With my experiance the best open source option will be UIKIT with its uikit slider component. and it is very easy to implement for example in your case you could do something like this.

<div data-uk-slider>
<div class="uk-slider-container">
    <ul class="uk-slider uk-grid-width-medium-1-4"> // width of the elements
        <li>...</li> //slide elements
        ...
    </ul>
</div>

Remove trailing newline from the elements of a string list

list comprehension? [x.strip() for x in lst]

PowerShell: Store Entire Text File Contents in Variable

Get-Content grabs data and dumps it into an array, line by line. Assuming there aren't other special requirements than you listed, you could just save your content into a variable?

$file = Get-Content c:\file\whatever.txt

Running just $file will return the full contents. Then you can just do $file.Count (because arrays already have a count method built in) to get the total # of lines.

Hope this helps! I'm not a scripting wiz, but this seemed easier to me than a lot of the stuff above.

Remove trailing comma from comma-separated string

    String str = "kushalhs , mayurvm , narendrabz ,";
    System.out.println(str.replaceAll(",([^,]*)$", "$1"));

Get name of current class?

You can access it by the class' private attributes:

cls_name = self.__class__.__name__

EDIT:

As said by Ned Batcheler, this wouldn't work in the class body, but it would in a method.

How to remove leading and trailing whitespace in a MySQL field?

If you need to use trim in select query, you can also use regular expressions

SELECT * FROM table_name WHERE field RLIKE ' * query-string *'

return rows with field like '      query-string   '

Return string without trailing slash

Here a small url example.

var currentUrl = location.href;

if(currentUrl.substr(-1) == '/') {
    currentUrl = currentUrl.substr(0, currentUrl.length - 1);
}

log the new url

console.log(currentUrl);

Strip Leading and Trailing Spaces From Java String

To trim specific char, you can use:

String s = s.replaceAll("^(,|\\s)*|(,|\\s)*$", "")

Here will strip leading and trailing space and comma.

How to check for a valid Base64 encoded string

Do decode, re encode and compare the result to original string

public static Boolean IsBase64(this String str)
{
    if ((str.Length % 4) != 0)
    {
        return false;
    }

    //decode - encode and compare
    try
    {
        string decoded = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(str));
        string encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(decoded));
        if (str.Equals(encoded, StringComparison.InvariantCultureIgnoreCase))
        {
            return true;
        }
    }
    catch { }
    return false;
}

Escape double quotes in Java

For a String constant you have no choice other than escaping via backslash.

Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.

Node.js: printing to console without a trailing newline?

None of these solutions work for me, process.stdout.write('ok\033[0G') and just using '\r' just create a new line but don't overwrite on Mac OSX 10.9.2.

EDIT: I had to use this to replace the current line:

process.stdout.write('\033[0G');
process.stdout.write('newstuff');

When should I use a trailing slash in my URL?

In my personal opinion trailing slashes are misused.

Basically the URL format came from the same UNIX format of files and folders, later on, on DOS systems, and finally, adapted for the web.

A typical URL for this book on a Unix-like operating system would be a file path such as file:///home/username/RomeoAndJuliet.pdf, identifying the electronic book saved in a file on a local hard disk.

Source: Wikipedia: Uniform Resource Identifier

Another good source to read: Wikipedia: URI Scheme

According to RFC 1738, which defined URLs in 1994, when resources contain references to other resources, they can use relative links to define the location of the second resource as if to say, "in the same place as this one except with the following relative path". It went on to say that such relative URLs are dependent on the original URL containing a hierarchical structure against which the relative link is based, and that the ftp, http, and file URL schemes are examples of some that can be considered hierarchical, with the components of the hierarchy being separated by "/".

Source: Wikipedia Uniform Resource Locator (URL)

Also:

That is the question we hear often. Onward to the answers! Historically, it’s common for URLs with a trailing slash to indicate a directory, and those without a trailing slash to denote a file:

http://example.com/foo/ (with trailing slash, conventionally a directory)

http://example.com/foo (without trailing slash, conventionally a file)

Source: Google WebMaster Central Blog - To slash or not to slash

Finally:

  1. A slash at the end of the URL makes the address look "pretty".

  2. A URL without a slash at the end and without an extension looks somewhat "weird".

  3. You will never name your CSS file (for example) http://www.sample.com/stylesheet/ would you?

BUT I'm being a proponent of web best practices regardless of the environment. It can be wonky and unclear, just as you said about the URL with no ext.

Git status shows files as changed even though contents are the same

i had the same problem. after win->lin copy i've got all files modified.
i used fromdos to fix line endings
and then

git add -uv 

to add changes.
it added 3 files (not all of them), which i actually modified. and after that git status shows only 3 modified files. after git commit everything is ok with git status

Define a global variable in a JavaScript function

Just declare it outside the functions, and assign values inside the functions. Something like:

<script type="text/javascript">
    var offsetfrommouse = [10, -20];
    var displayduration = 0;
    var obj_selected = 0;
    var trailimage = null ;  // Global variable
    function makeObj(address) {
        trailimage = [address, 50, 50];  // Assign value

Or simply removing "var" from your variable name inside function also makes it global, but it is better to declare it outside once for cleaner code. This will also work:

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;

function makeObj(address) {
    trailimage = [address, 50, 50];  // Global variable, assign value

I hope this example explains more: http://jsfiddle.net/qCrGE/

var globalOne = 3;
testOne();

function testOne()
{
    globalOne += 2;
    alert("globalOne is :" + globalOne );
    globalOne += 1;
}

alert("outside globalOne is: " + globalOne);

testTwo();

function testTwo()
{
    globalTwo = 20;
    alert("globalTwo is " + globalTwo);
    globalTwo += 5;
}

alert("outside globalTwo is:" + globalTwo);

How to remove trailing whitespace in code, using another script?

If you're looking to tidy up for PEP8, this will trim trailing whitespace for your whole project:

import os

PATH = '/path/to/your/project'

for path, dirs, files in os.walk(PATH):
    for f in files:
        file_name, file_extension = os.path.splitext(f)
        if file_extension == '.py':
            path_name = os.path.join(path, f)
            with open(path_name, 'r') as fh:
                new = [line.rstrip() for line in fh]
            with open(path_name, 'w') as fh:
                [fh.write('%s\n' % line) for line in new]

How to split string using delimiter char using T-SQL?

You simply need to do a SUBSTR on the string in col3....

    Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'), 
    (instr(col3, '|', instr(col3, 'Client Name')  -
    instr(col3, 'Client Name'))
    ),
'Client Name = ',
'')
    from Table01 

And yes, that is a bad DB design for the reasons stated in the original issue

How to remove the last character from a bash grep output

I'd use sed 's/;$//'. eg:

COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2 | sed 's/;$//'`

Split string with multiple delimiters in Python

In response to Jonathan's answer above, this only seems to work for certain delimiters. For example:

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

>>> b='1999-05-03 10:37:00'
>>> re.split('- :', b)
['1999-05-03 10:37:00']

By putting the delimiters in square brackets it seems to work more effectively.

>>> re.split('[- :]', b)
['1999', '05', '03', '10', '37', '00']

Float to String format specifier

In C#, float is an alias for System.Single (a bit like intis an alias for System.Int32).

Perl: function to trim string leading and trailing whitespace

Apply: s/^\s*//; s/\s+$//; to it. Or use s/^\s+|\s+$//g if you want to be fancy.

Remove trailing zeros

try like this

string s = "2.4200";

s = s.TrimStart('0').TrimEnd('0', '.');

and then convert that to float

How to remove trailing whitespaces with sed?

Just for fun:

#!/bin/bash

FILE=$1

if [[ -z $FILE ]]; then
   echo "You must pass a filename -- exiting" >&2
   exit 1
fi

if [[ ! -f $FILE ]]; then
   echo "There is not file '$FILE' here -- exiting" >&2
   exit 1
fi

BEFORE=`wc -c "$FILE" | cut --delimiter=' ' --fields=1`

# >>>>>>>>>>
sed -i.bak -e's/[ \t]*$//' "$FILE"
# <<<<<<<<<<

AFTER=`wc -c "$FILE" | cut --delimiter=' ' --fields=1`

if [[ $? != 0 ]]; then
   echo "Some error occurred" >&2
else
   echo "Filtered '$FILE' from $BEFORE characters to $AFTER characters"
fi

Remove .php extension with .htaccess

To remove the .php extension from a PHP file for example yoursite.com/about.php to yoursite.com/about Follow these step . Open .htaccess(create new one if not exists) file from root of your website, and add the following code.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

To remove the .html extension from a html file for example yoursite.com/about.html to yoursite.com/about Follow these step .

Open .htaccess(create new one if not exists) file from root of your website, and add the following code.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

Reference: How to Remove php Extention from URL

tar: Error is not recoverable: exiting now

use sudo

sudo tar -zxvf xxxxxxxxx.tar.gz

How to match, but not capture, part of a regex?

I have modified one of the answers (by @op1ekun):

123-(apple(?=-)|banana(?=-)|(?!-))-?456

The reason is that the answer from @op1ekun also matches "123-apple456", without the hyphen after apple.

Oracle sqlldr TRAILING NULLCOLS required, but why?

Try giving 5 ',' in every line, similar to line number 4.

Remove insignificant trailing zeros from a number?

If you convert it to a string it will not display any trailing zeros, which aren't stored in the variable in the first place since it was created as a Number, not a String.

var n = 1.245000
var noZeroes = n.toString() // "1.245" 

How to remove leading and trailing spaces from a string

text.Trim() is to be used

string txt = "                   i am a string                                    ";
txt = txt.Trim();

Pad with leading zeros

An integer value is a mathematical representation of a number and is ignorant of leading zeroes.

You can get a string with leading zeroes like this:

someNumber.ToString("00000000")

exception in initializer error in java when using Netbeans

I found that I had bound jFormattedCheckBox1.foreground to jCheckBox1[${selected}].... this was the problem. Thank you for your help.

It seems that a color should not be able to be bound to a boolean. I guess bindings are an advanced feature?

I found the problem by deleting all of the controls, then running, then undoing and then deleting one at a time. When I found the offending control, I examined the properties.

How to remove trailing and leading whitespace for user-provided input in a batch file?

for /f "usebackq tokens=*" %%a in (`echo %StringWithLeadingSpaces%`) do set StringWithout=%%a

This is very simple. for without any parameters considers spaces to be delimiters; setting "*" as the tokens parameter causes the program to gather up all the parts of the string that are not spaces and place them into a new string into which it inserts gaps of its own.

Remove trailing zeros from decimal in SQL Server

How about this? Assuming data coming into your function as @thisData:

BEGIN
  DECLARE @thisText VARCHAR(255)
  SET @thisText = REPLACE(RTRIM(REPLACE(@thisData, '0', ' ')), ' ', '0')
  IF SUBSTRING(@thisText, LEN(@thisText), 1) = '.'
    RETURN STUFF(@thisText, LEN(@thisText), 1, '')
  RETURN @thisText
END

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

You could use lookarounds also.

test.replaceAll("^ +| +$|(?<= ) ", "");

OR

test.replaceAll("^ +| +$| (?= )", "")

<space>(?= ) matches a space character which is followed by another space character. So in consecutive spaces, it would match all the spaces except the last because it isn't followed by a space character. This leaving you a single space for consecutive spaces after the removal operation.

Example:

    String[] tests = {
            "  x  ",          // [x]
            "  1   2   3  ",  // [1 2 3]
            "",               // []
            "   ",            // []
        };
        for (String test : tests) {
            System.out.format("[%s]%n",
                test.replaceAll("^ +| +$| (?= )", "")
            );
        }

Opening PDF String in new window with javascript

Just encode your formatted PDF string in base 64. Then you should do:

$pdf = 'data:application/pdf;base64,'.$base64EncodedString;

return this to javascript and open in a new window:

window.open(return);

Removing trailing newline character from fgets() input

The elegant way:

Name[strcspn(Name, "\n")] = 0;

The slightly ugly way:

char *pos;
if ((pos=strchr(Name, '\n')) != NULL)
    *pos = '\0';
else
    /* input too long for buffer, flag error */

The slightly strange way:

strtok(Name, "\n");

Note that the strtok function doesn't work as expected if the user enters an empty string (i.e. presses only Enter). It leaves the \n character intact.

There are others as well, of course.

How can I set size of a button?

GridLayout is often not the best choice for buttons, although it might be for your application. A good reference is the tutorial on using Layout Managers. If you look at the GridLayout example, you'll see the buttons look a little silly -- way too big.

A better idea might be to use a FlowLayout for your buttons, or if you know exactly what you want, perhaps a GroupLayout. (Sun/Oracle recommend that GroupLayout or GridBag layout are better than GridLayout when hand-coding.)

Formatting floats without trailing zeros

What about trying the easiest and probably most effective approach? The method normalize() removes all the rightmost trailing zeros.

from decimal import Decimal

print (Decimal('0.001000').normalize())
# Result: 0.001

Works in Python 2 and Python 3.

-- Updated --

The only problem as @BobStein-VisiBone pointed out, is that numbers like 10, 100, 1000... will be displayed in exponential representation. This can be easily fixed using the following function instead:

from decimal import Decimal


def format_float(f):
    d = Decimal(str(f));
    return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

Right-click on your project's name in Eclipse's Project Explorer, then click Run As followed by Run on Server. Click the Next button. Make sure your project's name is listed in the Configured: column on the right. If it is, then you should be able to access it with this URL:

http://localhost:8085/projectname/

Additionally, whenever you make new additions (such as new JSPs, graphics or other resources) to your project, be sure to refresh the project by clicking on its name and then hitting F5. Otherwise Eclipse does not know that those new resources are available and will not make them available to Tomcat to serve.

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

I used

View.inflate(getContext(), R.layout.whatever, null)

The using of View.inflate prevents the warning of using null at getLayoutInflater().inflate().

How can I trim leading and trailing white space?

Removing leading and trailing blanks might be achieved through the trim() function from the gdata package as well:

require(gdata)
example(trim)

Usage example:

> trim("   Remove leading and trailing blanks    ")
[1] "Remove leading and trailing blanks"

I'd prefer to add the answer as comment to user56's, but I am yet unable so writing as an independent answer.

Removing leading and trailing spaces from a string

Easy removing leading, trailing and extra spaces from a std::string in one line

value = std::regex_replace(value, std::regex("^ +| +$|( ) +"), "$1");

removing only leading spaces

value.erase(value.begin(), std::find_if(value.begin(), value.end(), std::bind1st(std::not_equal_to<char>(), ' ')));

or

value = std::regex_replace(value, std::regex("^ +"), "");

removing only trailing spaces

value.erase(std::find_if(value.rbegin(), value.rend(), std::bind1st(std::not_equal_to<char>(), ' ')).base(), value.end());

or

value = std::regex_replace(value, std::regex(" +$"), "");

removing only extra spaces

value = regex_replace(value, std::regex(" +"), " ");

Make Vim show ALL white spaces as a character

I like using special characters to show whitespace, is more clear. Even a map to toggle is a key feature, for a quick check.

You can find this features in an old vim script not updated since 2004:

vim-scripts/[email protected]

Thanks to project vim-scripts and vundle you can come back to life this plugin

vim-scripts/cream-showinvisibles@github

Even better, my two cents on this is to add a configurable shortcut (instead of predefined F4)

so add this to ~/.vimrc

Plugin 'albfan/cream-invisibles'

let g:creamInvisibleShortCut = "<F5>" "for my F4 goto next error

install plugin on vim

:PluginInstall

and there you go

How can I delete a newline if it is the last character in a file?

A fast solution is using the gnu utility truncate:

[ -z $(tail -c1 file) ] && truncate -s-1 file

The test will be true if the file does have a trailing new line.

The removal is very fast, truly in place, no new file is needed and the search is also reading from the end just one byte (tail -c1).

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

The difference from the Java API Specifications is as follows.

For ClassNotFoundException:

Thrown when an application tries to load in a class through its string name using:

  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader.
  • The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.

For NoClassDefFoundError:

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

So, it appears that the NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included.

As for ClassNotFoundException, it appears that it may stem from trying to make reflective calls to classes at runtime, but the classes the program is trying to call is does not exist.

The difference between the two is that one is an Error and the other is an Exception. With NoClassDefFoundError is an Error and it arises from the Java Virtual Machine having problems finding a class it expected to find. A program that was expected to work at compile-time can't run because of class files not being found, or is not the same as was produced or encountered at compile-time. This is a pretty critical error, as the program cannot be initiated by the JVM.

On the other hand, the ClassNotFoundException is an Exception, so it is somewhat expected, and is something that is recoverable. Using reflection is can be error-prone (as there is some expectations that things may not go as expected. There is no compile-time check to see that all the required classes exist, so any problems with finding the desired classes will appear at runtime.

String strip() for JavaScript?

If you're already using jQuery, then you may want to have a look at jQuery.trim() which is already provided with jQuery.

Non greedy (reluctant) regex matching in sed?

Have not yet seen this answer, so here's how you can do this with vi or vim:

vi -c '%s/\(http:\/\/.\{-}\/\).*/\1/ge | wq' file &>/dev/null

This runs the vi :%s substitution globally (the trailing g), refrains from raising an error if the pattern is not found (e), then saves the resulting changes to disk and quits. The &>/dev/null prevents the GUI from briefly flashing on screen, which can be annoying.

I like using vi sometimes for super complicated regexes, because (1) perl is dead dying, (2) vim has a very advanced regex engine, and (3) I'm already intimately familiar with vi regexes in my day-to-day usage editing documents.

How can I remove leading and trailing quotes in SQL Server?

The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].

-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters 
-- (from the 2nd character and the LEN([Description]) - 2th character)

UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'

How to auto-remove trailing whitespace in Eclipse?

I would say AnyEdit too. It does not provide this specific functionalities. However, if you and your team use the AnyEdit features at each save actions, then when you open a file, it must not have any trailing whitespace.

So, if you modify this file, and if you add new trailing spaces, then during the save operation, AnyEdit will remove only these new spaces, as they are the only trailing spaces in this file.

If, for some reasons, you need to keep the trailing spaces on the lines that were not modified by you, then I have no answer for you, and I am not sure this kind of feature exists in any Eclipse plugin...

What is the canonical way to trim a string in Ruby without creating a new string?

If you want to use another method after you need something like this:

( str.strip || str ).split(',')

This way you can strip and still do something after :)

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
(
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
    (
        oneChar := param[index];
        index := index - 1;
    );

    Left(param , index + 1);
)

How do I trim whitespace from a string?

This will remove all leading and trailing whitespace in myString:

myString.strip()

How to nicely format floating numbers to string without unnecessary decimal 0's

new DecimalFormat("00.#").format(20.236)
//out =20.2

new DecimalFormat("00.#").format(2.236)
//out =02.2
  1. 0 for minimum number of digits
  2. Renders # digits

Make git automatically remove trailing whitespace before committing

Using git attributes, and filters setup with git config

OK, this is a new tack on solving this problem… My approach is to not use any hooks, but rather use filters and git attributes. What this allows you to do, is setup, on each machine you develop on, a set of filters that will strip extra trailing white space and extra blank lines at the end of files before committing them. Then setup a .gitattributes file that says which types of files the filter should be applied to. The filters have two phases, clean which is applied when adding files to the index, and smudge which is applied when adding them to the working directory.

Tell your git to look for a global attributes file

First, tell your global config to use a global attributes file:

git config --global core.attributesfile ~/.gitattributes_global

Create global filters

Now, create the filter:

git config --global filter.fix-eol-eof.clean fixup-eol-eof %f
git config --global filter.fix-eol-eof.smudge cat
git config --global filter.fix-eol-eof.required true

Add the sed scripting magic

Finally, put the fixup-eol-eof script somewhere on your path, and make it executable. The script uses sed to do some on the fly editing (remove spaces and blanks at the end of lines, and extraneous blank lines at the end of the file)

fixup-eol-eof should look like this:

#!/bin/bash
sed -e 's/[  ]*$//' -e :a -e '/^\n*$/{$d;N;ba' -e '}' $1

my gist of this

Tell git which file types to apply your newly created filter to

Lastly, create or open ~/.gitattributes_global in your favorite editor and add lines like:

pattern attr1 [attr2 [attr3 […]]]

So if we want to fix the whitespace issue, for all of our c source files we would add a line that looks like this:

*.c filter=fix-eol-eof

Discussion of the filter

The filter has two phases, the clean phase which is applied when things are added to the index or checked in, and the smudge phase when git puts stuff into your working directory. Here, our smudge is just running the contents through the cat command which should leave them unchanged, with the exception of possibly adding a trailing newline character if there wasn’t one at the end of the file. The clean command is the whitespace filtering which I cobbled together from notes at http://sed.sourceforge.net/sed1line.txt. It seems that it must be put into a shell script, I couldn’t figure out how to inject the sed command, including the sanitation of the extraneous extra lines at the end of the file directly into the git-config file. (You CAN get rid of trailing blanks, however, without the need of a separate sed script, just set the filter.fix-eol-eofto something like sed 's/[ \t]*$//' %f where the \t is an actual tab, by pressing tab.)

The require = true causes an error to be raised if something goes wrong, to keep you out of trouble.

Please forgive me if my language concerning git is imprecise. I think I have a fairly good grasp of the concepts but am still learning the terminology.

Avoid trailing zeroes in printf()

Slight variation on above:

  1. Eliminates period for case (10000.0).
  2. Breaks after first period is processed.

Code here:

void EliminateTrailingFloatZeros(char *iValue)
{
  char *p = 0;
  for(p=iValue; *p; ++p) {
    if('.' == *p) {
      while(*++p);
      while('0'==*--p) *p = '\0';
      if(*p == '.') *p = '\0';
      break;
    }
  }
}

It still has potential for overflow, so be careful ;P

How can I remove a trailing newline?

It looks like there is not a perfect analog for perl's chomp. In particular, rstrip cannot handle multi-character newline delimiters like \r\n. However, splitlines does as pointed out here. Following my answer on a different question, you can combine join and splitlines to remove/replace all newlines from a string s:

''.join(s.splitlines())

The following removes exactly one trailing newline (as chomp would, I believe). Passing True as the keepends argument to splitlines retain the delimiters. Then, splitlines is called again to remove the delimiters on just the last "line":

def chomp(s):
    if len(s):
        lines = s.splitlines(True)
        last = lines.pop()
        return ''.join(lines + last.splitlines())
    else:
        return ''

Can you use a trailing comma in a JSON object?

I usually loop over the array and attach a comma after every entry in the string. After the loop I delete the last comma again.

Maybe not the best way, but less expensive than checking every time if it's the last object in the loop I guess.

How to round a number to n decimal places in Java

Just in case someone still needs help with this. This solution works perfectly for me.

private String withNoTrailingZeros(final double value, final int nrOfDecimals) {
return new BigDecimal(String.valueOf(value)).setScale(nrOfDecimals,  BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();

}

returns a String with the desired output.

How do I trim leading/trailing whitespace in a standard way?

I'm only including code because the code posted so far seems suboptimal (and I don't have the rep to comment yet.)

void inplace_trim(char* s)
{
    int start, end = strlen(s);
    for (start = 0; isspace(s[start]); ++start) {}
    if (s[start]) {
        while (end > 0 && isspace(s[end-1]))
            --end;
        memmove(s, &s[start], end - start);
    }
    s[end - start] = '\0';
}

char* copy_trim(const char* s)
{
    int start, end;
    for (start = 0; isspace(s[start]); ++start) {}
    for (end = strlen(s); end > 0 && isspace(s[end-1]); --end) {}
    return strndup(s + start, end - start);
}

strndup() is a GNU extension. If you don't have it or something equivalent, roll your own. For example:

r = strdup(s + start);
r[end-start] = '\0';

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

Jenkins, specifying JAVA_HOME

Upgrading from Ubuntu 10.0.4 to 12.0.4 we got wrong footed. We had a JDK installation configured (auto-configured?) pointing to /usr/lib/jvm/java-6-openjdk this no longer contained a JDK, Changing to /usr/lib/jvm/default-java fixed, and should make for a seamless java-7 upgrade.

So in answer to the question: do not specify JAVA_HOME on Ubuntu.

Finding the second highest number in array

public static void main(String[] args) {

    int[] arr = {0,12,74,56,2,63,45};
    int f1 = 1, f2 = 0, temp = 0;
    int num = 0;

    for (int i = 0; i < arr.length; i++){
        num = arr[i];
        if (f1 < num) {
            temp = f1;
            f1 = num;
            num = temp;
        }
        if (f2 < num) {
            temp = f2;
            f2 = num;
            num = temp;
        }
    }
    System.out.println("First Highest " + f1 + " Second Highest " + f2 + " Third " + num);

}

How to enable Bootstrap tooltip on disabled button?

pointer-events: auto; does not work on an <input type="text" />.

I took a different approach. I do not disable the input field, but make it act as disabled via css and javascript.

Because the input field is not disabled, the tooltip is displayed properly. It was in my case way simpler than adding a wrapper in case the input field was disabled.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
  $('.disabled[data-toggle="tooltip"]').tooltip();_x000D_
  $('.disabled').mousedown(function(event){_x000D_
    event.stopImmediatePropagation();_x000D_
    return false;_x000D_
  });_x000D_
});
_x000D_
input[type=text].disabled{_x000D_
  cursor: default;_x000D_
  margin-top: 40px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.3/js/tether.min.js"></script>_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> _x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<input type="text" name="my_field" value="100" class="disabled" list="values_z1" data-toggle="tooltip" data-placement="top" title="this is 10*10">
_x000D_
_x000D_
_x000D_

Convert RGB to Black & White in OpenCV

AFAIK, you have to convert it to grayscale and then threshold it to binary.

1. Read the image as a grayscale image If you're reading the RGB image from disk, then you can directly read it as a grayscale image, like this:

// C
IplImage* im_gray = cvLoadImage("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

// C++ (OpenCV 2.0)
Mat im_gray = imread("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

2. Convert an RGB image im_rgb into a grayscale image: Otherwise, you'll have to convert the previously obtained RGB image into a grayscale image

// C
IplImage *im_rgb  = cvLoadImage("image.jpg");
IplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);
cvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);

// C++
Mat im_rgb  = imread("image.jpg");
Mat im_gray;
cvtColor(im_rgb,im_gray,CV_RGB2GRAY);

3. Convert to binary You can use adaptive thresholding or fixed-level thresholding to convert your grayscale image to a binary image.

E.g. in C you can do the following (you can also do the same in C++ with Mat and the corresponding functions):

// C
IplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);
cvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

// C++
Mat img_bw = im_gray > 128;

In the above example, 128 is the threshold.

4. Save to disk

// C
cvSaveImage("image_bw.jpg",img_bw);

// C++
imwrite("image_bw.jpg", img_bw);

When to use Hadoop, HBase, Hive and Pig?

1.We are using Hadoop for storing Large data (i.e.structure,Unstructure and Semistructure data ) in the form file format like txt,csv.

2.If We want columnar Updations in our data then we are using Hbase tool

3.In case of Hive , we are storing Big data which is in structured format and in addition to that we are providing Analysis on that data.

4.Pig is tool which is using Pig latin language to analyze data which is in any format(structure,semistructure and unstructure).

Printing an array in C++?

C++ can print whatever you want if you program it to do so. You'll have to go through the array yourself printing each element.

Play/pause HTML 5 video using JQuery

    enter code here
<form class="md-form" action="#">
  <div class="file-field">
    <div class="btn btn-primary btn-sm float-left">
      <span>Choose files</span>
      <input type="file" multiple>
    </div>
    <div class="file-path-wrapper">
      <input class="file-path validate" type="text" placeholder="Upload one or more files">
    </div>
  </div>
</form>

<video  width="320" height="240" id="keerthan"></video>

<button onclick="playVid()" type="button">Play Video</button>
<button onclick="pauseVid()" type="button">Pause Video</button> 
<script>
    (function localFileVideoPlayer() {

  var playSelectedFile = function (event) {
    var file = this.files[0]
    var type = file.type
    var videoNode = document.querySelector('video')




    var fileURL = URL.createObjectURL(file)
    videoNode.src = fileURL
  }
  var inputNode = document.querySelector('input')
  inputNode.addEventListener('change', playSelectedFile, false)
})()
function playVid() { 
  keerthan.play(); 
} 

function pauseVid() { 
  keerthan.pause(); 
} 

</script>

Using Java 8 to convert a list of objects into a string obtained from the toString() method

With Java 8+

String s = Arrays.toString(list.stream().toArray(AClass[]::new));

Not the most efficient, but it is a solution with a small amount of code.

Remove "whitespace" between div element

Add line-height: 0px; to your parent div

jsfiddle: http://jsfiddle.net/majZt/

Arraylist swap elements

Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc

public static void swap(List list,
                        int i,
                        int j)

Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)

Parameters: list - The list in which to swap elements. i - the index of one element to be swapped. j - the index of the other element to be swapped.

Read The official Docs of collection

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29

import java.util.*;
import java.lang.*;

class Main {
    public static void main(String[] args) throws java.lang.Exception       
    {    
        //create an ArrayList object
        ArrayList words = new ArrayList();

        //Add elements to Arraylist
        words.add("A");
        words.add("B");
        words.add("C");
        words.add("D");
        words.add("E");

        System.out.println("Before swaping, ArrayList contains : " + words);

        /*
      To swap elements of Java ArrayList use,
      static void swap(List list, int firstElement, int secondElement)
      method of Collections class. Where firstElement is the index of first
      element to be swapped and secondElement is the index of the second element
      to be swapped.

      If the specified positions are equal, list remains unchanged.

      Please note that, this method can throw IndexOutOfBoundsException if
      any of the index values is not in range.        */

        Collections.swap(words, 0, words.size() - 1);

        System.out.println("After swaping, ArrayList contains : " + words);    

    }
}

Oneline compilation example http://ideone.com/MJJwtc

Converting ArrayList to HashMap

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

Vertically centering Bootstrap modal window

after 4 hours I found the solution. To center modal in different resolutions (desktop, tablets, smartphones):

index.php

<! - Bootstrap core CSS ->
     <link href=".../css/bootstrap-modal-bs3patch.css" rel="stylesheet">
     <link href=".../css/bootstrap-modal.css" rel="stylesheet">

The file bootstrap-modal-bs3patch.css I downloaded it from https://github.com/jschr/bootstrap-modal

I then modified this file. Css as follows:

body.modal-open,
. modal-open. navbar-fixed-top,
. modal-open. navbar-fixed-bottom {
   margin-right: 0;
}


. {modal
   padding: 0;
}

. modal.container {
   max-width: none;
}

@ media (min-width: 768px) and (max-width: 992px) {

. {modal-dialog
background-color: black;
position: fixed;
top: 20%! important;
left: 15%! important;
}
}

@ media (min-width: 992px) and (max-width: 1300px) {

. {modal-dialog
background-color: red;
position: fixed;
top: 20%! important;
left: 20%! important;
}
}

@ media (min-width: 1300px) {

. {modal-dialog
background-color: # 6e7ec3;
position: fixed;
top: 40%! important;
left: 35%! important;
}
}

I did tests on different resolutions and it works!

python's re: return True if string contains regex pattern

Match objects are always true, and None is returned if there is no match. Just test for trueness.

Code:

>>> st = 'bar'
>>> m = re.match(r"ba[r|z|d]",st)
>>> if m:
...     m.group(0)
...
'bar'

Output = bar

If you want search functionality

>>> st = "bar"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m is not None:
...     m.group(0)
...
'bar'

and if regexp not found than

>>> st = "hello"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m:
...     m.group(0)
... else:
...   print "no match"
...
no match

As @bukzor mentioned if st = foo bar than match will not work. So, its more appropriate to use re.search.

Difference between number and integer datatype in oracle dictionary views

This is what I got from oracle documentation, but it is for oracle 10g release 2:

When you define a NUMBER variable, you can specify its precision (p) and scale (s) so that it is sufficiently, but not unnecessarily, large. Precision is the number of significant digits. Scale can be positive or negative. Positive scale identifies the number of digits to the right of the decimal point; negative scale identifies the number of digits to the left of the decimal point that can be rounded up or down.

The NUMBER data type is supported by Oracle Database standard libraries and operates the same way as it does in SQL. It is used for dimensions and surrogates when a text or INTEGER data type is not appropriate. It is typically assigned to variables that are not used for calculations (like forecasts and aggregations), and it is used for variables that must match the rounding behavior of the database or require a high degree of precision. When deciding whether to assign the NUMBER data type to a variable, keep the following facts in mind in order to maximize performance:

  • Analytic workspace calculations on NUMBER variables is slower than other numerical data types because NUMBER values are calculated in software (for accuracy) rather than in hardware (for speed).
  • When data is fetched from an analytic workspace to a relational column that has the NUMBER data type, performance is best when the data already has the NUMBER data type in the analytic workspace because a conversion step is not required.

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

use grep -n -i null myfile.txt to output the line number in front of each match.

I dont think grep has a switch to print the count of total lines matched, but you can just pipe grep's output into wc to accomplish that:

grep -n -i null myfile.txt | wc -l

How to add element into ArrayList in HashMap

I know, this is an old question. But just for the sake of completeness, the lambda version.

Map<String, List<Item>> items = new HashMap<>();
items.computeIfAbsent(key, k -> new ArrayList<>()).add(item);

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

This specifies the default collation for the database. Every text field that you create in tables in the database will use that collation, unless you specify a different one.

A database always has a default collation. If you don't specify any, the default collation of the SQL Server instance is used.

The name of the collation that you use shows that it uses the Latin1 code page 1, is case insensitive (CI) and accent sensitive (AS). This collation is used in the USA, so it will contain sorting rules that are used in the USA.

The collation decides how text values are compared for equality and likeness, and how they are compared when sorting. The code page is used when storing non-unicode data, e.g. varchar fields.

How to determine the screen width in terms of dp or dip at runtime in Android?

Try this:

Display display   = getWindowManager().getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
int width  = displaySize.x;
int height = displaySize.y;

Python Replace \\ with \

In Python string literals, backslash is an escape character. This is also true when the interactive prompt shows you the value of a string. It will give you the literal code representation of the string. Use the print statement to see what the string actually looks like.

This example shows the difference:

>>> '\\'
'\\'
>>> print '\\'
\

How to find a value in an array and remove it by using PHP array functions?

The unset array_search has some pretty terrible side effects because it can accidentally strip the first element off your array regardless of the value:

        // bad side effects
        $a = [0,1,2,3,4,5];
        unset($a[array_search(3, $a)]);
        unset($a[array_search(6, $a)]);
        $this->log_json($a);
        // result: [1,2,4,5]
        // what? where is 0?
        // it was removed because false is interpreted as 0

        // goodness
        $b = [0,1,2,3,4,5];
        $b = array_diff($b, [3,6]);
        $this->log_json($b);
        // result: [0,1,2,4,5]

If you know that the value is guaranteed to be in the array, go for it, but I think the array_diff is far safer. (I'm using php7)

Add an object to a python list

while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy

How to get child process from parent process

You can get the pids of all child processes of a given parent process <pid> by reading the /proc/<pid>/task/<tid>/children entry.

This file contain the pids of first level child processes.

For more information head over to https://lwn.net/Articles/475688/

How do I load a PHP file into a variable?

ob_start();
include "yourfile.php";
$myvar = ob_get_clean();

ob_get_clean()

How to check if an option is selected?

If you're not familiar or comfortable with is(), you could just check the value of prop("selected").

As seen here:

$('#mySelectBox option').each(function() {
    if ($(this).prop("selected") == true) {
       // do something
    } else {
       // do something
    }
});?

Edit:

As @gdoron pointed out in the comments, the faster and most appropriate way to access the selected property of an option is via the DOM selector. Here is the fiddle update displaying this action.

if (this.selected == true) {

appears to work just as well! Thanks gdoron.

How do I run two commands in one line in Windows CMD?

One more example: For example, when we use the gulp build system, instead of

gulp - default > build

gulp build - build build-folder

gulp watch - start file-watch

gulp dist - build dist-folder

We can do that with one line:

cd c:\xampp\htdocs\project & gulp & gulp watch

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

make clean generally only cleans built files in the directory containing the source code itself, and rarely touches any installed software.

Makefiles generally don't contain a target for uninstallation -- you usually have to do that yourself, by removing the files from the directory into which they were installed. For example, if you built a program and installed it (using make install) into /usr/local, you'd want to look through /usr/local/bin, /usr/local/libexec, /usr/local/share/man, etc., and remove the unwanted files. Sometimes a Makefile includes an uninstall target, but not always.

Of course, typically on a Linux system you install software using a package manager, which is capable of uninstalling software "automagically".

equivalent of vbCrLf in c#

Add a reference to Microsoft.VisualBasic to your project.

Then insert the using statement

using Microsoft.VisualBasic;

Use the defined constant vbCrLf:

private const string myString = "abc" + Constants.vbCrLf;

How to empty/destroy a session in rails?

session in rails is a hash object. Hence any function available for clearing hash will work with sessions.

session.clear

or if specific keys have to be destroyed:

session.delete(key)

Tested in rails 3.2

added

People have mentioned by session={} is a bad idea. Regarding session.clear, Lobati comments- It looks like you're probably better off using reset_session [than session.clear], as it does some other cleaning up beyond what session.clear does. Internally, reset_session calls session.destroy, which itself calls clear as well some other stuff.

Using column alias in WHERE clause of MySQL query produces an error

Standard SQL (or MySQL) does not permit the use of column aliases in a WHERE clause because

when the WHERE clause is evaluated, the column value may not yet have been determined.

(from MySQL documentation). What you can do is calculate the column value in the WHERE clause, save the value in a variable, and use it in the field list. For example you could do this:

SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
@postcode AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE (@postcode := SUBSTRING(`locations`.`raw`,-6,4)) NOT IN
(
 SELECT `postcode` FROM `postcodes` WHERE `region` IN
 (
  'australia'
 )
)

This avoids repeating the expression when it grows complicated, making the code easier to maintain.

LIMIT 10..20 in SQL Server

Unfortunately, the ROW_NUMBER() is the best you can do. It's actually more correct, because the results of a limit or top clause don't really have meaning without respect to some specific order. But it's still a pain to do.

Update: Sql Server 2012 adds a limit -like feature via OFFSET and FETCH keywords. This is the ansi-standard approach, as opposed to LIMIT, which is a non-standard MySql extension.

Testing the type of a DOM element in JavaScript

You can use typeof(N) to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.

In that case, use the elem.tagName or elem.nodeName property.

if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.

Conditionally formatting cells if their value equals any value of another column

I unable to comment on the top answer, but Excel actually lets you do this without adding the ugly conditional logic.

Conditional formatting is automatically applied to any input that isn't an error, so you can achieve the same effect as:

=NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))

With this:

= MATCH(A1,$B$1:$B$1000,0)))

If the above is applied to your data, A1 will be formatted if it matches any cell in $B$1:$B$1000, as any non-match will return an error.

Read user input inside a loop

It looks like you read twice, the read inside the while loop is not needed. Also, you don't need to invoke the cat command:

while read input
do
    echo $input
done < filename

Adding a SVN repository in Eclipse

I doubt that Subclipse and then SVN can use your Eclipse proxy settings. You'll probably need to set the proxy for your SVN program itself. Trying to check out the files using SVN from the command line should tell you if that works.

If SVN can't connect either then put the proxy settings in your servers file in your Subversion settings folder (in your home folder).

If it can't do it even with the proxy settings set, then your firewall is probably blocking the methods and protocols that Subversion needs to use to download the files.

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

You need to provide a candidate for autowire. That means that an instance of PasswordHint must be known to spring in a way that it can guess that it must reference it.

Please provide the class head of PasswordHint and/or the spring bean definition of that class for further assistance.

Try changing the name of

PasswordHintAction action;

to

PasswordHintAction passwordHintAction;

so that it matches the bean definition.

MySQL: Can't create table (errno: 150)

In most of the cases the problem is because of the ENGINE dIfference .If the parent is created by InnoDB then the referenced tables supposed to be created by MyISAM & vice versa

WhatsApp API (java/python)

WhatsApp Inc. does not provide an open API but a reverse-engineered library is made available on GitHub by the team Venomous on the GitHub. This however according to my knowledge is made possible in PHP. You can check the link here: https://github.com/venomous0x/WhatsAPI

Hope this helps

How can I clear the content of a file?

This is what I did to clear the contents of the file without creating a new file as I didn't want the file to display new time of creation even when the application just updated its contents.

FileStream fileStream = File.Open(<path>, FileMode.Open);

/* 
 * Set the length of filestream to 0 and flush it to the physical file.
 *
 * Flushing the stream is important because this ensures that
 * the changes to the stream trickle down to the physical file.
 * 
 */
fileStream.SetLength(0);
fileStream.Close(); // This flushes the content, too.

In Python, what does dict.pop(a,b) mean?

def func(*args): 
    pass

When you define a function this way, *args will be array of arguments passed to the function. This allows your function to work without knowing ahead of time how many arguments are going to be passed to it.

You do this with keyword arguments too, using **kwargs:

def func2(**kwargs): 
    pass

See: Arbitrary argument lists


In your case, you've defined a class which is acting like a dictionary. The dict.pop method is defined as pop(key[, default]).

Your method doesn't use the default parameter. But, by defining your method with *args and passing *args to dict.pop(), you are allowing the caller to use the default parameter.

In other words, you should be able to use your class's pop method like dict.pop:

my_a = a()
value1 = my_a.pop('key1')       # throw an exception if key1 isn't in the dict
value2 = my_a.pop('key2', None) # return None if key2 isn't in the dict

Looping through a hash, or using an array in PowerShell

I prefer this variant on the enumerator method with a pipeline, because you don't have to refer to the hash table in the foreach (tested in PowerShell 5):

$hash = @{
    'a' = 3
    'b' = 2
    'c' = 1
}
$hash.getEnumerator() | foreach {
    Write-Host ("Key = " + $_.key + " and Value = " + $_.value);
}

Output:

Key = c and Value = 1
Key = b and Value = 2
Key = a and Value = 3

Now, this has not been deliberately sorted on value, the enumerator simply returns the objects in reverse order.

But since this is a pipeline, I now can sort the objects received from the enumerator on value:

$hash.getEnumerator() | sort-object -Property value -Desc | foreach {
  Write-Host ("Key = " + $_.key + " and Value = " + $_.value);
}

Output:

Key = a and Value = 3
Key = b and Value = 2
Key = c and Value = 1

What is best way to start and stop hadoop ecosystem, with command line?

Starting

start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)

Stopping

stop-dfs.sh
stop-mapred.sh

Type converting slices of interfaces

In case you need more shorting your code, you can creating new type for helper

type Strings []string

func (ss Strings) ToInterfaceSlice() []interface{} {
    iface := make([]interface{}, len(ss))
    for i := range ss {
        iface[i] = ss[i]
    }
    return iface
}

then

a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()

Is Unit Testing worth the effort?

I do not know. A lot of places do not do unit test, but the quality of the code is good. Microsoft does unit test, but Bill Gates gave a blue screen at his presentation.

Convert String to Carbon

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

How to sort strings in JavaScript

Use sort() straight forward without any - or <

_x000D_
_x000D_
const areas = ['hill', 'beach', 'desert', 'mountain']
console.log(areas.sort())

// To print in descending way
console.log(areas.sort().reverse())
_x000D_
_x000D_
_x000D_

How do I alter the position of a column in a PostgreSQL database table?

There are some workarounds to make it possible:

  1. Recreating the whole table

  2. Create new columns within the current table

  3. Create a view

https://tableplus.com/blog/2018/09/postgresql-is-it-possible-to-alter-column-order-position-in-a-table.html

Avoid dropdown menu close on click inside

Bootstrap 4

$('.dropdown-menu[data-handledropdownclose="true"]').on("click.bs.dropdown", function (e) {
    if ($(this).parent().hasClass("show")) {
        var target = $(e.target);

        if (!(target.hasClass("CloseDropDown") || target.parents(".CloseDropDown").length)) {
            e.stopPropagation();
        }
    }
});

<div class="dropdown">
    <button type="button" class="btn-no-border dropdown-toggle" data-toggle="dropdown">
        <img src="~/Content/CSS/CssImages/Icons/usr_icon.png" alt="" title="language" class="float-right" />
    </button>

    <div class="dropdown-menu profile-menu-logout" data-handledropdownclose="true">
        <div class="prof-name">
            <i class="fa fa-user"></i> Hello World
        </div>

        <hr />

        <div>
            <a href="/Test/TestAction" class="CloseDropDown">
                <i class="fa fa-briefcase"></i>
                <span>Test Action</span>
            </a>
        </div>

        <div>
            <nav>
                <ul class="nav-menu-prof padding-0">
                    <li class="menu-has-children">
                        <a href="#">
                            <span class="cyan-text-color">
                                Test 2
                            </span>
                        </a>

                        <ul id="ulList" class="padding-0 pad-left-25">
                            <li>
                                <a href="/Test/Test2" class="action currentmenu"> Test 1 </a>
                                <a href="/Test/Test2" class="action CloseDropDown"> Test 2 </a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </nav>
        </div>

        <div>
            <a href="/Account/Logout" class="cyan-text-color CloseDropDown">
                <i class="fa fa-power-off"></i>
                <span>Logout</span>
            </a>
        </div>
    </div>
</div>

how to set font size based on container size?

I had a similar issue but I had to consider other issues that @apaul34208 example did not tackle. In my case;

  • I have a container that changed size depending on the viewport using media queries
  • Text inside is dynamically generated
  • I want to scale up as well as down

Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (https://lodash.com/)

_x000D_
_x000D_
var TextFit = function(){_x000D_
 var container = $('.container');_x000D_
  container.each(function(){_x000D_
    var container_width = $(this).width(),_x000D_
      width_offset = parseInt($(this).data('width-offset')),_x000D_
        font_container = $(this).find('.font-container');_x000D_
 _x000D_
     if ( width_offset > 0 ) {_x000D_
         container_width -= width_offset;_x000D_
     }_x000D_
                _x000D_
    font_container.each(function(){_x000D_
      var font_container_width = $(this).width(),_x000D_
          font_size = parseFloat( $(this).css('font-size') );_x000D_
_x000D_
      var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);_x000D_
 _x000D_
      var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );_x000D_
      _x000D_
      if (diff_percentage !== 0){_x000D_
          if ( container_width > font_container_width ) {_x000D_
            new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          } else if ( container_width < font_container_width ) {_x000D_
            new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          }_x000D_
      }_x000D_
      $(this).css('font-size', new_font_size + 'px');_x000D_
    });_x000D_
  });_x000D_
}_x000D_
_x000D_
$(function(){_x000D_
  TextFit();_x000D_
  $(window).resize(function(){_x000D_
   TextFit();_x000D_
  });_x000D_
});
_x000D_
.container {_x000D_
  width:341px;_x000D_
  height:341px;_x000D_
  background-color:#000;_x000D_
  padding:20px;_x000D_
 }_x000D_
 .font-container {_x000D_
  font-size:131px;_x000D_
  text-align:center;_x000D_
  color:#fff;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container" data-width-offset="10">_x000D_
 <span class="font-container">£5000</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/Merch80/b8hoctfb/7/

Find the differences between 2 Excel worksheets?

I used Excel Compare. It is payware, but they do have a 15 day trial. It will report amended rows, added rows, and deleted rows. It will match based on the worksheet name (as an option):

http://www.formulasoft.com/excel-compare.html

How to determine when a Git branch was created?

As pointed out in the comments and in Jackub's answer, as long as your branch is younger than the number of days set in the config setting gc.reflogexpire (the default is 90 days), then you can utilize your reflog to find out when a branch reference was first created.

Note that git reflog can take most git log flags. Further note that the HEAD@{0} style selectors are effectively notions of time and, in fact, are handled (in a hacked sort of way) as date strings. This means that you can use the flag --date=local and get output like this:

$ git reflog --date=local
763008c HEAD@{Fri Aug 20 10:09:18 2010}: pull : Fast-forward
f6cec0a HEAD@{Tue Aug 10 09:37:55 2010}: pull : Fast-forward
e9e70bc HEAD@{Thu Feb 4 02:51:10 2010}: pull : Fast forward
836f48c HEAD@{Thu Jan 21 14:08:14 2010}: checkout: moving from master to master
836f48c HEAD@{Thu Jan 21 14:08:10 2010}: pull : Fast forward
24bc734 HEAD@{Wed Jan 20 12:05:45 2010}: checkout: moving from 74fca6a42863ffacaf7ba6f1936a9f228950f657 
74fca6a HEAD@{Wed Jan 20 11:55:43 2010}: checkout: moving from master to v2.6.31
24bc734 HEAD@{Wed Jan 20 11:44:42 2010}: pull : Fast forward
964fe08 HEAD@{Mon Oct 26 15:29:29 2009}: checkout: moving from 4a6908a3a050aacc9c3a2f36b276b46c0629ad91 
4a6908a HEAD@{Mon Oct 26 14:52:12 2009}: checkout: moving from master to v2.6.28

It may also be useful at times to use --date=relative:

$ git reflog --date=relative
763008c HEAD@{4 weeks ago}: pull : Fast-forward
f6cec0a HEAD@{6 weeks ago}: pull : Fast-forward
e9e70bc HEAD@{8 months ago}: pull : Fast forward
836f48c HEAD@{8 months ago}: checkout: moving from master to master
836f48c HEAD@{8 months ago}: pull : Fast forward
24bc734 HEAD@{8 months ago}: checkout: moving from 74fca6a42863ffacaf7ba6f1936a9f228950f657 to master
74fca6a HEAD@{8 months ago}: checkout: moving from master to v2.6.31
24bc734 HEAD@{8 months ago}: pull : Fast forward
964fe08 HEAD@{11 months ago}: checkout: moving from 4a6908a3a050aacc9c3a2f36b276b46c0629ad91 to master
4a6908a HEAD@{11 months ago}: checkout: moving from master to v2.6.28

One last note: the --all flag (which is really a git-log flag understood by git-reflog) will show the reflogs for all known refs in refs/ (instead of simply, HEAD) which will show you branch events clearly:

git reflog --date=local --all
860e4e4 refs/heads/master@{Sun Sep 19 23:00:30 2010}: commit: Second.
17695bc refs/heads/example_branch@{Mon Sep 20 00:31:06 2010}: branch: Created from HEAD

How to Install Sublime Text 3 using Homebrew

brew install caskroom/cask/brew-cask
brew tap caskroom/versions
brew cask install sublime-text

Weird how I will struggle with this for days, post on StackOverflow, then figure out my own answer in 20 seconds.

[edited to reflect that the package name is now just sublime-text, not sublime-text3]

Efficiently test if a port is open on Linux?

If you're using iptables try:

iptables -nL

or

iptables -nL | grep 445

How can I represent an infinite number in Python?

I don't know exactly what you are doing, but float("inf") gives you a float Infinity, which is greater than any other number.

<button> vs. <input type="button" />. Which to use?

There is a big difference if you are using jQuery. jQuery is aware of more events on inputs than it does on buttons. On buttons, jQuery is only aware of 'click' events. On inputs, jQuery is aware of 'click', 'focus', and 'blur' events.

You could always bind events to your buttons as needed, but just be aware that the events that jQuery automatically is aware of are different. For example, if you created a function that was executed whenever there was a 'focusin' event on your page, an input would trigger the function but a button would not.

How do I do a HTTP GET in Java?

The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.

MINGW64 "make build" error: "bash: make: command not found"

You can also use Chocolatey.

Having it installed, just run:

choco install make

When it finishes, it is installed and available in Git for Bash / MinGW.

How to see the changes between two commits without commits in-between?

Asking for the difference /between/ two commits without including the commits in-between makes little sense. Commits are just snapshots of the contents of the repository; asking for the difference between two necessarily includes them. So the question then is, what are you really looking for?

As William suggested, cherry-picking can give you the delta of a single commit rebased on top of another. That is:

$ git checkout 012345
$ git cherry-pick -n abcdef
$ git diff --cached

This takes commit 'abcdef', compares it to its immediate ancestor, then applies that difference on top of '012345'. This new difference is then shown - the only change is the context comes from '012345' rather than 'abcdef's immediate ancestor. Of course, you may get conflicts and etc, so it's not a very useful process in most cases.

If you're just interested in abcdef itself, you can do:

$ git log -u -1 abcdef

This compares abcdef to its immediate ancestor, alone, and is usually what you want.

And of course

$ git diff 012345..abcdef

gives you all differences between those two commits.

It would help to get a better idea of what you're trying to achieve - as I mentioned, asking for the difference between two commits without what's in between doesn't actually make sense.

SQL/mysql - Select distinct/UNIQUE but return all columns?

SELECT DISTINCT FIELD1, FIELD2, FIELD3 FROM TABLE1 works if the values of all three columns are unique in the table.

If, for example, you have multiple identical values for first name, but the last name and other information in the selected columns is different, the record will be included in the result set.

How do you make an anchor link non-clickable or disabled?

Jason MacDonald comments worked for me, tested in Chrome, Mozila and IE.

Added gray color to show disable effect.

.disable_a_href{
    pointer-events: none;
    **color:#c0c0c0 !important;**
}

Jquery was selecting only first element in the anchor list, added meta character (*) to select and disable all element with id #ThisLink.

$("#ThisLink*").addClass("disable_a_href"); 

How to use a WSDL

In visual studio.

  • Create or open a project.
  • Right-click project from solution explorer.
  • Select "Add service refernce"
  • Paste the address with WSDL you received.
  • Click OK.

If no errors, you should be able to see the service reference in the object browser and all related methods.

Python data structure sort list alphabetically

Python has a built-in function called sorted, which will give you a sorted list from any iterable you feed it (such as a list ([1,2,3]); a dict ({1:2,3:4}, although it will just return a sorted list of the keys; a set ({1,2,3,4); or a tuple ((1,2,3,4))).

>>> x = [3,2,1]
>>> sorted(x)
[1, 2, 3]
>>> x
[3, 2, 1]

Lists also have a sort method that will perform the sort in-place (x.sort() returns None but changes the x object) .

>>> x = [3,2,1]
>>> x.sort()
>>> x
[1, 2, 3]

Both also take a key argument, which should be a callable (function/lambda) you can use to change what to sort by.
For example, to get a list of (key,value)-pairs from a dict which is sorted by value you can use the following code:

>>> x = {3:2,2:1,1:5}
>>> sorted(x.items(), key=lambda kv: kv[1])  # Items returns a list of `(key,value)`-pairs
[(2, 1), (3, 2), (1, 5)]

You can't specify target table for update in FROM clause

In Mysql, you can not update one table by subquery the same table.

You can separate the query in two parts, or do

 UPDATE TABLE_A AS A
 INNER JOIN TABLE_A AS B ON A.field1 = B.field1
 SET field2 = ? 

How to count occurrences of a column value efficiently in SQL?

select s.id, s.age, c.count
from students s
inner join (
    select age, count(*) as count
    from students
    group by age
) c on s.age = c.age
order by id

What is the difference between char s[] and char *s?

An example to the difference:

printf("hello" + 2); //llo
char a[] = "hello" + 2; //error

In the first case pointer arithmetics are working (arrays passed to a function decay to pointers).

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

Replace NA with 0 in a data frame column

Since nobody so far felt fit to point out why what you're trying doesn't work:

  1. NA == NA doesn't return TRUE, it returns NA (since comparing to undefined values should yield an undefined result).
  2. You're trying to call apply on an atomic vector. You can't use apply to loop over the elements in a column.
  3. Your subscripts are off - you're trying to give two indices into a$x, which is just the column (an atomic vector).

I'd fix up 3. to get to a$x[is.na(a$x)] <- 0

Scanning Java annotations at runtime

There's a wonderful comment by zapp that sinks in all those answers:

new Reflections("my.package").getTypesAnnotatedWith(MyAnnotation.class)

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

You can also specify the range with the coord_cartesian command to set the y-axis range that you want, an like in the previous post use scales = free_x

p <- ggplot(plot, aes(x = pred, y = value)) +
     geom_point(size = 2.5) +
     theme_bw()+
     coord_cartesian(ylim = c(-20, 80))
p <- p + facet_wrap(~variable, scales = "free_x")
p

enter image description here

Setting default value in select drop-down using Angularjs

$scope.item = {
    "id": "3",
    "name": "ALL",
};

$scope.CategoryLst = [
    { id: '1', name: 'MD' },
    { id: '2', name: 'CRNA' },
    { id: '3', name: 'ALL' }];

<select ng-model="item.id" ng-selected="3" ng-options="i.id as i.name for i in CategoryLst"></select>

How to get rid of blank pages in PDF exported from SSRS

I've successfully used pdftk to remove pages I didn't want/need in pdfs. You can download the program here

You might try something like the following. Taken from here under examples

Remove 'page 13' from in1.pdf to create out1.pdf pdftk in.pdf cat 1-12 14-end output out1.pdf

or:

pdftk A=in1.pdf cat A1-12 A14-end output out1.pdf

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

Why controllers are needed

The difference between link and controller comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.

From the docs:

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

Say you want to have two directives my-form and my-text-input and you want my-text-input directive to appear only inside my-form and nowhere else.

In that case, you will say while defining the directive my-text-input that it requires a controller from the parent DOM element using the require argument, like this: require: '^myForm'. Now the controller from the parent element will be injected into the link function as the fourth argument, following $scope, element, attributes. You can call functions on that controller and communicate with the parent directive.

Moreover, if such a controller is not found, an error will be raised.

Why use link at all

There is no real need to use the link function if one is defining the controller since the $scope is available on the controller. Moreover, while defining both link and controller, one does need to be careful about the order of invocation of the two (controller is executed before).

However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers is usually done in the link function while the API for children and $scope manipulation is done in the controller. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive state and link function will maintain the DOM + outside bindings).

Disable browser cache for entire ASP.NET website

You can try below code in Global.asax file.

protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
        Response.Cache.SetNoStore();
    }

Check if multiple strings exist in another string

It depends on the context suppose if you want to check single literal like(any single word a,e,w,..etc) in is enough

original_word ="hackerearcth"
for 'h' in original_word:
      print("YES")

if you want to check any of the character among the original_word: make use of

if any(your_required in yourinput for your_required in original_word ):

if you want all the input you want in that original_word,make use of all simple

original_word = ['h', 'a', 'c', 'k', 'e', 'r', 'e', 'a', 'r', 't', 'h']
yourinput = str(input()).lower()
if all(requested_word in yourinput for requested_word in original_word):
    print("yes")

Printf long long int in C with GCC?

Try to update your compiler, I'm using GCC 4.7 on Windows 7 Starter x86 with MinGW and it compiles fine with the same options both in C99 and C11.

How to perform OR condition in django queryset?

Both options are already mentioned in the existing answers:

from django.db.models import Q
q1 = User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

and

q2 = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)

However, there seems to be some confusion regarding which one is to prefer.

The point is that they are identical on the SQL level, so feel free to pick whichever you like!

The Django ORM Cookbook talks in some detail about this, here is the relevant part:


queryset = User.objects.filter(
        first_name__startswith='R'
    ) | User.objects.filter(
    last_name__startswith='D'
)

leads to

In [5]: str(queryset.query)
Out[5]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

and

qs = User.objects.filter(Q(first_name__startswith='R') | Q(last_name__startswith='D'))

leads to

In [9]: str(qs.query)
Out[9]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
 "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
  "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
  "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
  WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

source: django-orm-cookbook


Overlaying a DIV On Top Of HTML 5 Video

Here is a stripped down example, using as little HTML markup as possible.

The Basics

  • The overlay is provided by the :before pseudo element on the .content container.

  • No z-index is required, :before is naturally layered over the video element.

  • The .content container is position: relative so that the position: absolute overlay is positioned in relation to it.

  • The overlay is stretched to cover the entire .content div width with left / right / bottom and left set to 0.

  • The width of the video is controlled by the width of its container with width: 100%

The Demo

_x000D_
_x000D_
.content {
  position: relative;
  width: 500px;
  margin: 0 auto;
  padding: 20px;
}
.content video {
  width: 100%;
  display: block;
}
.content:before {
  content: '';
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
_x000D_
<div class="content">
  <video id="player" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.360p.vp9.webm" autoplay loop muted></video>
</div>
_x000D_
_x000D_
_x000D_

Removing empty rows of a data file in R

Here are some dplyr options:

# sample data
df <- data.frame(a = c('1', NA, '3', NA), b = c('a', 'b', 'c', NA), c = c('e', 'f', 'g', NA))

library(dplyr)

# remove rows where all values are NA:
df %>% filter_all(any_vars(!is.na(.)))
df %>% filter_all(any_vars(complete.cases(.)))  


# remove rows where only some values are NA:
df %>% filter_all(all_vars(!is.na(.)))
df %>% filter_all(all_vars(complete.cases(.)))  

# or more succinctly:
df %>% filter(complete.cases(.))  
df %>% na.omit

# dplyr and tidyr:
library(tidyr)
df %>% drop_na

Remove "Using default security password" on Spring Boot

For Reactive Stack (Spring Webflux, Netty) you either need to exclude ReactiveUserDetailsServiceAutoConfiguration.class

@SpringBootApplication(exclude = {ReactiveUserDetailsServiceAutoConfiguration.class})

Or define ReactiveAuthenticationManager bean (there are different implementations, here is the JWT one example)

@Bean
public ReactiveJwtDecoder jwtDecoder() {
    return new NimbusReactiveJwtDecoder(keySourceUrl);
}
@Bean
public ReactiveAuthenticationManager authenticationManager() {
    return new JwtReactiveAuthenticationManager(jwtDecoder());
}

Is there an easy way to convert Android Application to IPad, IPhone

I'm not sure how helpful this answer is for your current application, but it may prove helpful for the next applications that you will be developing.

As iOS does not use Java like Android, your options are quite limited:

1) if your application is written mostly in C/C++ using JNI, you can write a wrapper and interface it with the iOS (i.e. provide callbacks from iOS to your JNI written function). There may be frameworks out there that help you do this easier, but there's still the problem of integrating the application and adapting it to the framework (and of course the fact that the application has to be written in C/C++).

2) rewrite it for iOS. I don't know whether there are any good companies that do this for you. Also, due to the variety of applications that can be written which can use different services and API, there may not be any software that can port it for you (I guess this kind of software is like a gold mine heh) or do a very good job at that.

3) I think that there are Java->C/C++ converters, but there won't help you at all when it comes to API differences. Also, you may find yourself struggling more to get the converted code working on any of the platforms rather than rewriting your application from scratch for iOS.

The problem depends quite a bit on the services and APIs your application is using. I haven't really look this up, but there may be some APIs that provide certain functionality in Android that iOS doesn't provide.

Using C/C++ and natively compiling it for the desired platform looks like the way to go for Android-iOS-Win7Mobile cross-platform development. This gets you somewhat of an application core/kernel which you can use to do the actual application logic.

As for the OS specific parts (APIs) that your application is using, you'll have to set up communication interfaces between them and your application's core.

How do I check if an integer is even or odd?

Here is an answer in Java:

public static boolean isEven (Integer Number) {
    Pattern number = Pattern.compile("^.*?(?:[02]|8|(?:6|4))$");
    String num = Number.toString(Number);
    Boolean numbr = new Boolean(number.matcher(num).matches());
    return numbr.booleanValue();
}

ALTER TABLE to add a composite primary key

You may simply want a UNIQUE CONSTRAINT. Especially if you already have a surrogate key. (example of an already existing surrogate key would be a single column that is an AUTO_INCREMENT )

Below is the sql code for a Unique Constraint

ALTER TABLE `MyDatabase`.`Provider`
    ADD CONSTRAINT CK_Per_Place_Thing_Unique UNIQUE (person,place,thing)
;

Hibernate, @SequenceGenerator and allocationSize

To be absolutely clear... what you describe does not conflict with the spec in any way. The spec talks about the values Hibernate assigns to your entities, not the values actually stored in the database sequence.

However, there is the option to get the behavior you are looking for. First see my reply on Is there a way to dynamically choose a @GeneratedValue strategy using JPA annotations and Hibernate? That will give you the basics. As long as you are set up to use that SequenceStyleGenerator, Hibernate will interpret allocationSize using the "pooled optimizer" in the SequenceStyleGenerator. The "pooled optimizer" is for use with databases that allow an "increment" option on the creation of sequences (not all databases that support sequences support an increment). Anyway, read up about the various optimizer strategies there.

Send a ping to each IP on a subnet

I just came around this question, but the answers did not satisfy me. So i rolled my own:

echo $(seq 254) | xargs -P255 -I% -d" " ping -W 1 -c 1 192.168.0.% | grep -E "[0-1].*?:"
  • Advantage 1: You don't need to install any additional tool
  • Advantage 2: It's fast. It does everything in Parallel with a timout for every ping of 1s ("-W 1"). So it will finish in 1s :)
  • Advantage 3: The output is like this
64 bytes from 192.168.0.16: icmp_seq=1 ttl=64 time=0.019 ms
64 bytes from 192.168.0.12: icmp_seq=1 ttl=64 time=1.78 ms
64 bytes from 192.168.0.21: icmp_seq=1 ttl=64 time=2.43 ms
64 bytes from 192.168.0.1: icmp_seq=1 ttl=64 time=1.97 ms
64 bytes from 192.168.0.11: icmp_seq=1 ttl=64 time=619 ms

Edit: And here is the same as script, for when your xargs do not have the -P flag, as is the case in openwrt (i just found out)

for i in $(seq 255);
do
 ping -W 1 -c 1 10.0.0.$i | grep 'from' &
done

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

$(document).ready(function() {
    $(".tab").click(function () {
        if(!$(this).hasClass('active'))
        {
            $(".tab.active").removeClass("active");
            $(this).addClass("active");        
        }
    });
});

Find out which remote branch a local branch is tracking

I don't know if this counts as parsing the output of git config, but this will determine the URL of the remote that master is tracking:

$ git config remote.$(git config branch.master.remote).url

What's the difference between ".equals" and "=="?

Lets say that "==" operator returns true if both both operands belong to same object but when it will return true as we can't assign a single object multiple values

public static void main(String [] args){
    String s1 = "Hello";
    String s1 = "Hello";  // This is not possible to assign multiple values to single object
    if(s1 == s1){
      // Now this retruns true
   }
}

Now when this happens practically speaking, If its not happen then why this is == compares functionality....

Can I pass parameters by reference in Java?

In Java there is nothing at language level similar to ref. In Java there is only passing by value semantic

For the sake of curiosity you can implement a ref-like semantic in Java simply wrapping your objects in a mutable class:

public class Ref<T> {

    private T value;

    public Ref(T value) {
        this.value = value;
    }

    public T get() {
        return value;
    }

    public void set(T anotherValue) {
        value = anotherValue;
    }

    @Override
    public String toString() {
        return value.toString();
    }

    @Override
    public boolean equals(Object obj) {
        return value.equals(obj);
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }
}

testcase:

public void changeRef(Ref<String> ref) {
    ref.set("bbb");
}

// ...
Ref<String> ref = new Ref<String>("aaa");
changeRef(ref);
System.out.println(ref); // prints "bbb"

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

You should avoid setting LD_LIBRARY_PATH in your .bashrc. See "Why LD_LIBRARY_PATH is bad" for more information.

Use the linker option -rpath while linking so that the dynamic linker knows where to find libsync.so during runtime.

gcc ... -Wl,-rpath /path/to/library -L/path/to/library -lsync -o sync_test

EDIT:

Another way would be to use a wrapper like this

#!/bin/bash

LD_LIBRARY_PATH=/path/to/library sync_test "$@"

If sync_test starts any other programs, they might end up using the libs in /path/to/library which may or may not be intended.

How to check ASP.NET Version loaded on a system?

You can use

<%
Response.Write("Version: " + System.Environment.Version.ToString());
%>

That will get the currently running version. You can check the registry for all installed versions at:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP

Remove old Fragment from fragment manager

You need to find reference of existing Fragment and remove that fragment using below code. You need add/commit fragment using one tag ex. "TAG_FRAGMENT".

Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
    getSupportFragmentManager().beginTransaction().remove(fragment).commit();

That is it.

How to mount host volumes into docker containers in Dockerfile during build

There is a way to mount a volume during a build, but it doesn't involve Dockerfiles.

The technique would be to create a container from whatever base you wanted to use (mounting your volume(s) in the container with the -v option), run a shell script to do your image building work, then commit the container as an image when done.

Not only will this leave out the excess files you don't want (this is good for secure files as well, like SSH files), it also creates a single image. It has downsides: the commit command doesn't support all of the Dockerfile instructions, and it doesn't let you pick up when you left off if you need to edit your build script.

UPDATE:

For example,

CONTAINER_ID=$(docker run -dit ubuntu:16.04)
docker cp build.sh $CONTAINER_ID:/build.sh
docker exec -t $CONTAINER_ID /bin/sh -c '/bin/sh /build.sh'
docker commit $CONTAINER_ID $REPO:$TAG
docker stop $CONTAINER_ID

An unhandled exception occurred during the execution of the current web request. ASP.NET

Here is the code with line 156, it has try and catch above it

    /// <summary>
    /// Execute a SQL Query statement, using the default SQL connection for the application
    /// </summary>
    /// <param name="query">SQL query to execute</param>
    /// <returns>DataTable of results</returns>
    public static DataTable Query(string query)
    {
        DataTable results = new DataTable();
        string configConnectionString = "ApplicationServices";

        System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
        System.Configuration.ConnectionStringSettings connString;

        if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
        {
            connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];

            if (connString != null)
            {
                try
                {
                    using (SqlConnection conn = new SqlConnection(connString.ToString()))
                    using (SqlCommand cmd = new SqlCommand(query, conn))
                    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
                        dataAdapter.Fill(results);

                    return results;
                }
                catch (Exception ex)
                {
                    throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
                }
            }
            else
            {
                throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
            }
        }
        else
        {
            throw new SqlException(string.Format("No connection strings found in Web.config file."));
        }
    }

Disable nginx cache for JavaScript files

Remember set sendfile off; or cache headers doesn't work. I use this snipped:

location / {

        index index.php index.html index.htm;
        try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular

        #.s. kill cache. use in dev
        sendfile off;
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
        proxy_no_cache 1;
        proxy_cache_bypass 1; 
    }

Add an index (numeric ID) column to large data frame

Using alternative dplyr package:

library("dplyr") # or library("tidyverse")

df <- df %>% mutate(id = row_number())

Why do we use volatile keyword?

Consider this code,

int some_int = 100;

while(some_int == 100)
{
   //your code
}

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

volatile int some_int = 100; //note the 'volatile' qualifier now!

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.


Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?

API pagination best practices

Option A: Keyset Pagination with a Timestamp

In order to avoid the drawbacks of offset pagination you have mentioned, you can use keyset based pagination. Usually, the entities have a timestamp that states their creation or modification time. This timestamp can be used for pagination: Just pass the timestamp of the last element as the query parameter for the next request. The server, in turn, uses the timestamp as a filter criterion (e.g. WHERE modificationDate >= receivedTimestampParameter)

{
    "elements": [
        {"data": "data", "modificationDate": 1512757070}
        {"data": "data", "modificationDate": 1512757071}
        {"data": "data", "modificationDate": 1512757072}
    ],
    "pagination": {
        "lastModificationDate": 1512757072,
        "nextPage": "https://domain.de/api/elements?modifiedSince=1512757072"
    }
}

This way, you won't miss any element. This approach should be good enough for many use cases. However, keep the following in mind:

  • You may run into endless loops when all elements of a single page have the same timestamp.
  • You may deliver many elements multiple times to the client when elements with the same timestamp are overlapping two pages.

You can make those drawbacks less likely by increasing the page size and using timestamps with millisecond precision.

Option B: Extended Keyset Pagination with a Continuation Token

To handle the mentioned drawbacks of the normal keyset pagination, you can add an offset to the timestamp and use a so-called "Continuation Token" or "Cursor". The offset is the position of the element relative to the first element with the same timestamp. Usually, the token has a format like Timestamp_Offset. It's passed to the client in the response and can be submitted back to the server in order to retrieve the next page.

{
    "elements": [
        {"data": "data", "modificationDate": 1512757070}
        {"data": "data", "modificationDate": 1512757072}
        {"data": "data", "modificationDate": 1512757072}
    ],
    "pagination": {
        "continuationToken": "1512757072_2",
        "nextPage": "https://domain.de/api/elements?continuationToken=1512757072_2"
    }
}

The token "1512757072_2" points to the last element of the page and states "the client already got the second element with the timestamp 1512757072". This way, the server knows where to continue.

Please mind that you have to handle cases where the elements got changed between two requests. This is usually done by adding a checksum to the token. This checksum is calculated over the IDs of all elements with this timestamp. So we end up with a token format like this: Timestamp_Offset_Checksum.

For more information about this approach check out the blog post "Web API Pagination with Continuation Tokens". A drawback of this approach is the tricky implementation as there are many corner cases that have to be taken into account. That's why libraries like continuation-token can be handy (if you are using Java/a JVM language). Disclaimer: I'm the author of the post and a co-author of the library.

Python spacing and aligning strings

Resurrecting another topic, but this may come in handy for some.

With a little bit of inspiration from https://pyformat.info you can build a method to get a Table of Content [TOC] style printout.

# Define parameters
Location = '10-10-10-10'
Revision = 1
District = 'Tower'
MyDate = 'May 16, 2012'
MyUser = 'LOD'
MyTime = '10:15'

# This is just one way to arrange the data
data = [
    ['Location: '+Location, 'Revision:'+str(Revision)],
    ['District: '+District, 'Date: '+MyDate],
    ['User: '+MyUser,'Time: '+MyTime]
]

# The 'Table of Content' [TOC] style print function
def print_table_line(key,val,space_char,val_loc):
    # key:        This would be the TOC item equivalent
    # val:        This would be the TOC page number equivalent
    # space_char: This is the spacing character between key and val (often a dot for a TOC), must be >= 5
    # val_loc:    This is the location in the string where the first character of val would be located

    val_loc = max(5,val_loc)

    if (val_loc <= len(key)):
        # if val_loc is within the space of key, truncate key and
        cut_str =  '{:.'+str(val_loc-4)+'}'
        key = cut_str.format(key)+'...'+space_char

    space_str = '{:'+space_char+'>'+str(val_loc-len(key)+len(str(val)))+'}'
    print(key+space_str.format(str(val)))

# Examples
for d in data:
    print_table_line(d[0],d[1],' ',30)

print('\n')
for d in data:
    print_table_line(d[0],d[1],'_',25)

print('\n')
for d in data:
    print_table_line(d[0],d[1],' ',20)

The resulting output is as follows:

Location: 10-10-10-10         Revision:1
District: Tower               Date: May 16, 2012
User: LOD                     Time: 10:15


Location: 10-10-10-10____Revision:1
District: Tower__________Date: May 16, 2012
User: LOD________________Time: 10:15


Location: 10-10-... Revision:1
District: Tower     Date: May 16, 2012
User: LOD           Time: 10:15

What does $1 mean in Perl?

Since you asked about the capture groups, you might want to know about $+ too... Pretty useful...

use Data::Dumper;
$text = "hiabc ihabc ads byexx eybxx";
while ($text =~ /(hi|ih)abc|(bye|eyb)xx/igs)
{
    print Dumper $+;
}

OUTPUT:
$VAR1 = 'hi';
$VAR1 = 'ih';
$VAR1 = 'bye';
$VAR1 = 'eyb';

Is it possible to wait until all javascript files are loaded before executing javascript code?

Thats work for me:

var jsScripts = [];

jsScripts.push("/js/script1.js" );
jsScripts.push("/js/script2.js" );
jsScripts.push("/js/script3.js" );

$(jsScripts).each(function( index, value ) {
    $.holdReady( true );
    $.getScript( value ).done(function(script, status) {
        console.log('Loaded ' + index + ' : ' + value + ' (' + status + ')');                
        $.holdReady( false );
    });
});

SQL Server String or binary data would be truncated

The issue is quite simple: one or more of the columns in the source query contains data that exceeds the length of its destination column. A simple solution would be to take your source query and execute Max(Len( source col )) on each column. I.e.,

Select Max(Len(TextCol1))
    , Max(Len(TextCol2))
    , Max(Len(TextCol3))
    , ...
From ...

Then compare those lengths to the data type lengths in your destination table. At least one, exceeds its destination column length.

If you are absolutely positive that this should not be the case and do not care if it is not the case, then another solution is to forcibly cast the source query columns to their destination length (which will truncate any data that is too long):

Select Cast(TextCol1 As varchar(...))
    , Cast(TextCol2 As varchar(...))
    , Cast(TextCol3 As varchar(...))
    , ...
From ...

How to get the unix timestamp in C#

You can also use Ticks. I'm coding for Windows Mobile so don't have the full set of methods. TotalSeconds is not available to me.

long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);

or

TimeSpan epochTicks = new TimeSpan(new DateTime(1970, 1, 1).Ticks);
TimeSpan unixTicks = new TimeSpan(DateTime.UtcNow.Ticks) - epochTicks;
double unixTime = unixTicks.TotalSeconds;

How do you get the cursor position in a textarea?

Here is code to get line number and column position

function getLineNumber(tArea) {

    return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}

function getCursorPos() {
    var me = $("textarea[name='documenttext']")[0];
    var el = $(me).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    var ret = pos - prevLine(me);
    alert(ret);

    return ret; 
}

function prevLine(me) {
    var lineArr = me.value.substr(0, me.selectionStart).split("\n");

    var numChars = 0;

    for (var i = 0; i < lineArr.length-1; i++) {
        numChars += lineArr[i].length+1;
    }

    return numChars;
}

tArea is the text area DOM element

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

By any chance have you tried POST vs post? This support article suggests it can cause problems with IIS: http://support.microsoft.com/?id=828726

Recommended way of making React component/div draggable

I implemented react-dnd, a flexible HTML5 drag-and-drop mixin for React with full DOM control.

Existing drag-and-drop libraries didn't fit my use case so I wrote my own. It's similar to the code we've been running for about a year on Stampsy.com, but rewritten to take advantage of React and Flux.

Key requirements I had:

  • Emit zero DOM or CSS of its own, leaving it to the consuming components;
  • Impose as little structure as possible on consuming components;
  • Use HTML5 drag and drop as primary backend but make it possible to add different backends in the future;
  • Like original HTML5 API, emphasize dragging data and not just “draggable views”;
  • Hide HTML5 API quirks from the consuming code;
  • Different components may be “drag sources” or “drop targets” for different kinds of data;
  • Allow one component to contain several drag sources and drop targets when needed;
  • Make it easy for drop targets to change their appearance if compatible data is being dragged or hovered;
  • Make it easy to use images for drag thumbnails instead of element screenshots, circumventing browser quirks.

If these sound familiar to you, read on.

Usage

Simple Drag Source

First, declare types of data that can be dragged.

These are used to check “compatibility” of drag sources and drop targets:

// ItemTypes.js
module.exports = {
  BLOCK: 'block',
  IMAGE: 'image'
};

(If you don't have multiple data types, this libary may not be for you.)

Then, let's make a very simple draggable component that, when dragged, represents IMAGE:

var { DragDropMixin } = require('react-dnd'),
    ItemTypes = require('./ItemTypes');

var Image = React.createClass({
  mixins: [DragDropMixin],

  configureDragDrop(registerType) {

    // Specify all supported types by calling registerType(type, { dragSource?, dropTarget? })
    registerType(ItemTypes.IMAGE, {

      // dragSource, when specified, is { beginDrag(), canDrag()?, endDrag(didDrop)? }
      dragSource: {

        // beginDrag should return { item, dragOrigin?, dragPreview?, dragEffect? }
        beginDrag() {
          return {
            item: this.props.image
          };
        }
      }
    });
  },

  render() {

    // {...this.dragSourceFor(ItemTypes.IMAGE)} will expand into
    // { draggable: true, onDragStart: (handled by mixin), onDragEnd: (handled by mixin) }.

    return (
      <img src={this.props.image.url}
           {...this.dragSourceFor(ItemTypes.IMAGE)} />
    );
  }
);

By specifying configureDragDrop, we tell DragDropMixin the drag-drop behavior of this component. Both draggable and droppable components use the same mixin.

Inside configureDragDrop, we need to call registerType for each of our custom ItemTypes that component supports. For example, there might be several representations of images in your app, and each would provide a dragSource for ItemTypes.IMAGE.

A dragSource is just an object specifying how the drag source works. You must implement beginDrag to return item that represents the data you're dragging and, optionally, a few options that adjust the dragging UI. You can optionally implement canDrag to forbid dragging, or endDrag(didDrop) to execute some logic when the drop has (or has not) occured. And you can share this logic between components by letting a shared mixin generate dragSource for them.

Finally, you must use {...this.dragSourceFor(itemType)} on some (one or more) elements in render to attach drag handlers. This means you can have several “drag handles” in one element, and they may even correspond to different item types. (If you're not familiar with JSX Spread Attributes syntax, check it out).

Simple Drop Target

Let's say we want ImageBlock to be a drop target for IMAGEs. It's pretty much the same, except that we need to give registerType a dropTarget implementation:

var { DragDropMixin } = require('react-dnd'),
    ItemTypes = require('./ItemTypes');

var ImageBlock = React.createClass({
  mixins: [DragDropMixin],

  configureDragDrop(registerType) {

    registerType(ItemTypes.IMAGE, {

      // dropTarget, when specified, is { acceptDrop(item)?, enter(item)?, over(item)?, leave(item)? }
      dropTarget: {
        acceptDrop(image) {
          // Do something with image! for example,
          DocumentActionCreators.setImage(this.props.blockId, image);
        }
      }
    });
  },

  render() {

    // {...this.dropTargetFor(ItemTypes.IMAGE)} will expand into
    // { onDragEnter: (handled by mixin), onDragOver: (handled by mixin), onDragLeave: (handled by mixin), onDrop: (handled by mixin) }.

    return (
      <div {...this.dropTargetFor(ItemTypes.IMAGE)}>
        {this.props.image &&
          <img src={this.props.image.url} />
        }
      </div>
    );
  }
);

Drag Source + Drop Target In One Component

Say we now want the user to be able to drag out an image out of ImageBlock. We just need to add appropriate dragSource to it and a few handlers:

var { DragDropMixin } = require('react-dnd'),
    ItemTypes = require('./ItemTypes');

var ImageBlock = React.createClass({
  mixins: [DragDropMixin],

  configureDragDrop(registerType) {

    registerType(ItemTypes.IMAGE, {

      // Add a drag source that only works when ImageBlock has an image:
      dragSource: {
        canDrag() {
          return !!this.props.image;
        },

        beginDrag() {
          return {
            item: this.props.image
          };
        }
      }

      dropTarget: {
        acceptDrop(image) {
          DocumentActionCreators.setImage(this.props.blockId, image);
        }
      }
    });
  },

  render() {

    return (
      <div {...this.dropTargetFor(ItemTypes.IMAGE)}>

        {/* Add {...this.dragSourceFor} handlers to a nested node */}
        {this.props.image &&
          <img src={this.props.image.url}
               {...this.dragSourceFor(ItemTypes.IMAGE)} />
        }
      </div>
    );
  }
);

What Else Is Possible?

I have not covered everything but it's possible to use this API in a few more ways:

  • Use getDragState(type) and getDropState(type) to learn if dragging is active and use it to toggle CSS classes or attributes;
  • Specify dragPreview to be Image to use images as drag placeholders (use ImagePreloaderMixin to load them);
  • Say, we want to make ImageBlocks reorderable. We only need them to implement dropTarget and dragSource for ItemTypes.BLOCK.
  • Suppose we add other kinds of blocks. We can reuse their reordering logic by placing it in a mixin.
  • dropTargetFor(...types) allows to specify several types at once, so one drop zone can catch many different types.
  • When you need more fine-grained control, most methods are passed drag event that caused them as the last parameter.

For up-to-date documentation and installation instructions, head to react-dnd repo on Github.

Replace characters from a column of a data frame R

Use gsub:

data1$c <- gsub('_', '-', data1$c)
data1

            a b   c
1  0.34597094 a A-B
2  0.92791908 b A-B
3  0.30168772 c A-B
4  0.46692738 d A-B
5  0.86853784 e A-C
6  0.11447618 f A-C
7  0.36508645 g A-C
8  0.09658292 h A-C
9  0.71661842 i A-C
10 0.20064575 j A-C

MySQL set current date in a DATETIME field on insert

Since MySQL 5.6.X you can do this:

ALTER TABLE `schema`.`users` 
CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;

That way your column will be updated with the current timestamp when a new row is inserted, or updated.

If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP in the DEFAULT value field, like so:

enter image description here

http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html

How to filter by IP address in Wireshark?

Match destination: ip.dst == x.x.x.x

Match source: ip.src == x.x.x.x

Match either: ip.addr == x.x.x.x

SQL update statement in C#

This is not a correct method of updating record in SQL:

command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";

You should write it like this:

command.CommandText = "UPDATE Student 
SET Address = @add, City = @cit Where FirstName = @fn and LastName = @add";

Then you add the parameters same as you added them for the insert operation.

Concatenate a list of pandas dataframes together

concat also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe

df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column

review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame

# Gets rows in df where IDs match in the userID column and combines them 

dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])

How to set RelativeLayout layout params in code not in xml?

Just a basic example:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);

params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);

As you can see, this is what you have to do:

  1. Create a RelativeLayout.LayoutParams object.
  2. Use addRule(int) or addRule(int, int) to set the rules. The first method is used to add rules that don't require values.
  3. Set the parameters to the view (in this case, to each button).

How to uncheck a checkbox in pure JavaScript?

You will need to assign an ID to the checkbox:

<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">

and then in JavaScript:

document.getElementById("checkboxId").checked = false;

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

Java IOException "Too many open files"

Although in most general cases the error is quite clearly that file handles have not been closed, I just encountered an instance with JDK7 on Linux that well... is sufficiently ****ed up to explain here.

The program opened a FileOutputStream (fos), a BufferedOutputStream (bos) and a DataOutputStream (dos). After writing to the dataoutputstream, the dos was closed and I thought everything went fine.

Internally however, the dos, tried to flush the bos, which returned a Disk Full error. That exception was eaten by the DataOutputStream, and as a consequence the underlying bos was not closed, hence the fos was still open.

At a later stage that file was then renamed from (something with a .tmp) to its real name. Thereby, the java file descriptor trackers lost track of the original .tmp, yet it was still open !

To solve this, I had to first flush the DataOutputStream myself, retrieve the IOException and close the FileOutputStream myself.

I hope this helps someone.

PHP code to remove everything but numbers

Try this:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.

How to detect READ_COMMITTED_SNAPSHOT is enabled?

  1. As per https://msdn.microsoft.com/en-us/library/ms180065.aspx, "DBCC USEROPTIONS reports an isolation level of 'read committed snapshot' when the database option READ_COMMITTED_SNAPSHOT is set to ON and the transaction isolation level is set to 'read committed'. The actual isolation level is read committed."

  2. Also in SQL Server Management Studio, in database properties under Options->Miscellaneous there is "Is Read Committed Snapshot On" option status

Is there a standard sign function (signum, sgn) in C/C++?

Why use ternary operators and if-else when you can simply do this

#define sgn(x) x==0 ? 0 : x/abs(x)

ImportError: No module named sqlalchemy

Okay,I have re-installed the package via pip even that didn't help. And then I rsync'ed the entire /usr/lib/python-2.7 directory from other working machine with similar configuration to the current machine.It started working. I don't have any idea ,what was wrong with my setup. I see some difference "print sys.path" output earlier and now. but now my issue is resolved by this work around.

EDIT:Found the real solution for my setup. upgrading "sqlalchemy only doesn't solve the issue" I also need to upgrade flask-sqlalchemy that resolved the issue.

Efficient way to update all rows in a table

You could drop any indexes on the table, then do your insert, and then recreate the indexes.

DBCC CHECKIDENT Sets Identity to 0

See also here: http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/06/26/fun-with-dbcc-chekident.aspx

This is documented behavior, why do you run CHECKIDENT if you recreate the table, in that case skip the step or use TRUNCATE (if you don't have FK relationships)

Find a private field with Reflection?

Use BindingFlags.NonPublic and BindingFlags.Instance flags

FieldInfo[] fields = myType.GetFields(
                         BindingFlags.NonPublic | 
                         BindingFlags.Instance);

PHP AES encrypt / decrypt

These are compact methods to encrypt / decrypt strings with PHP using AES256 CBC:

function encryptString($plaintext, $password, $encoding = null) {
    $iv = openssl_random_pseudo_bytes(16);
    $ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext.$iv, hash('sha256', $password, true), true);
    return $encoding == "hex" ? bin2hex($iv.$hmac.$ciphertext) : ($encoding == "base64" ? base64_encode($iv.$hmac.$ciphertext) : $iv.$hmac.$ciphertext);
}

function decryptString($ciphertext, $password, $encoding = null) {
    $ciphertext = $encoding == "hex" ? hex2bin($ciphertext) : ($encoding == "base64" ? base64_decode($ciphertext) : $ciphertext);
    if (!hash_equals(hash_hmac('sha256', substr($ciphertext, 48).substr($ciphertext, 0, 16), hash('sha256', $password, true), true), substr($ciphertext, 16, 32))) return null;
    return openssl_decrypt(substr($ciphertext, 48), "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, substr($ciphertext, 0, 16));
}

Usage:

$enc = encryptString("mysecretText", "myPassword");
$dec = decryptString($enc, "myPassword");

How to insert new cell into UITableView in Swift

Use beginUpdates and endUpdates to insert a new cell when the button clicked.

As @vadian said in comment, begin/endUpdates has no effect for a single insert/delete/move operation

First of all, append data in your tableview array

Yourarray.append([labeltext])  

Then update your table and insert a new row

// Update Table Data
tblname.beginUpdates()
tblname.insertRowsAtIndexPaths([
NSIndexPath(forRow: Yourarray.count-1, inSection: 0)], withRowAnimation: .Automatic)
tblname.endUpdates()

This inserts cell and doesn't need to reload the whole table but if you get any problem with this, you can also use tableview.reloadData()


Swift 3.0

tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: yourArray.count-1, section: 0)], with: .automatic)
tableView.endUpdates()

Objective-C

[self.tblname beginUpdates];
NSArray *arr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:Yourarray.count-1 inSection:0]];
[self.tblname insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tblname endUpdates];

How can I use the python HTMLParser library to extract data from a specific div tag?

class LinksParser(HTMLParser.HTMLParser):
  def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.recording = 0
    self.data = []

  def handle_starttag(self, tag, attributes):
    if tag != 'div':
      return
    if self.recording:
      self.recording += 1
      return
    for name, value in attributes:
      if name == 'id' and value == 'remository':
        break
    else:
      return
    self.recording = 1

  def handle_endtag(self, tag):
    if tag == 'div' and self.recording:
      self.recording -= 1

  def handle_data(self, data):
    if self.recording:
      self.data.append(data)

self.recording counts the number of nested div tags starting from a "triggering" one. When we're in the sub-tree rooted in a triggering tag, we accumulate the data in self.data.

The data at the end of the parse are left in self.data (a list of strings, possibly empty if no triggering tag was met). Your code from outside the class can access the list directly from the instance at the end of the parse, or you can add appropriate accessor methods for the purpose, depending on what exactly is your goal.

The class could be easily made a bit more general by using, in lieu of the constant literal strings seen in the code above, 'div', 'id', and 'remository', instance attributes self.tag, self.attname and self.attvalue, set by __init__ from arguments passed to it -- I avoided that cheap generalization step in the code above to avoid obscuring the core points (keep track of a count of nested tags and accumulate data into a list when the recording state is active).

Why doesn't height: 100% work to expand divs to the screen height?

Try to play around also with the calc and overflow functions

.myClassName {
    overflow: auto;
    height: calc(100% - 1.5em);
}

Foreach loop, determine which is the last iteration of the loop

Improving Daniel Wolf answer even further you could stack on another IEnumerable to avoid multiple iterations and lambdas such as:

var elements = new[] { "A", "B", "C" };
foreach (var e in elements.Detailed())
{
    if (!e.IsLast) {
        Console.WriteLine(e.Value);
    } else {
        Console.WriteLine("Last one: " + e.Value);
    }
}

The extension method implementation:

public static class EnumerableExtensions {
    public static IEnumerable<IterationElement<T>> Detailed<T>(this IEnumerable<T> source)
    {
        if (source == null)
            throw new ArgumentNullException(nameof(source));

        using (var enumerator = source.GetEnumerator())
        {
            bool isFirst = true;
            bool hasNext = enumerator.MoveNext();
            int index = 0;
            while (hasNext)
            {
                T current = enumerator.Current;
                hasNext = enumerator.MoveNext();
                yield return new IterationElement<T>(index, current, isFirst, !hasNext);
                isFirst = false;
                index++;
            }
        }
    }

    public struct IterationElement<T>
    {
        public int Index { get; }
        public bool IsFirst { get; }
        public bool IsLast { get; }
        public T Value { get; }

        public IterationElement(int index, T value, bool isFirst, bool isLast)
        {
            Index = index;
            IsFirst = isFirst;
            IsLast = isLast;
            Value = value;
        }
    }
}

Representing Directory & File Structure in Markdown Syntax

I made a node module to automate this task: mddir

Usage

node mddir "../relative/path/"

To install: npm install mddir -g

To generate markdown for current directory: mddir

To generate for any absolute path: mddir /absolute/path

To generate for a relative path: mddir ~/Documents/whatever.

The md file gets generated in your working directory.

Currently ignores node_modules, and .git folders.

Troubleshooting

If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.

Line endings fix

Get npm bin folder path with:

npm config get prefix

Cd into that folder

brew install dos2unix

dos2unix lib/node_modules/mddir/src/mddir.js

This converts line endings to Unix instead of Dos

Then run as normal with: node mddir "../relative/path/".

Example generated markdown file structure 'directoryList.md'

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js

How to print colored text to the terminal?

For Windows you cannot print to console with colors unless you're using the Win32 API.

For Linux it's as simple as using print, with the escape sequences outlined here:

Colors

For the character to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font:

#

Add a space (" ") after an element using :after

Turns out it needs to be specified via escaped unicode. This question is related and contains the answer.

The solution:

h2:after {
    content: "\00a0";
}

Why am I getting "IndentationError: expected an indented block"?

This is just an indentation problem since Python is very strict when it comes to it.

If you are using Sublime, you can select all, click on the lower right beside 'Python' and make sure you check 'Indent using spaces' and choose your Tab Width to be consistent, then Convert Indentation to Spaces to convert all tabs to spaces.

git: How to ignore all present untracked files?

I came here trying to solve a slightly different problem. Maybe this will be useful to someone else:

I create a new branch feature-a. as part of this branch I create new directories and need to modify .gitignore to suppress some of them. This happens a lot when adding new tools to a project that create various cache folders. .serverless, .terraform, etc.

Before I'm ready to merge that back to master I have something else come up, so I checkout master again, but now git status picks up those suppressed folders again, since the .gitignore hasn't been merged yet.

The answer here is actually simple, though I had to find this blog to figure it out:

Just checkout the .gitignore file from feature-a branch

git checkout feature-a -- feature-a/.gitignore
git add .
git commit -m "update .gitignore from feature-a branch"

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

In my case the sql server version on my localhost is higher than that on the production server and hence some new variables were added to the generated script from the localhost. This caused errors in creating the table in the first place. Since the creation of the table failed, subsequent query on the "NON EXISITING" table also failed. Luckily, in among the long list of the sql errors, I found this "OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF" to be the new varialbe in the script causing my issue. I did a search and replace and the error went away. Hope it helps someone.

Command line tool to dump Windows DLL version?

The listdlls tools from Systernals might do the job: http://technet.microsoft.com/en-us/sysinternals/bb896656.aspx

listdlls -v -d mylib.dll

Search an array for matching attribute

for(var i = 0; i < restaurants.length; i++)
{
  if(restaurants[i].restaurant.food == 'chicken')
  {
    return restaurants[i].restaurant.name;
  }
}

Java AES encryption and decryption

If for a block cipher you're not going to use a Cipher transformation that includes a padding scheme, you need to have the number of bytes in the plaintext be an integral multiple of the block size of the cipher.

So either pad out your plaintext to a multiple of 16 bytes (which is the AES block size), or specify a padding scheme when you create your Cipher objects. For example, you could use:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Unless you have a good reason not to, use a padding scheme that's already part of the JCE implementation. They've thought out a number of subtleties and corner cases you'll have to realize and deal with on your own otherwise.


Ok, your second problem is that you are using String to hold the ciphertext.

In general,

String s = new String(someBytes);
byte[] retrievedBytes = s.getBytes();

will not have someBytes and retrievedBytes being identical.

If you want/have to hold the ciphertext in a String, base64-encode the ciphertext bytes first and construct the String from the base64-encoded bytes. Then when you decrypt you'll getBytes() to get the base64-encoded bytes out of the String, then base64-decode them to get the real ciphertext, then decrypt that.

The reason for this problem is that most (all?) character encodings are not capable of mapping arbitrary bytes to valid characters. So when you create your String from the ciphertext, the String constructor (which applies a character encoding to turn the bytes into characters) essentially has to throw away some of the bytes because it can make no sense of them. Thus, when you get bytes out of the string, they are not the same bytes you put into the string.

In Java (and in modern programming in general), you cannot assume that one character = one byte, unless you know absolutely you're dealing with ASCII. This is why you need to use base64 (or something like it) if you want to build strings from arbitrary bytes.

For homebrew mysql installs, where's my.cnf?

You can find where the my.cnf file has been provided by the specific package, e.g.

brew list mysql # or: mariadb

In addition to verify if that file is read, you can run:

sudo fs_usage | grep my.cnf

which will show you filesystem activity in real-time related to that file.

Pull request vs Merge request

They are the same feature

Merge or pull requests are created in a git management application and ask an assigned person to merge two branches. Tools such as GitHub and Bitbucket choose the name pull request since the first manual action would be to pull the feature branch. Tools such as GitLab and Gitorious choose the name merge request since that is the final action that is requested of the assignee. In this article we’ll refer to them as merge requests.

-- https://about.gitlab.com/2014/09/29/gitlab-flow/

MySQL INSERT INTO ... VALUES and SELECT

try this

INSERT INTO TABLE1 (COL1 , COL2,COL3) values
('A STRING' , 5 , (select idTable2 from Table2) )
where ...

Pagination response payload from a RESTful API

ReSTful APIs are consumed primarily by other systems, which is why I put paging data in the response headers. However, some API consumers may not have direct access to the response headers, or may be building a UX over your API, so providing a way to retrieve (on demand) the metadata in the JSON response is a plus.

I believe your implementation should include machine-readable metadata as a default, and human-readable metadata when requested. The human-readable metadata could be returned with every request if you like or, preferably, on-demand via a query parameter, such as include=metadata or include_metadata=true.

In your particular scenario, I would include the URI for each product with the record. This makes it easy for the API consumer to create links to the individual products. I would also set some reasonable expectations as per the limits of my paging requests. Implementing and documenting default settings for page size is an acceptable practice. For example, GitHub's API sets the default page size to 30 records with a maximum of 100, plus sets a rate limit on the number of times you can query the API. If your API has a default page size, then the query string can just specify the page index.

In the human-readable scenario, when navigating to /products?page=5&per_page=20&include=metadata, the response could be:

{
  "_metadata": 
  {
      "page": 5,
      "per_page": 20,
      "page_count": 20,
      "total_count": 521,
      "Links": [
        {"self": "/products?page=5&per_page=20"},
        {"first": "/products?page=0&per_page=20"},
        {"previous": "/products?page=4&per_page=20"},
        {"next": "/products?page=6&per_page=20"},
        {"last": "/products?page=26&per_page=20"},
      ]
  },
  "records": [
    {
      "id": 1,
      "name": "Widget #1",
      "uri": "/products/1"
    },
    {
      "id": 2,
      "name": "Widget #2",
      "uri": "/products/2"
    },
    {
      "id": 3,
      "name": "Widget #3",
      "uri": "/products/3"
    }
  ]
}

For machine-readable metadata, I would add Link headers to the response:

Link: </products?page=5&perPage=20>;rel=self,</products?page=0&perPage=20>;rel=first,</products?page=4&perPage=20>;rel=previous,</products?page=6&perPage=20>;rel=next,</products?page=26&perPage=20>;rel=last

(the Link header value should be urlencoded)

...and possibly a custom total-count response header, if you so choose:

total-count: 521

The other paging data revealed in the human-centric metadata might be superfluous for machine-centric metadata, as the link headers let me know which page I am on and the number per page, and I can quickly retrieve the number of records in the array. Therefore, I would probably only create a header for the total count. You can always change your mind later and add more metadata.

As an aside, you may notice I removed /index from your URI. A generally accepted convention is to have your ReST endpoint expose collections. Having /index at the end muddies that up slightly.

These are just a few things I like to have when consuming/creating an API. Hope that helps!

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

You need the Microsoft.AspNet.WebApi.Core package.

You can see it in the .csproj file:

<Reference Include="System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.0.0\lib\net45\System.Web.Http.dll</HintPath>
</Reference>

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

I am using JDK 7 for maven project and I used -Dhttps.protocols=TLSv1.2 as argument in JRE. It has allowed to download all maven repository which were failing earlier.

mysql select from n last rows

because it is autoincrement, here's my take:

Select * from tbl 
where certainconditionshere 
and autoincfield >= (select max(autoincfield) from tbl) - $n

how to get the base url in javascript

var baseTags = document.getElementsByTagName("base");
var basePath = baseTags.length ? 
    baseTags[ 0 ].href.substr( location.origin.length, 999 ) : 
    "";

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

Mocha / Chai expect.to.throw not catching thrown errors

examples from doc... ;)

because you rely on this context:

  • which is lost when the function is invoked by .throw
  • there’s no way for it to know what this is supposed to be

you have to use one of these options:

  • wrap the method or function call inside of another function
  • bind the context

    // wrap the method or function call inside of another function
    expect(function () { cat.meow(); }).to.throw();  // Function expression
    expect(() => cat.meow()).to.throw();             // ES6 arrow function
    
    // bind the context
    expect(cat.meow.bind(cat)).to.throw();           // Bind
    

move_uploaded_file gives "failed to open stream: Permission denied" error

If you have Mac OS X, go to the file root or the folder of your website.

Then right-hand click on it, go to get information, go to the very bottom (Sharing & Permissions), open that, change all read-only to read and write. Make sure to open padlock, go to setting icon, and choose Apply to the enclosed items...

Python dictionary get multiple values

If you have pandas installed you can turn it into a series with the keys as the index. So something like

import pandas as pd

s = pd.Series(my_dict)

s[['key1', 'key3', 'key2']]

How to check if a function exists on a SQL database

This is what SSMS uses when you script using the DROP and CREATE option

IF EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                  AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].[foo]

GO 

This approach to deploying changes means that you need to recreate all permissions on the object so you might consider ALTER-ing if Exists instead.

Best solution to protect PHP code without encryption

See our SD PHP Obfuscator. Handles huge systems of PHP files. No runtime requirements on PHP server. No extra runtime overhead.

[EDIT May 2016] A recent answer noted that Zend does not handle PHP5.5. The SD PHP Obfuscator does.

What do curly braces mean in Verilog?

As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]} are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".

{16{a[15]}}

is the same as

{ 
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}

In bit-blasted form,

assign result = {{16{a[15]}}, {a[15:0]}};

is the same as:

assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];

How do I access call log for android?

Before considering making Read Call Log or Read SMS permissions a part of your application I strongly advise you to have a look at this policy of Google Play Market: https://support.google.com/googleplay/android-developer/answer/9047303?hl=en

Those permissions are very sensitive and you will have to prove that your application needs them. But even if it really needs them Google Play Support team may easily reject your request without proper explanations.

This is what happened to me. After providing all the needed information along with the Demonstration video of my application it was rejected with the explanation that my "account is not authorized to provide a certain use case solution in my application" (the list of use cases they may consider as an exception is listed on that Policy page). No link to any policy statement was provided to explain what it all means. Basically they just judged my app as not to go without proper explanation.

I wish you good luck of cause with your applications guys but be careful.

python: changing row index of pandas data frame

followers_df.reset_index()
followers_df.reindex(index=range(0,20))

TypeError: 'NoneType' object is not iterable in Python

Just continue the loop when you get None Exception,

example:

   a = None
   if a is None:
       continue
   else:
       print("do something")

This can be any iterable coming from DB or an excel file.

How do I pass environment variables to Docker containers?

If you are using 'docker-compose' as the method to spin up your container(s), there is actually a useful way to pass an environment variable defined on your server to the Docker container.

In your docker-compose.yml file, let's say you are spinning up a basic hapi-js container and the code looks like:

hapi_server:
  container_name: hapi_server
  image: node_image
  expose:
    - "3000"

Let's say that the local server that your docker project is on has an environment variable named 'NODE_DB_CONNECT' that you want to pass to your hapi-js container, and you want its new name to be 'HAPI_DB_CONNECT'. Then in the docker-compose.yml file, you would pass the local environment variable to the container and rename it like so:

hapi_server:
  container_name: hapi_server
  image: node_image
  environment:
    - HAPI_DB_CONNECT=${NODE_DB_CONNECT}
  expose:
    - "3000"

I hope this helps you to avoid hard-coding a database connect string in any file in your container!

Node.js setting up environment specific configs to be used with everyauth

An elegant way is to use .env file to locally override production settings. No need for command line switches. No need for all those commas and brackets in a config.json file. See my answer here

Example: on my machine the .env file is this:

NODE_ENV=dev
TWITTER_AUTH_TOKEN=something-needed-for-api-calls

My local .env overrides any environment variables. But on the staging or production servers (maybe they're on heroku.com) the environment variables are pre-set to stage NODE_ENV=stage or production NODE_ENV=prod.

What to gitignore from the .idea folder?

For a couple of years I was a supporter of using a specific .gitignore for IntelliJ with this suggested configuration.

Not anymore.

IntelliJ is updated quite frequently, internal config file specs change more often than I would like and JetBrains flagship excels at auto-configuring itself based on maven/gradle/etc build files.

So my suggestion would be to leave all editor config files out of project and have users configure editor to their liking. Things like code styling can and should be configured at build level; say using Google Code Style or CheckStyle directly on Maven/Gradle/sbt/etc.

This ensures consistency and leaves editor files out of source code that, in my personal opinion, is where they should be.

not None test in Python

Either of the latter two, since val could potentially be of a type that defines __eq__() to return true when passed None.

The property 'value' does not exist on value of type 'HTMLElement'

The problem is here:

document.getElementById(elementId).value

You know that HTMLElement returned from getElementById() is actually an instance of HTMLInputElement inheriting from it because you are passing an ID of input element. Similarly in statically typed Java this won't compile:

public Object foo() {
  return 42;
}

foo().signum();

signum() is a method of Integer, but the compiler only knows the static type of foo(), which is Object. And Object doesn't have a signum() method.

But the compiler can't know that, it can only base on static types, not dynamic behaviour of your code. And as far as the compiler knows, the type of document.getElementById(elementId) expression does not have value property. Only input elements have value.

For a reference check HTMLElement and HTMLInputElement in MDN. I guess Typescript is more or less consistent with these.

increase legend font size ggplot2

You can use theme_get() to display the possible options for theme. You can control the legend font size using:

+ theme(legend.text=element_text(size=X))

replacing X with the desired size.

What is "overhead"?

Think about the overhead as the time required to manage the threads and coordinate among them. It is a burden if the thread does not have enough task to do. In such a case the overhead cost over come the saved time through using threading and the code takes more time than the sequential one.

How to keep a Python script output window open?

I had a similar problem. With Notepad++ I used to use the command : C:\Python27\python.exe "$(FULL_CURRENT_PATH)" which closed the cmd window immediately after the code terminated.
Now I am using cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)" which keeps the cmd window open.

Mockito - NullpointerException when stubbing Method

For future readers, another cause for NPE when using mocks is forgetting to initialize the mocks like so:

@Mock
SomeMock someMock;

@InjectMocks
SomeService someService;

@Before
public void setup(){
    MockitoAnnotations.initMocks(this); //without this you will get NPE
}

@Test
public void someTest(){
    Mockito.when(someMock.someMethod()).thenReturn("some result");
   // ...
}

Also make sure you are using JUnit for all annotations. I once accidently created a test with @Test from testNG so the @Before didn't work with it (in testNG the annotation is @BeforeTest)

Why aren't variable-length arrays part of the C++ standard?

If you know the value at compile time you can do the following:

template <int X>
void foo(void)
{
   int values[X];

}

Edit: You can create an a vector that uses a stack allocator (alloca), since the allocator is a template parameter.

SSL Error: CERT_UNTRUSTED while using npm command

Since i stumbled on the post via google:

Try using npm ci it will be much than an npm install.

From the manual:

In short, the main differences between using npm install and npm ci are:

  • The project must have an existing package-lock.json or npm-shrinkwrap.json.
  • If dependencies in the package lock do not match those in package.json, npm ci will exit with an error, instead of updating the package lock.
  • npm ci can only install entire projects at a time: individual dependencies cannot be added with this command.
  • If a node_modules is already present, it will be automatically removed before npm ci begins its install.
  • It will never write to package.json or any of the package-locks: installs are essentially frozen.

What does ':' (colon) do in JavaScript?

It is part of the object literal syntax. The basic format is:

var obj = { field_name: "field value", other_field: 42 };

Then you can access these values with:

obj.field_name; // -> "field value"
obj["field_name"]; // -> "field value"

You can even have functions as values, basically giving you the methods of the object:

obj['func'] = function(a) { return 5 + a;};
obj.func(4);  // -> 9

How to pull specific directory with git

It's not possible. You need pull all repository or nothing.

Zoom to fit: PDF Embedded in HTML

just in case someone need it, in firefox for me it work like this

<iframe src="filename.pdf#zoom=FitH" style="position:absolute;right:0; top:0; bottom:0; width:100%;"></iframe>

Is it possible to delete an object's property in PHP?

unset($a->new_property);

This works for array elements, variables, and object attributes.

Example:

$a = new stdClass();

$a->new_property = 'foo';
var_export($a);  // -> stdClass::__set_state(array('new_property' => 'foo'))

unset($a->new_property);
var_export($a);  // -> stdClass::__set_state(array())

Change key pair for ec2 instance

Once an instance has been started, there is no way to change the keypair associated with the instance at a meta data level, but you can change what ssh key you use to connect to the instance.

There is a startup process on most AMIs that downloads the public ssh key and installs it in a .ssh/authorized_keys file so that you can ssh in as that user using the corresponding private ssh key.

If you want to change what ssh key you use to access an instance, you will want to edit the authorized_keys file on the instance itself and convert to your new ssh public key.

The authorized_keys file is under the .ssh subdirectory under the home directory of the user you are logging in as. Depending on the AMI you are running, it might be in one of:

/home/ec2-user/.ssh/authorized_keys
/home/ubuntu/.ssh/authorized_keys
/root/.ssh/authorized_keys

After editing an authorized_keys file, always use a different terminal to confirm that you are able to ssh in to the instance before you disconnect from the session you are using to edit the file. You don't want to make a mistake and lock yourself out of the instance entirely.

While you're thinking about ssh keypairs on EC2, I recommend uploading your own personal ssh public key to EC2 instead of having Amazon generate the keypair for you.

Here's an article I wrote about this:

Uploading Personal ssh Keys to Amazon EC2
http://alestic.com/2010/10/ec2-ssh-keys

This would only apply to new instances you run.

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

Also, if you're just looking for a specific value nested within the JSON content you can do something like so:

yourJObject.GetValue("jsonObjectName").Value<string>("jsonPropertyName");

And so on from there.

This could help if you don't want to bear the cost of converting the entire JSON into a C# object.

PostgreSQL Autoincrement

If you want to add sequence to id in the table which already exist you can use:

CREATE SEQUENCE user_id_seq;
ALTER TABLE user ALTER user_id SET DEFAULT NEXTVAL('user_id_seq');

T-SQL - function with default parameters

You can call it three ways - with parameters, with DEFAULT and via EXECUTE

SET NOCOUNT ON;

DECLARE
@Table  SYSNAME = 'YourTable',
@Schema SYSNAME = 'dbo',
@Rows   INT;

SELECT dbo.TableRowCount( @Table, @Schema )

SELECT dbo.TableRowCount( @Table, DEFAULT )

EXECUTE @Rows = dbo.TableRowCount @Table

SELECT @Rows

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Can i suggest http://www.jqueryscript.net/form/Twitter-Like-Mentions-Auto-Suggesting-Plugin-with-jQuery-Bootstrap-Suggest.html, works more like the twitter post suggestion where it gives you a list of users or topics based on @ or # tags,

view demo here: http://www.jqueryscript.net/demo/Twitter-Like-Mentions-Auto-Suggesting-Plugin-with-jQuery-Bootstrap-Suggest/

in this one you can easily change the @ and # to anything you want

Event on a disabled input

I would suggest an alternative - use CSS:

input.disabled {
    user-select : none;
    -moz-user-select : none;
    -webkit-user-select : none;
    color: gray;
    cursor: pointer;
}

instead of the disabled attribute. Then, you can add your own CSS attributes to simulate a disabled input, but with more control.

Non greedy (reluctant) regex matching in sed?

Have not yet seen this answer, so here's how you can do this with vi or vim:

vi -c '%s/\(http:\/\/.\{-}\/\).*/\1/ge | wq' file &>/dev/null

This runs the vi :%s substitution globally (the trailing g), refrains from raising an error if the pattern is not found (e), then saves the resulting changes to disk and quits. The &>/dev/null prevents the GUI from briefly flashing on screen, which can be annoying.

I like using vi sometimes for super complicated regexes, because (1) perl is dead dying, (2) vim has a very advanced regex engine, and (3) I'm already intimately familiar with vi regexes in my day-to-day usage editing documents.

Remove a marker from a GoogleMap

Create array with all markers on add in map.

Later, use:

Marker temp = markers.get(markers.size() - 1);
temp.remove();

JVM option -Xss - What does it do exactly?

Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.

List(of String) or Array or ArrayList

Sometimes I don't want to add items to a list when I instantiate it.

Instantiate a blank list

Dim blankList As List(Of String) = New List(Of String)

Add to the list

blankList.Add("Dis be part of me list") 'blankList is no longer blank, but you get the drift

Loop through the list

For Each item in blankList
  ' write code here, for example:
  Console.WriteLine(item)
Next

How to set a header for a HTTP GET request, and trigger file download?

There are two ways to download a file where the HTTP request requires that a header be set.

The credit for the first goes to @guest271314, and credit for the second goes to @dandavis.

The first method is to use the HTML5 File API to create a temporary local file, and the second is to use base64 encoding in conjunction with a data URI.

The solution I used in my project uses the base64 encoding approach for small files, or when the File API is not available, otherwise using the the File API approach.

Solution:

        var id = 123;

        var req = ic.ajax.raw({
            type: 'GET',
            url: '/api/dowloads/'+id,
            beforeSend: function (request) {
                request.setRequestHeader('token', 'token for '+id);
            },
            processData: false
        });

        var maxSizeForBase64 = 1048576; //1024 * 1024

        req.then(
            function resolve(result) {
                var str = result.response;

                var anchor = $('.vcard-hyperlink');
                var windowUrl = window.URL || window.webkitURL;
                if (str.length > maxSizeForBase64 && typeof windowUrl.createObjectURL === 'function') {
                    var blob = new Blob([result.response], { type: 'text/bin' });
                    var url = windowUrl.createObjectURL(blob);
                    anchor.prop('href', url);
                    anchor.prop('download', id+'.bin');
                    anchor.get(0).click();
                    windowUrl.revokeObjectURL(url);
                }
                else {
                    //use base64 encoding when less than set limit or file API is not available
                    anchor.attr({
                        href: 'data:text/plain;base64,'+FormatUtils.utf8toBase64(result.response),
                        download: id+'.bin',
                    });
                    anchor.get(0).click();
                }

            }.bind(this),
            function reject(err) {
                console.log(err);
            }
        );

Note that I'm not using a raw XMLHttpRequest, and instead using ic-ajax, and should be quite similar to a jQuery.ajax solution.

Note also that you should substitute text/bin and .bin with whatever corresponds to the file type being downloaded.

The implementation of FormatUtils.utf8toBase64 can be found here

What causes a java.lang.StackOverflowError

I was having the same issue

Role.java

 @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY,cascade = CascadeType.ALL)
 Set<BusinessUnitMaster> businessUnits =new HashSet<>();

BusinessUnitMaster.java

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(
        name = "BusinessUnitRoles",
        joinColumns = {@JoinColumn(name = "unit_id", referencedColumnName = "record_id")},
        inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "record_id")}
)
private Set<Role> roles=new HashSet<>();

the problem is that when you create BusinessUnitMaster and Role you have to save the object for both sides for RoleService.java

roleRepository.save(role);

for BusinessUnitMasterService.java

businessUnitMasterRepository.save(businessUnitMaster);

Add quotation at the start and end of each line in Notepad++

  1. Put your cursor at the begining of line 1.
  2. click Edit>ColumnEditor. Put " in the text and hit enter.
  3. Repeat 2 but put the cursor at the end of line1 and put ", and hit enter.

Convert interface{} to int

To better understand the type conversion, look at the code below:

package main
import "fmt"
func foo(a interface{}) {
    fmt.Println(a.(int))  // conversion of interface into int
}
func main() {
    var a int = 10
    foo(a)
}

This code executes perfectly and converts interface type to int type

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion. More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.

Going back to your code, this

iAreaId := val.(int)

should work good. If you want to check error occured while conversion, you can also re-write above line as

iAreaId, ok := val.(int)

Text inset for UITextField?

How about an @IBInspectable, @IBDesignable swift class.

@IBDesignable
class TextField: UITextField {
    @IBInspectable var insetX: CGFloat = 6 {
       didSet {
         layoutIfNeeded()
       }
    }
    @IBInspectable var insetY: CGFloat = 6 {
       didSet {
         layoutIfNeeded()
       }
    }

    // placeholder position
    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds , insetX , insetY)
    }

    // text position
    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds , insetX , insetY)
    }
}

You'll see this in your storyboard.

enter image description here

Update - Swift 3

@IBDesignable
class TextField: UITextField {
    @IBInspectable var insetX: CGFloat = 0
    @IBInspectable var insetY: CGFloat = 0

    // placeholder position
    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: insetX, dy: insetY)
    }

    // text position
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: insetX, dy: insetY)
    }
}

How to check if string input is a number?

If you wanted to evaluate floats, and you wanted to accept NaNs as input but not other strings like 'abc', you could do the following:

def isnumber(x):
    import numpy
    try:
        return type(numpy.float(x)) == float
    except ValueError:
        return False

Web scraping with Java

Look at an HTML parser such as TagSoup, HTMLCleaner or NekoHTML.

Row count on the Filtered data

If you try to count the number of rows in the already autofiltered range like this:

Rowz = rnData.SpecialCells(xlCellTypeVisible).Rows.Count

It will only count the number of rows in the first contiguous visible area of the autofiltered range. E.g. if the autofilter range is rows 1 through 10 and rows 3, 5, 6, 7, and 9 are filtered, four rows are visible (rows 2, 4, 8, and 10), but it would return 2 because the first contiguous visible range is rows 1 (the header row) and 2.

A more accurate alternative is this (assuming that ws contains the worksheet with the filtered data):

Rowz = ws.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1

We have to subtract 1 to remove the header row. We need to include the header row in our counted range because SpecialCells will throw an error if no cells are found, which we want to avoid.

The Cells property will give you an accurate count even if the Range has multiple Areas, unlike the Rows property. So we just take the first column of the autofilter range and count the number of visible cells.

Running unittest with typical test directory structure

From the article you linked to:

Create a test_modulename.py file and put your unittest tests in it. Since the test modules are in a separate directory from your code, you may need to add your module’s parent directory to your PYTHONPATH in order to run them:

$ cd /path/to/googlemaps

$ export PYTHONPATH=$PYTHONPATH:/path/to/googlemaps/googlemaps

$ python test/test_googlemaps.py

Finally, there is one more popular unit testing framework for Python (it’s that important!), nose. nose helps simplify and extend the builtin unittest framework (it can, for example, automagically find your test code and setup your PYTHONPATH for you), but it is not included with the standard Python distribution.

Perhaps you should look at nose as it suggests?

What happened to console.log in IE8?

There are so many Answers. My solution for this was:

globalNamespace.globalArray = new Array();
if (typeof console === "undefined" || typeof console.log === "undefined") {
    console = {};
    console.log = function(message) {globalNamespace.globalArray.push(message)};   
}

In short, if console.log doesn't exists (or in this case, isn't opened) then store the log in a global namespace Array. This way, you're not pestered with millions of alerts and you can still view your logs with the developer console opened or closed.

Reading string by char till end of line C/C++

You want to use single quotes:

if(c=='\0')

Double quotes (") are for strings, which are sequences of characters. Single quotes (') are for individual characters.

However, the end-of-line is represented by the newline character, which is '\n'.

Note that in both cases, the backslash is not part of the character, but just a way you represent special characters. Using backslashes you can represent various unprintable characters and also characters which would otherwise confuse the compiler.

if condition in sql server update query

Since you're using SQL 2008:

UPDATE
    table_Name

SET
    column_A  
     = CASE
        WHEN @flag = '1' THEN @new_value
        ELSE 0
    END + column_A,

    column_B  
     = CASE
        WHEN @flag = '0' THEN @new_value
        ELSE 0
    END + column_B 
WHERE
    ID = @ID

If you were using SQL 2012:

UPDATE
    table_Name
SET
    column_A  = column_A + IIF(@flag = '1', @new_value, 0),
    column_B  = column_B + IIF(@flag = '0', @new_value, 0)
WHERE
    ID = @ID

Twitter API returns error 215, Bad Authentication Data

After two days of research I finally found that to access s.o. public tweets you just need any application credentials, and not that particular user ones. So if you are developing for a client, you don't have to ask them to do anything.

To use the new Twitter API 1.1 you need two things:

First, you can (actually have to) create an application with your own credentials and then get the Access token (OAUTH_TOKEN) and Access token secret (OAUTH_TOKEN_SECRET) from the "Your access token" section. Then you supply them in the constructor for the new TwitterOAuth object. Now you can access anyone public tweets.

$connection = new TwitterOAuth( CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET );

$connection->host = "https://api.twitter.com/1.1/"; // change the default
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';

$tweets = $connection->get('http://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='.$username.'&count='.$count);

Actually I think this is what Pavel has suggested also, but it is not so obvious from his answer.

Hope this saves someone else those two days :)

What is the best open XML parser for C++?

try this one: http://www.applied-mathematics.net/tools/xmlParser.html
it's easier and faster than RapidXML or PUGXML.
TinyXML is the worst of the "simple parser".

How can I do an UPDATE statement with JOIN in SQL Server?

MySQL

You'll get the best performance if you forget the where clause and place all conditions in the ON expression.

I think this is because the query first has to join the tables then runs the where clause on that, so if you can reduce what is required to join then that's the fasted way to get the results/do the udpate.

Example

Scenario

You have a table of users. They can log in using their username or email or account_number. These accounts can be active (1) or inactive (0). This table has 50000 rows

You then have a table of users to disable at one go because you find out they've all done something bad. This table however, has one column with usernames, emails and account numbers mixed. It also has a "has_run" indicator which needs to be set to 1 (true) when it has been run

Query

UPDATE users User
    INNER JOIN
        blacklist_users BlacklistUser
        ON
        (
            User.username = BlacklistUser.account_ref
            OR
            User.email = BlacklistedUser.account_ref
            OR
            User.phone_number = BlacklistUser.account_ref
            AND
            User.is_active = 1
            AND
            BlacklistUser.has_run = 0
        )
    SET
        User.is_active = 0,
        BlacklistUser.has_run = 1;

Reasoning

If we had to join on just the OR conditions it would essentially need to check each row 4 times to see if it should join, and potentially return a lot more rows. However, by giving it more conditions it can "skip" a lot of rows if they don't meet all the conditions when joining.

Bonus

It's more readable. All the conditions are in one place and the rows to update are in one place

ROW_NUMBER() in MySQL

Important: Please consider upgrading to MySQL 8+ and use the defined and documented ROW_NUMBER() function, and ditch old hacks tied to a feature limited ancient version of MySQL

Now here's one of those hacks:

The answers here that use in-query variables mostly/all seem to ignore the fact that the documentation says (paraphrase):

Don't rely on items in the SELECT list being evaluated in order from top to bottom. Don't assign variables in one SELECT item and use them in another one

As such, there's a risk they will churn out the wrong answer, because they typically do a

select
  (row number variable that uses partition variable),
  (assign partition variable)

If these are ever evaluated bottom up, the row number will stop working (no partitions)

So we need to use something with a guaranteed order of execution. Enter CASE WHEN:

SELECT
  t.*, 
  @r := CASE 
    WHEN col = @prevcol THEN @r + 1 
    WHEN (@prevcol := col) = null THEN null
    ELSE 1 END AS rn
FROM
  t, 
  (SELECT @r := 0, @prevcol := null) x
ORDER BY col

As outline ld, order of assignment of prevcol is important - prevcol has to be compared to the current row's value before we assign it a value from the current row (otherwise it would be the current rows col value, not the previous row's col value).

Here's how this fits together:

  • The first WHEN is evaluated. If this row's col is the same as the previous row's col then @r is incremented and returned from the CASE. This return led values is stored in @r. It's a feature of MySQL that assignment returns the new value of what is assigned into @r into the result rows.

  • For the first row on the result set, @prevcol is null (it is initialised to null in the subquery) so this predicate is false. This first predicate also returns false every time col changes (current row is different to previous row). This causes the second WHEN to be evaluated.

  • The second WHEN predicate is always false, and it exists purely to assign a new value to @prevcol. Because this row's col is different to the previous row's col (we know this because if it were the same, the first WHEN would have been used), we have to assign the new value to keep it for testing next time. Because the assignment is made and then the result of the assignment is compared with null, and anything equated with null is false, this predicate is always false. But at least evaluating it did its job of keeping the value of col from this row, so it can be evaluated against the next row's col value

  • Because the second WHEN is false, it means in situations where the column we are partitioning by (col) has changed, it is the ELSE that gives a new value for @r, restarting the numbering from 1

We this get to a situation where this:

SELECT
  t.*, 
  ROW_NUMBER() OVER(PARTITION BY pcol1, pcol2, ... pcolX ORDER BY ocol1, ocol2, ... ocolX) rn
FROM
  t

Has the general form:

SELECT
  t.*, 
  @r := CASE 
    WHEN col1 = @pcol1 AND col2 = @pcol2 AND ... AND colX = @pcolX THEN @r + 1 
    WHEN (@pcol1 := pcol1) = null OR (@pcol2 := col2) = null OR ... OR (@pcolX := colX) = null THEN null
    ELSE 1 
  END AS rn
FROM
  t, 
  (SELECT @r := 0, @pcol1 := null, @pcol2 := null, ..., @pcolX := null) x
ORDER BY pcol1, pcol2, ..., pcolX, ocol1, ocol2, ..., ocolX

Footnotes:

  • The p in pcol means "partition", the o in ocol means "order" - in the general form I dropped the "prev" from the variable name to reduce visual clutter

  • The brackets around (@pcolX := colX) = null are important. Without them you'll assign null to @pcolX and things stop working

  • It's a compromise that the result set has to be ordered by the partition columns too, for the previous column compare to work out. You can't thus have your rownumber ordered according to one column but your result set ordered to another You might be able to resolve this with subqueries but I believe the docs also state that subquery ordering may be ignored unless LIMIT is used and this could impact performance

  • I haven't delved into it beyond testing that the method works, but if there is a risk that the predicates in the second WHEN will be optimised away (anything compared to null is null/false so why bother running the assignment) and not executed, it also stops. This doesn't seem to happen in my experience but I'll gladly accept comments and propose solution if it could reasonably occur

  • It may be wise to cast the nulls that create @pcolX to the actual types of your columns, in the subquery that creates the @pcolX variables, viz: select @pcol1 := CAST(null as INT), @pcol2 := CAST(null as DATE)

Sum function in VBA

Range("A10") = WorksheetFunction.Sum(Worksheets("Sheet1").Range("A1", "A9"))

Where

Range("A10") is the answer cell

Range("A1", "A9") is the range to calculate

Java, Check if integer is multiple of a number

Use modulo

whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use

if (j % 4 == 0)