Programs & Examples On #Turnkeylinux.org

How can I perform a short delay in C# without using sleep?

Sorry for awakening an old question like this. But I think what the original author wanted as an answer was:

You need to force your program to make the graphic update after you make the change to the textbox1. You can do that by invoking Update();

textBox1.Text += "\r\nThread Sleeps!";
textBox1.Update();
System.Threading.Thread.Sleep(4000);
textBox1.Text += "\r\nThread awakens!";
textBox1.Update();

Normally this will be done automatically when the thread is done. Ex, you press a button, changes are made to the text, thread dies, and then .Update() is fired and you see the changes. (I'm not an expert so I cant really tell you when its fired, but its something similar to this any way.)

In this case, you make a change, pause the thread, and then change the text again, and when the thread finally dies the .Update() is fired. This resulting in you only seeing the last change made to the text.

You would experience the same issue if you had a long execution between the text changes.

Angular + Material - How to refresh a data source (mat-table)

in my case (Angular 6+), I inherited from MatTableDataSource to create MyDataSource. Without calling after this.data = someArray

this.entitiesSubject.next(this.data as T[])

data where not displayed

class MyDataSource

export class MyDataSource<T extends WhateverYouWant> extends MatTableDataSource<T> {

    private entitiesSubject = new BehaviorSubject<T[]>([]);


    loadDataSourceData(someArray: T[]){
        this.data = someArray //whenever it comes from an API asyncronously or not
        this.entitiesSubject.next(this.data as T[])// Otherwise data not displayed
    }

    public connect(): BehaviorSubject<T[]> {
        return this.entitiesSubject
    }

}//end Class 

How to make the python interpreter correctly handle non-ASCII characters in string operations?

Python 2 uses ascii as the default encoding for source files, which means you must specify another encoding at the top of the file to use non-ascii unicode characters in literals. Python 3 uses utf-8 as the default encoding for source files, so this is less of an issue.

See: http://docs.python.org/tutorial/interpreter.html#source-code-encoding

To enable utf-8 source encoding, this would go in one of the top two lines:

# -*- coding: utf-8 -*-

The above is in the docs, but this also works:

# coding: utf-8

Additional considerations:

  • The source file must be saved using the correct encoding in your text editor as well.

  • In Python 2, the unicode literal must have a u before it, as in s.replace(u"Â ", u"") But in Python 3, just use quotes. In Python 2, you can from __future__ import unicode_literals to obtain the Python 3 behavior, but be aware this affects the entire current module.

  • s.replace(u"Â ", u"") will also fail if s is not a unicode string.

  • string.replace returns a new string and does not edit in place, so make sure you're using the return value as well

datatable jquery - table header width not aligned with body width

Gyrocode.com answer to problem was totally correct but his solution will not work in all cases. A more general approach is to add the following outside your document.ready function:

$(document).on( 'init.dt', function ( e, settings ) {
    var api = new $.fn.dataTable.Api( settings );
    window.setTimeout(function () {
            api.table().columns.adjust().draw();
        },1);
} );

How to access a dictionary key value present inside a list?

To get all the values from a list of dictionaries, use the following code :

list = [{'text': 1, 'b': 2}, {'text': 3, 'd': 4}, {'text': 5, 'f': 6}]
subtitle=[]
for value in list:
   subtitle.append(value['text'])

Select option padding not working in chrome

Very, VERY simple idea, but you can modify it accordingly. This isn't set up to look good, only to provide the idea. Hope it helps.

CSS:

ul {
    width: 50px;
    height: 20px;
    border: 1px solid black;
    display: block;

}

li {
    padding: 5px 0px;
    width: 50px;
    display: none;

}

HTML:

<ul id="customComboBox">
&nbsp
    <li>Test</li>
    <li>Test 2</li>
    <li>Test 3</li>
</ul>

Script:

$(document).ready(function(){
    $("#customComboBox").click(function(){
        $("li").toggle("slow");
    });
});

DEMO

Batch command date and time in file name

You can add leading zeroes to a variable (value up to 99) like this in batch: IF 1%Var% LSS 100 SET Var=0%Var%

So you'd need to parse your date and time components out into separate variables, treat them all like this, then concatenate them back together to create the file name.

However, your underlying method for parsing date and time is dependent on system locale settings. If you're happy for your code not to be portable to other machines, that's probably fine, but if you expect it to work in different international contexts then you'll need a different approach, for example by reading out the registry settings:

HKEY_CURRENT_USER\Control Panel\International\iDate
HKEY_CURRENT_USER\Control Panel\International\iTime
HKEY_CURRENT_USER\Control Panel\International\iTLZero

(That last one controls whether there is a leading zero on times, but not dates as far as I know).

Trigger an action after selection select2

There was made some changes to the select2 events names (I think on v. 4 and later) so the '-' is changed into this ':'.
See the next examples:

$('#select').on("select2:select", function(e) { 
    //Do stuff
});

You can check all the events at the 'select2' plugin site: select2 Events

How can I get an object's absolute position on the page in Javascript?

I would definitely suggest using element.getBoundingClientRect().

https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Summary

Returns a text rectangle object that encloses a group of text rectangles.

Syntax

var rectObject = object.getBoundingClientRect();

Returns

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

Here's a browser compatibility table taken from the linked MDN site:

+---------------+--------+-----------------+-------------------+-------+--------+
|    Feature    | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0    | 3.0 (1.9)       | 4.0               | (Yes) | 4.0    |
+---------------+--------+-----------------+-------------------+-------+--------+

It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/

You can use it like this:

var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();

console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);

Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).

Or here's another one using Chrome's console: Using element.getBoundingClientRect() in Chrome

Note:

I have to mention that the width and height attributes of the getBoundingClientRect() method's return value are undefined in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width, you could subtract the return value's right and left attributes, and for height, you could subtract bottom and top attributes (like this).

What's the fastest way to do a bulk insert into Postgres?

The external file is the best and typical bulk-data

The term "bulk data" is related to "a lot of data", so it is natural to use original raw data, with no need to transform it into SQL. Typical raw data files for "bulk insert" are CSV and JSON formats.

Bulk insert with some transformation

In ETL applications and ingestion processes, we need to change the data before inserting it. Temporary table consumes (a lot of) disk space, and it is not the faster way to do it. The PostgreSQL foreign-data wrapper (FDW) is the best choice.

CSV example. Suppose the tablename (x, y, z) on SQL and a CSV file like

fieldname1,fieldname2,fieldname3
etc,etc,etc
... million lines ...

You can use the classic SQL COPY to load (as is original data) into tmp_tablename, them insert filtered data into tablename... But, to avoid disk consumption, the best is to ingested directly by

INSERT INTO tablename (x, y, z)
  SELECT f1(fieldname1), f2(fieldname2), f3(fieldname3) -- the transforms 
  FROM tmp_tablename_fdw
  -- WHERE condictions
;

You need to prepare database for FDW, and instead static tmp_tablename_fdw you can use a function that generates it:

CREATE EXTENSION file_fdw;
CREATE SERVER import FOREIGN DATA WRAPPER file_fdw;
CREATE FOREIGN TABLE tmp_tablename_fdw(
  ...
) SERVER import OPTIONS ( filename '/tmp/pg_io/file.csv', format 'csv');

JSON example. A set of two files, myRawData1.json and Ranger_Policies2.json can be ingested by:

INSERT INTO tablename (fname, metadata, content)
 SELECT fname, meta, j  -- do any data transformation here
 FROM jsonb_read_files('myRawData%.json')
 -- WHERE any_condiction_here
;

where the function jsonb_read_files() reads all files of a folder, defined by a mask:

CREATE or replace FUNCTION jsonb_read_files(
  p_flike text, p_fpath text DEFAULT '/tmp/pg_io/'
) RETURNS TABLE (fid int,  fname text, fmeta jsonb, j jsonb) AS $f$
  WITH t AS (
     SELECT (row_number() OVER ())::int id, 
           f as fname,
           p_fpath ||'/'|| f as f
     FROM pg_ls_dir(p_fpath) t(f)
     WHERE    f like p_flike
  ) SELECT id,  fname,
         to_jsonb( pg_stat_file(f) ) || jsonb_build_object('fpath',p_fpath),
         pg_read_file(f)::jsonb
    FROM t
$f$  LANGUAGE SQL IMMUTABLE;

Lack of gzip streaming

The most frequent method for "file ingestion" (mainlly in Big Data) is preserving original file on gzip format and transfering it with streaming algorithm, anything that can runs fast and without disc consumption in unix pipes:

 gunzip remote_or_local_file.csv.gz | convert_to_sql | psql 

So ideal (future) is a server option for format .csv.gz.

How do I clone a range of array elements to a new array?

You can do this fairly easially;

    object[] foo = new object[10];
    object[] bar = new object[7];   
    Array.Copy(foo, 3, bar, 0, 7);  

Safe String to BigDecimal conversion

I needed a solution to convert a String to a BigDecimal without knowing the locale and being locale-independent. I couldn't find any standard solution for this problem so i wrote my own helper method. May be it helps anybody else too:

Update: Warning! This helper method works only for decimal numbers, so numbers which always have a decimal point! Otherwise the helper method could deliver a wrong result for numbers between 1000 and 999999 (plus/minus). Thanks to bezmax for his great input!

static final String EMPTY = "";
static final String POINT = '.';
static final String COMMA = ',';
static final String POINT_AS_STRING = ".";
static final String COMMA_AS_STRING = ",";

/**
     * Converts a String to a BigDecimal.
     *     if there is more than 1 '.', the points are interpreted as thousand-separator and will be removed for conversion
     *     if there is more than 1 ',', the commas are interpreted as thousand-separator and will be removed for conversion
     *  the last '.' or ',' will be interpreted as the separator for the decimal places
     *  () or - in front or in the end will be interpreted as negative number
     *
     * @param value
     * @return The BigDecimal expression of the given string
     */
    public static BigDecimal toBigDecimal(final String value) {
        if (value != null){
            boolean negativeNumber = false;

            if (value.containts("(") && value.contains(")"))
               negativeNumber = true;
            if (value.endsWith("-") || value.startsWith("-"))
               negativeNumber = true;

            String parsedValue = value.replaceAll("[^0-9\\,\\.]", EMPTY);

            if (negativeNumber)
               parsedValue = "-" + parsedValue;

            int lastPointPosition = parsedValue.lastIndexOf(POINT);
            int lastCommaPosition = parsedValue.lastIndexOf(COMMA);

            //handle '1423' case, just a simple number
            if (lastPointPosition == -1 && lastCommaPosition == -1)
                return new BigDecimal(parsedValue);
            //handle '45.3' and '4.550.000' case, only points are in the given String
            if (lastPointPosition > -1 && lastCommaPosition == -1){
                int firstPointPosition = parsedValue.indexOf(POINT);
                if (firstPointPosition != lastPointPosition)
                    return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY));
                else
                    return new BigDecimal(parsedValue);
            }
            //handle '45,3' and '4,550,000' case, only commas are in the given String
            if (lastPointPosition == -1 && lastCommaPosition > -1){
                int firstCommaPosition = parsedValue.indexOf(COMMA);
                if (firstCommaPosition != lastCommaPosition)
                    return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY));
                else
                    return new BigDecimal(parsedValue.replace(COMMA, POINT));
            }
            //handle '2.345,04' case, points are in front of commas
            if (lastPointPosition < lastCommaPosition){
                parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY);
                return new BigDecimal(parsedValue.replace(COMMA, POINT));
            }
            //handle '2,345.04' case, commas are in front of points
            if (lastCommaPosition < lastPointPosition){
                parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY);
                return new BigDecimal(parsedValue);
            }
            throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal.");
        }
        return null;
    }

Of course i've tested the method:

@Test(dataProvider = "testBigDecimals")
    public void toBigDecimal_defaultLocaleTest(String stringValue, BigDecimal bigDecimalValue){
        BigDecimal convertedBigDecimal = DecimalHelper.toBigDecimal(stringValue);
        Assert.assertEquals(convertedBigDecimal, bigDecimalValue);
    }
    @DataProvider(name = "testBigDecimals")
    public static Object[][] bigDecimalConvertionTestValues() {
        return new Object[][] {
                {"5", new BigDecimal(5)},
                {"5,3", new BigDecimal("5.3")},
                {"5.3", new BigDecimal("5.3")},
                {"5.000,3", new BigDecimal("5000.3")},
                {"5.000.000,3", new BigDecimal("5000000.3")},
                {"5.000.000", new BigDecimal("5000000")},
                {"5,000.3", new BigDecimal("5000.3")},
                {"5,000,000.3", new BigDecimal("5000000.3")},
                {"5,000,000", new BigDecimal("5000000")},
                {"+5", new BigDecimal("5")},
                {"+5,3", new BigDecimal("5.3")},
                {"+5.3", new BigDecimal("5.3")},
                {"+5.000,3", new BigDecimal("5000.3")},
                {"+5.000.000,3", new BigDecimal("5000000.3")},
                {"+5.000.000", new BigDecimal("5000000")},
                {"+5,000.3", new BigDecimal("5000.3")},
                {"+5,000,000.3", new BigDecimal("5000000.3")},
                {"+5,000,000", new BigDecimal("5000000")},
                {"-5", new BigDecimal("-5")},
                {"-5,3", new BigDecimal("-5.3")},
                {"-5.3", new BigDecimal("-5.3")},
                {"-5.000,3", new BigDecimal("-5000.3")},
                {"-5.000.000,3", new BigDecimal("-5000000.3")},
                {"-5.000.000", new BigDecimal("-5000000")},
                {"-5,000.3", new BigDecimal("-5000.3")},
                {"-5,000,000.3", new BigDecimal("-5000000.3")},
                {"-5,000,000", new BigDecimal("-5000000")},
                {null, null}
        };
    }

Cannot get a text value from a numeric cell “Poi”

As explained in the Apache POI Javadocs, you should not use cell.setCellType(Cell.CELL_TYPE_STRING) to get the string value of a numeric cell, as you'll loose all the formatting

Instead, as the javadocs explain, you should use DataFormatter

What DataFormatter does is take the floating point value representing the cell is stored in the file, along with the formatting rules applied to it, and returns you a string that look like it the cell does in Excel.

So, if you're after a String of the cell, looking much as you had it looking in Excel, just do:

 // Create a formatter, do this once
 DataFormatter formatter = new DataFormatter(Locale.US);

 .....

 for (int i=1; i <= sheet.getLastRowNum(); i++) {
        Row r = sheet.getRow(i);
        if (r == null) { 
           // empty row, skip
        } else {
           String j_username = formatter.formatCellValue(row.getCell(0));
           String j_password =  formatter.formatCellValue(row.getCell(1));

           // Use these
        }
 }

The formatter will return String cells as-is, and for Numeric cells will apply the formatting rules on the style to the number of the cell

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

MVC - Set selected value of SelectList

Use LINQ and add the condition on the "selected" as a question mark condition.

    var listSiteId = (from site in db.GetSiteId().ToList()
                                      select new SelectListItem
                                      {
                                          Value = site.SITEID,
                                          Text = site.NAME,
                                          Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
                                      }).ToList();
                    ViewBag.SiteId = listSiteId;

c# datatable insert column at position 0

    //Example to define how to do :

    DataTable dt = new DataTable();   

    dt.Columns.Add("ID");
    dt.Columns.Add("FirstName");
    dt.Columns.Add("LastName");
    dt.Columns.Add("Address");
    dt.Columns.Add("City");
           //  The table structure is:
            //ID    FirstName   LastName    Address     City

       //Now we want to add a PhoneNo column after the LastName column. For this we use the                               
             //SetOrdinal function, as iin:
        dt.Columns.Add("PhoneNo").SetOrdinal(3);

            //3 is the position number and positions start from 0.`enter code here`

               //Now the table structure will be:
              // ID      FirstName   LastName    PhoneNo    Address     City

Performing Breadth First Search recursively

If you use an array to back the binary tree, you can determine the next node algebraically. if i is a node, then its children can be found at 2i + 1 (for the left node) and 2i + 2 (for the right node). A node's next neighbor is given by i + 1, unless i is a power of 2

Here's pseudocode for a very naive implementation of breadth first search on an array backed binary search tree. This assumes a fixed size array and therefore a fixed depth tree. It will look at parentless nodes, and could create an unmanageably large stack.

bintree-bfs(bintree, elt, i)
    if (i == LENGTH)
        return false

    else if (bintree[i] == elt)
        return true

    else 
        return bintree-bfs(bintree, elt, i+1)        

Run JavaScript code on window close or page refresh?

Ok, I found a working solution for this, it consists of using the beforeunload event and then making the handler return null. This executes the wanted code without a confirmation box popping-up. It goes something like this:

window.onbeforeunload = closingCode;
function closingCode(){
   // do something...
   return null;
}

Counting in a FOR loop using Windows Batch script

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

In other words, %count% is replaced with its value 1 before running the loop.

What you need is something like:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
  set /a count += 1
  echo !count!
)
endlocal

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.


Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.

You can string together multiple sub-commands to leak as much information as you need:

endlocal && set count=%count% && set something_else=%something_else%

Print raw string from variable? (not getting the answers)

i wrote a small function.. but works for me

def conv(strng):
    k=strng
    k=k.replace('\a','\\a')
    k=k.replace('\b','\\b')
    k=k.replace('\f','\\f')
    k=k.replace('\n','\\n')
    k=k.replace('\r','\\r')
    k=k.replace('\t','\\t')
    k=k.replace('\v','\\v')
    return k

JavaScript: undefined !== undefined?

From - JQuery_Core_Style_Guidelines

  • Global Variables:
    typeof variable === "undefined"

  • Local Variables:
    variable === undefined

  • Properties:
    object.prop === undefined

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

resize2fs Command will not work for all file systems.

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

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

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

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

sudo xfs_growfs -d /

then "df -h" to check.

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

You can use the focusout event to detect keyboard dismissal. It's like blur, but bubbles. It will fire when the keyboard closes (but also in other cases, of course). In Safari and Chrome the event can only be registered with addEventListener, not with legacy methods. Here is an example I used to restore a Phonegap app after keyboard dismissal.

 document.addEventListener('focusout', function(e) {window.scrollTo(0, 0)});

Without this snippet, the app container stayed in the up-scrolled position until page refresh.

SQL Server principal "dbo" does not exist,

After restoring a Database from SQL2016 to SQL2019, I had the same issue when I try to access Database Diagrams. I had the correct Database owner already but owner of Files was empty. Once I set that, it worked properly...

enter image description here

How to deserialize a JObject to .NET object

Too late, just in case some one is looking for another way:

void Main()
{
    string jsonString = @"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}";

    Product product = new Product();
    //Serializing to Object
    Product obj = JObject.Parse(jsonString).SelectToken("$.Manufacturers[?(@.Name == 'Acme Co' && @.Name != 'Contoso')]").ToObject<Product>();

    Console.WriteLine(obj);
}


public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Why does multiplication repeats the number several times?

In [58]: price = 1 *9
In [59]: price
Out[59]: 9

HTTP Error 500.30 - ANCM In-Process Start Failure

Plz see my prev answer in this same thread to understand the whole. Sorry for multiple answers

After further investigation, the issue was happening due to VS 2019 picks the latest patch(default behavior of VS) of .net core 2.2 which is 2.2.8 for me to publish the application. We can restrict this to a specific version of choice by using

<RuntimeFrameworkVersion>2.2.4</RuntimeFrameworkVersion>

See Here. This finally solved my issue even though the latest patch is not applied. I can build from any VS 2017 or VS 2019, both publish the application for .net core 2.2.0 runtime version

enter image description here

How to convert string to string[]?

An array is a fixed collection of same-type data that are stored contiguously and that are accessible by an index (zero based).

A string is a sequence of characters.

Hence a String[] is a collection of Strings.

For example:

String foo = "Foo";  // one instance of String
String[] foos = new String[] { "Foo1", "Foo2", "Foo3" };
String firstFoo = foos[0];  // "Foo1"

Arrays (C# Programming Guide)

Edit: So obviously there's no direct way to convert a single String to an String[] or vice-versa. Though you can use String.Split to get a String[] from a String by using a separator(for example comma).

To "convert" a String[] to a String(the opposite) you can use String.Join. You need to specify how you want to join those strings(f.e. with comma).

Here's an example:

var foos = "Foo1,Foo2,Foo3";
var fooArray = foos.Split(',');  // now you have an array of 3 strings
foos = String.Join(",", fooArray); // now you have the same as in the first line

Refresh Page C# ASP.NET

I use

Response.Redirect(Page.Request.Path);

If you have to check for the Request.Params when the page is refresh use below. This will not rewrite the Request.Params to the URL.

Response.Redirect(Page.Request.Path + "?Remove=1");

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

In this simple case, where someClass.f is not inheriting any data from the class and not attaching anything to the class, a possible solution would be to separate out f, so it can be pickled:

import multiprocessing


def f(x):
    return x*x


class someClass(object):
    def __init__(self):
        pass

    def go(self):
        pool = multiprocessing.Pool(processes=4)       
        print pool.map(f, range(10))

VBA Macro to compare all cells of two Excel files

A very simple check you can do with Cell formulas:

Sheet 1 (new - old)

=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")

Sheet 2 (old - new)

=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")

This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)

You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".

Doe the same for Sheet two.

Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.

But two cases are not covered here:

  1. In the compared cell of New and Old is the same data (Resulting Cell will be empty)
  2. In the compared cell of New and Old is diffe data (Resulting Cell will be empty)

To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com

Group by with multiple columns using lambda

Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.

return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
                .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
                .SelectMany(a => a)
                .ToList();

Where CustomerGroupingKey takes the group keys:

    private class CustomerGroupingKey
    {
        public CustomerGroupingKey(string country, string gender)
        {
            Country = country;
            Gender = gender;
        }

        public string Country { get; }

        public string Gender { get; }
    }

Suppress warning messages using mysql from within Terminal, but password written in bash script

You can execute mySQL and suppress warning and error messages by using /dev/null for example:

# if you run just a SQL-command
mysql -u ${USERNAME} -p${PASSWORD} -h ${HOST} ${DATABASE} -e "${STATEMENT}" &> /dev/null

# Or you can run SQL-script as a file
mysql -u ${USERNAME} -p${PASSWORD} -h ${HOST} ${DATABASE} < ${FILEPATH} &> /dev/null

Where:

${USERNAME} - existing mysql user

${PASSWORD} - password

${HOST}     - ip or hostname, for example 'localhost'

${DATABASE} - name of database

${STATEMENT}- SQL command

${FILEPATH} - Path to the SQL-script

enjoy!

Spring not autowiring in unit tests with JUnit

I'm using JUnit 5 and for me the problem was that I had imported Test from the wrong package:

import org.junit.Test;

Replacing it with the following worked for me:

import org.junit.jupiter.api.Test;

jQuery text() and newlines

Using the CSS white-space property is probably the best solution. Use Firebug or Chrome Developer Tools to identify the source of the extra padding you were seeing.

Reading a key from the Web.Config using ConfigurationManager

with assuming below setting in .config file:

<configuration>
   <appSettings>
     <add key="PFUserName" value="myusername"/>
     <add key="PFPassWord" value="mypassword"/>
   </appSettings> 
</configuration>

try this:

public class myController : Controller
{
    NameValueCollection myKeys = ConfigurationManager.AppSettings;

    public void MyMethod()
    {
        var myUsername = myKeys["PFUserName"];
        var myPassword = myKeys["PFPassWord"];
    }
}

How to add app icon within phonegap projects?

Fortunately there is a little bit in the docs about the splash images, which put me on the road to getting the right location for the icon images as well. So here it goes.

Where the files are placed Once you have built your project using command-line interface "cordova build ios" you should have a complete file structure for your iOS app in the platforms/ios/ folder.

Inside that folder is a folder with the name of your app. Which in turn contains a resources/ directory where you will find the icons/ and splashscreen/ folders.

In the icons folder you will find four icon files (for 57px and 72 px, each in regular and @2x version). These are the Phonegap placeholder icons you've been seeing so far.

What to do

All you have to do is save the icon files in this folder. So that's:

YourPhonegapProject/Platforms/ios/YourAppName/Resources/icons

Same for splashscreen files.

Notes

  1. After placing the files there, rebuild the project using cordova build ios AND use xCode's 'Clean product' menu command. Without this, you'll still be seeing the Phonegap placeholders.

  2. It's wisest to rename your files the iOS/Apple way (i.e. [email protected] etc) instead of editing the names in the info.plist or config.xml. At least that worked for me.

  3. And by the way, ignore the weird path and the weird filename given for the icons in config.xml (i.e. <icon gap:platform="ios" height="114" src="res/icon/ios/icon-57-2x.png" width="114" />). I just left those definitions there, and the icons showed up just fine even though my 114px icon was named [email protected] instead of icon-57-2x.png.

  4. Don't use config.xml to prevent Apple's gloss effect on the icon. Instead, tick the box in xCode (click the project title in the left navigation column, select your app under the Target header, and scroll down to the icons section).

Is it possible to set ENV variables for rails development environment in my code?

The way I am trying to do this in my question actually works!

# environment/development.rb

ENV['admin_password'] = "secret" 

I just had to restart the server. I thought running reload! in rails console would be enough but I also had to restart the web server.

I am picking my own answer because I feel this is a better place to put and set the ENV variables

jQuery hasClass() - check for more than one class

use default js match() function:

if( element.attr('class') !== undefined && element.attr('class').match(/class1|class2|class3|class4|class5/) ) {
  console.log("match");
}

to use variables in regexp, use this:

var reg = new RegExp(variable, 'g');
$(this).match(reg);

by the way, this is the fastest way: http://jsperf.com/hasclass-vs-is-stackoverflow/22

Get Memory Usage in Android

enter the android terminal and then you can type the following commands :dumpsys cpuinfo

shell@android:/ $ dumpsys cpuinfo                                              
Load: 0.8 / 0.75 / 1.15
CPU usage from 69286ms to 9283ms ago with 99% awake:
  47% 1118/com.wxg.sodproject: 12% user + 35% kernel
  1.6% 1225/android.process.media: 1% user + 0.6% kernel
  1.3% 263/mpdecision: 0.1% user + 1.2% kernel
  0.1% 32747/kworker/u:1: 0% user + 0.1% kernel
  0.1% 883/com.android.systemui: 0.1% user + 0% kernel
  0.1% 521/system_server: 0.1% user + 0% kernel / faults: 14 minor
  0.1% 1826/com.quicinc.trepn: 0.1% user + 0% kernel
  0.1% 2462/kworker/0:2: 0.1% user + 0% kernel
  0.1% 32649/kworker/0:0: 0% user + 0.1% kernel
  0% 118/mmcqd/0: 0% user + 0% kernel
  0% 179/surfaceflinger: 0% user + 0% kernel
  0% 46/kinteractiveup: 0% user + 0% kernel
  0% 141/jbd2/mmcblk0p26: 0% user + 0% kernel
  0% 239/sdcard: 0% user + 0% kernel
  0% 1171/com.xiaomi.channel:pushservice: 0% user + 0% kernel / faults: 1 minor
  0% 1207/com.xiaomi.channel: 0% user + 0% kernel / faults: 1 minor
  0% 32705/kworker/0:1: 0% user + 0% kernel
12% TOTAL: 3.2% user + 9.4% kernel + 0% iowait

"Default Activity Not Found" on Android Studio upgrade

Go to manifest file and then go merge manifest file see error and solve manifest issue

clean project and run

How to Compare a long value is equal to Long value

First your code is not compiled. Line Long b = 1113;

is wrong. You have to say

Long b = 1113L;

Second when I fixed this compilation problem the code printed "not equals".

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

PDO Prepared Inserts multiple rows in single query

This worked for me

$sql = 'INSERT INTO table(pk_pk1,pk_pk2,date,pk_3) VALUES '; 
$qPart = array_fill(0, count($array), "(?, ?,UTC_TIMESTAMP(),?)");
$sql .= implode(",", $qPart);
$stmt =    DB::prepare('base', $sql);
$i = 1;
foreach ($array as $value) { 
  $stmt->bindValue($i++, $value);
  $stmt->bindValue($i++, $pk_pk1);
  $stmt->bindValue($i++, $pk_pk2); 
  $stmt->bindValue($i++, $pk_pk3); 
} 
$stmt->execute();

Tool for comparing 2 binary files in Windows

If you want to find out only whether or not the files are identical, you can use the Windows fc command in binary mode:

fc.exe /b file1 file2

For details, see the reference for fc

What is the difference between Nexus and Maven?

Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.

Details

How to Handle Button Click Events in jQuery?

 $("#btnSubmit").click(function(){
        alert("button");
    });    

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I ran into this error because I was attempting to write a string to a cell which started with an "=".

The solution was to put an "'" (apostrophe) before the equals sign, which is a way to tell excel that you're not, in fact, trying to write a formula, and just want to print the equals sign.

Numpy: Divide each row by a vector element

Here you go. You just need to use None (or alternatively np.newaxis) combined with broadcasting:

In [6]: data - vector[:,None]
Out[6]:
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

In [7]: data / vector[:,None]
Out[7]:
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

jQuery - on change input text

The jQuery documentation says this "It is also displayed [the handler execution result] if you change the text in the field and then click away. If the field loses focus without the contents having changed, though, the event is not triggered.".

Try the keyup and keydown events, like this:

$("#kat").keydown(function(){ 
   alert("Hello");
});

Overcoming "Display forbidden by X-Frame-Options"

If you are getting this error for a YouTube video, rather than using the full url use the embed url from the share options. It will look like http://www.youtube.com/embed/eCfDxZxTBW4

You may also replace watch?v= with embed/ so http://www.youtube.com/watch?v=eCfDxZxTBW4 becomes http://www.youtube.com/embed/eCfDxZxTBW4

Making a button invisible by clicking another button in HTML

Using jQuery!

var demoShow = function(){
    $("#p2").hide();
}

But I would recommend you give an id to your button on which you want an action to happen. For example:

<input type="button" id="p1" value="edit" />
<input type="button" id="p2" value="submit" name="submit" />

<script type="text/javascript"> 
$("#p1").click(function(){
    $("#p2").hide();
});
</script>

To show it again you can simply write: $("#p2").show();

JSLint is suddenly reporting: Use the function form of "use strict"

I think everyone missed the "suddenly" part of this question. Most likely, your .jshintrc has a syntax error, so it's not including the 'browser' line. Run it through a json validator to see where the error is.

Get filename from input [type='file'] using jQuery

If selected more 1 file:

$("input[type="file"]").change(function() {
   var files = $("input[type="file"]").prop("files");
   var names = $.map(files, function(val) { return val.name; });
   $(".some_div").text(names);
});

files will be a FileList object. names is an array of strings (file names).

Java: Check the date format of current string is according to required format or not

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
formatter.setLenient(false);
try {
    Date date= formatter.parse("02/03/2010");
} catch (ParseException e) {
    //If input date is in different format or invalid.
}

formatter.setLenient(false) will enforce strict matching.

If you are using Joda-Time -

private boolean isValidDate(String dateOfBirth) {
        boolean valid = true;
        try {
            DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
            DateTime dob = formatter.parseDateTime(dateOfBirth);
        } catch (Exception e) {
            valid = false;
        }
        return valid;
    }

How can I read a text file from the SD card in Android?

In your layout you'll need something to display the text. A TextView is the obvious choice. So you'll have something like this:

<TextView 
    android:id="@+id/text_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/>

And your code will look like this:

//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text
tv.setText(text);

This could go in the onCreate() method of your Activity, or somewhere else depending on just what it is you want to do.

How to Sort a List<T> by a property in the object

An improved of Roger's version.

The problem with GetDynamicSortProperty is that only get the property names but what happen if in the GridView we use NavigationProperties? it will send an exception, since it finds null.

Example:

"Employee.Company.Name; " will crash... since allows only "Name" as a parameter to get its value.

Here's an improved version that allows us to sort by Navigation Properties.

public object GetDynamicSortProperty(object item, string propName)
    {
        try
        {                 
            string[] prop = propName.Split('.'); 

            //Use reflection to get order type                   
            int i = 0;                    
            while (i < prop.Count())
            {
                item = item.GetType().GetProperty(prop[i]).GetValue(item, null);
                i++;
            }                     

            return item;
        }
        catch (Exception ex)
        {
            throw ex;
        }


    } 

Undo a Git merge that hasn't been pushed yet

Okay, the answers other people here gave me were close, but it didn't work. Here's what I did.

Doing this...

git reset --hard HEAD^
git status

...gave me the following status.

# On branch master
# Your branch and 'origin/master' have diverged,
# and have 3 and 3 different commit(s) each, respectively.

I then had to type in the same git reset command several more times. Each time I did that, the message changed by one as you can see below.

> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 3 and 3 different commit(s) each, respectively.
> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 3 different commit(s) each, respectively.
> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 1 and 3 different commit(s) each, respectively.
> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch is behind 'origin/master' by 3 commits, and can be fast-forwarded.

At this point, I saw the status message changed, so I tried doing a git pull, and that seemed to work:

> git pull
Updating 2df6af4..12bbd2f
Fast forward
 app/views/truncated |    9 ++++++---
 app/views/truncated |   13 +++++++++++++
 app/views/truncated |    2 +-
 3 files changed, 20 insertions(+), 4 deletions(-)
> git status
# On branch master

So long story short, my commands came down to this:

git reset --hard HEAD^
git reset --hard HEAD^
git reset --hard HEAD^
git reset --hard HEAD^
git pull

How do I make Java register a string input with spaces?

Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.

Class Scanner

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.

Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;

System.out.println("Please input question:");
question = in.next();

// TODO do something with your input such as removing spaces...

if (question.equalsIgnoreCase("howdoyoulikeschool?") )
    /* it seems strings do not allow for spaces */
    System.out.println("CLOSED!!");
else
    System.out.println("Que?");

Bower: ENOGIT Git is not installed or not in the PATH

You are missing the ENVIRONMENT PATH. Follow these steps:

  1. Search for 'Edit the system environment variables'.
  2. Click on 'Environment Variables'.
  3. In the 'System variables' section, scroll down and click on the variable 'Path'. Click 'Edit'.
  4. Append this text to the end of the 'Variable value'.

;%PROGRAMFILES%\Git\bin;%PROGRAMFILES%\Git\cmd

How to determine if a number is odd in JavaScript

When you need to test if some variable is odd, you should first test if it is integer. Also, notice that when you calculate remainder on negative number, the result will be negative (-3 % 2 === -1).

function isOdd(value) {
  return typeof value === "number" && // value should be a number
    isFinite(value) &&                // value should be finite
    Math.floor(value) === value &&    // value should be integer
    value % 2 !== 0;                  // value should not be even
}

If Number.isInteger is available, you may also simplify this code to:

function isOdd(value) {
  return Number.isInteger(value)      // value should be integer
    value % 2 !== 0;                  // value should not be even
}

Note: here, we test value % 2 !== 0 instead of value % 2 === 1 is because of -3 % 2 === -1. If you don't want -1 pass this test, you may need to change this line.

Here are some test cases:

isOdd();         // false
isOdd("string"); // false
isOdd(Infinity); // false
isOdd(NaN);      // false
isOdd(0);        // false
isOdd(1.1);      // false
isOdd("1");      // false
isOdd(1);        // true
isOdd(-1);       // true

Regular Expression for alphanumeric and underscores

To match a string that contains only those characters (or an empty string), try

"^[a-zA-Z0-9_]*$"

This works for .NET regular expressions, and probably a lot of other languages as well.

Breaking it down:

^ : start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
] : end of character group
* : zero or more of the given characters
$ : end of string

If you don't want to allow empty strings, use + instead of *.


As others have pointed out, some regex languages have a shorthand form for [a-zA-Z0-9_]. In the .NET regex language, you can turn on ECMAScript behavior and use \w as a shorthand (yielding ^\w*$ or ^\w+$). Note that in other languages, and by default in .NET, \w is somewhat broader, and will match other sorts of Unicode characters as well (thanks to Jan for pointing this out). So if you're really intending to match only those characters, using the explicit (longer) form is probably best.

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

What is a good alternative to using an image map generator?

I have found Adobe Dreamweaver to be quite good at that. However, it's not free.

How to combine class and ID in CSS selector?

I think you are all wrong. IDs versus Class is not a question of specificity; they have completely different logical uses.

IDs should be used to identify specific parts of a page: the header, the nav bar, the main article, author attribution, footer.

Classes should be used to apply styles to the page. Let's say you have a general magazine site. Every page on the site is going to have the same elements--header, nav, main article, sidebar, footer. But your magazine has different sections--economics, sports, entertainment. You want the three sections to have different looks--economics conservative and square, sports action-y, entertainment bright and young.

You use classes for that. You don't want to have to make multiple IDs--#economics-article and #sports-article and #entertainment-article. That doesn't make sense. Rather, you would define three classes, .economics, sports, and .entertainment, then define the #nav, #article, and #footer ids for each.

Linux/Unix command to determine if process is running?

You should know the PID of your process.

When you launch it, its PID will be recorded in the $! variable. Save this PID into a file.

Then you will need to check if this PID corresponds to a running process. Here's a complete skeleton script:

FILE="/tmp/myapp.pid"

if [ -f $FILE ];
then
   PID=$(cat $FILE)
else
   PID=1
fi

ps -o pid= -p $PID
if [ $? -eq 0 ]; then
  echo "Process already running."  
else
  echo "Starting process."
  run_my_app &
  echo $! > $FILE
fi

Based on the answer of peterh. The trick for knowing if a given PID is running is in the ps -o pid= -p $PID instruction.

How does System.out.print() work?

Its all about Method Overloading.

There are individual methods for each data type in println() method

If you pass object :

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

If you pass Primitive type:

corresponding primitive type method calls

if you pass String :

corresponding println(String x) method calls

Push Notifications in Android Platform

You can use Google Cloud Messaging or GCM, it's free and easy to use. Also you can use third party push servers like PushWoosh which gives you more flexibility

How do you properly use namespaces in C++?

Generally speaking, I create a namespace for a body of code if I believe there might possibly be function or type name conflicts with other libraries. It also helps to brand code, ala boost:: .

Convert integer to binary in C#

http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html

    public string DecimalToBinary(string data)
    {
        string result = string.Empty;
        int rem = 0;
        try
        {
            if (!IsNumeric(data))
                error = "Invalid Value - This is not a numeric value";
            else
            {
                int num = int.Parse(data);
                while (num > 0)
                {
                    rem = num % 2;
                    num = num / 2;
                    result = rem.ToString() + result;
                }
            }
        }
        catch (Exception ex)
        {
            error = ex.Message;
        }
        return result;
    }

How to use setprecision in C++

std::cout.precision(2);
std::cout<<std::fixed;

when you are using operator overloading try this.

Does Python have a string 'contains' substring method?

if needle in haystack: is the normal use, as @Michael says -- it relies on the in operator, more readable and faster than a method call.

If you truly need a method instead of an operator (e.g. to do some weird key= for a very peculiar sort...?), that would be 'haystack'.__contains__. But since your example is for use in an if, I guess you don't really mean what you say;-). It's not good form (nor readable, nor efficient) to use special methods directly -- they're meant to be used, instead, through the operators and builtins that delegate to them.

Casting objects in Java

Say you have a superclass Fruit and the subclass Banana and you have a method addBananaToBasket()

The method will not accept grapes for example so you want to make sure that you're adding a banana to the basket.

So:

Fruit myFruit = new Banana();
((Banana)myFruit).addBananaToBasket(); ? This is called casting

What's the purpose of the LEA instruction?

Forgive me if someone already mentioned, but in the days of x86 when memory segmentation was still relevant, you may not get the same results from these two instructions:

LEA AX, DS:[0x1234]

and

LEA AX, CS:[0x1234]

Extract substring in Bash

If x is constant, the following parameter expansion performs substring extraction:

b=${a:12:5}

where 12 is the offset (zero-based) and 5 is the length

If the underscores around the digits are the only ones in the input, you can strip off the prefix and suffix (respectively) in two steps:

tmp=${a#*_}   # remove prefix ending in "_"
b=${tmp%_*}   # remove suffix starting with "_"

If there are other underscores, it's probably feasible anyway, albeit more tricky. If anyone knows how to perform both expansions in a single expression, I'd like to know too.

Both solutions presented are pure bash, with no process spawning involved, hence very fast.

How to get instance variables in Python?

Although not directly an answer to the OP question, there is a pretty sweet way of finding out what variables are in scope in a function. take a look at this code:

>>> def f(x, y):
    z = x**2 + y**2
    sqrt_z = z**.5
    return sqrt_z

>>> f.func_code.co_varnames
('x', 'y', 'z', 'sqrt_z')
>>> 

The func_code attribute has all kinds of interesting things in it. It allows you todo some cool stuff. Here is an example of how I have have used this:

def exec_command(self, cmd, msg, sig):

    def message(msg):
        a = self.link.process(self.link.recieved_message(msg))
        self.exec_command(*a)

    def error(msg):
        self.printer.printInfo(msg)

    def set_usrlist(msg):
        self.client.connected_users = msg

    def chatmessage(msg):
        self.printer.printInfo(msg)

    if not locals().has_key(cmd): return
    cmd = locals()[cmd]

    try:
        if 'sig' in cmd.func_code.co_varnames and \
                       'msg' in cmd.func_code.co_varnames: 
            cmd(msg, sig)
        elif 'msg' in cmd.func_code.co_varnames: 
            cmd(msg)
        else:
            cmd()
    except Exception, e:
        print '\n-----------ERROR-----------'
        print 'error: ', e
        print 'Error proccessing: ', cmd.__name__
        print 'Message: ', msg
        print 'Sig: ', sig
        print '-----------ERROR-----------\n'

How do we determine the number of days for a given month in python

Alternative solution:

>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29

Making macOS Installer Packages which are Developer ID ready

FYI for those that are trying to create a package installer for a bundle or plugin, it's easy:

pkgbuild --component "Color Lists.colorPicker" --install-location ~/Library/ColorPickers ColorLists.pkg

Print the address or pointer for value in C

I have been in this position, especially with new hardware. I suggest you write a little hex dump routine of your own. You will be able to see the data, and the addresses they are at, shown all together. It's good practice and a confidence builder.

node.js http 'get' request with query string parameters

No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:

const requestUrl = url.parse(url.format({
    protocol: 'https',
    hostname: 'yoursite.com',
    pathname: '/the/path',
    query: {
        key: value
    }
}));

Then make the request with the formatted url. requestUrl.path will include the query parameters.

const req = https.get({
    hostname: requestUrl.hostname,
    path: requestUrl.path,
}, (res) => {
   // ...
})

When to use setAttribute vs .attribute= in JavaScript?

Interesting takeout from Google API script regarding this:

They do it like this:

var scriptElement = document.createElement("script");
scriptElement = setAttribute("src", "https://some.com");
scriptElement = setAttribute("nonce", "https://some.com");
scriptElement.async = "true";

Notice, how they use setAttribute for "src" and "nonce", but then .async = ... for "async" attribute.

I'm not 100% sure, but probably that's because "async" is only supported on browsers that support direct .attr = assignment. So, there's no sense trying to sestAttribute("async") because if browser doesn't understand .async=... - it will not understand "async" attribute.

Hopefully, that's a helpful insight from my ongoing "Un-minify GAPI" research project. Correct me if I'm wrong.

How to select rows with no matching entry in another table?

Let we have the following 2 tables(salary and employee) enter image description here

Now i want those records from employee table which are not in salary. We can do this in 3 ways:

  1. Using inner Join
select * from employee
where id not in(select e.id from employee e inner join salary s on e.id=s.id)

enter image description here

  1. Using Left outer join
select * from employee e 
left outer join salary s on e.id=s.id  where s.id is null

enter image description here

  1. Using Full Join
select * from employee e
full outer join salary s on e.id=s.id where e.id not in(select id from salary)

enter image description here

Check if a String is in an ArrayList of Strings

temp = bankAccNos.contains(no) ? 1 : 2;

How to pass Multiple Parameters from ajax call to MVC Controller

I did that with helping from this question

jquery get querystring from URL

so let see how we will use this function

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

and now just use it in Ajax call

"ajax": {
    url: '/Departments/GetAllDepartments/',                     
    type: 'GET',                       
    dataType: 'json',                       
    data: getUrlVars()// here is the tricky part
},

thats all, but if you want know how to use this function or not send all the query string parameters back to actual answer

Get POST data in C#/ASP.NET

c.Request["AP"] will read posted values. Also you need to use a submit button to post the form:

<input type="submit" value="Submit" />

instead of

<input type=button value="Submit" />

What is the python "with" statement designed for?

See PEP 343 - The 'with' statement, there is an example section at the end.

... new statement "with" to the Python language to make it possible to factor out standard uses of try/finally statements.

How do you cache an image in Javascript

Once an image has been loaded in any way into the browser, it will be in the browser cache and will load much faster the next time it is used whether that use is in the current page or in any other page as long as the image is used before it expires from the browser cache.

So, to precache images, all you have to do is load them into the browser. If you want to precache a bunch of images, it's probably best to do it with javascript as it generally won't hold up the page load when done from javascript. You can do that like this:

function preloadImages(array) {
    if (!preloadImages.list) {
        preloadImages.list = [];
    }
    var list = preloadImages.list;
    for (var i = 0; i < array.length; i++) {
        var img = new Image();
        img.onload = function() {
            var index = list.indexOf(this);
            if (index !== -1) {
                // remove image from the array once it's loaded
                // for memory consumption reasons
                list.splice(index, 1);
            }
        }
        list.push(img);
        img.src = array[i];
    }
}

preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"]);

This function can be called as many times as you want and each time, it will just add more images to the precache.

Once images have been preloaded like this via javascript, the browser will have them in its cache and you can just refer to the normal URLs in other places (in your web pages) and the browser will fetch that URL from its cache rather than over the network.

Eventually over time, the browser cache may fill up and toss the oldest things that haven't been used in awhile. So eventually, the images will get flushed out of the cache, but they should stay there for awhile (depending upon how large the cache is and how much other browsing is done). Everytime the images are actually preloaded again or used in a web page, it refreshes their position in the browser cache automatically so they are less likely to get flushed out of the cache.

The browser cache is cross-page so it works for any page loaded into the browser. So you can precache in one place in your site and the browser cache will then work for all the other pages on your site.


When precaching as above, the images are loaded asynchronously so they will not block the loading or display of your page. But, if your page has lots of images of its own, these precache images can compete for bandwidth or connections with the images that are displayed in your page. Normally, this isn't a noticeable issue, but on a slow connection, this precaching could slow down the loading of the main page. If it was OK for preload images to be loaded last, then you could use a version of the function that would wait to start the preloading until after all other page resources were already loaded.

function preloadImages(array, waitForOtherResources, timeout) {
    var loaded = false, list = preloadImages.list, imgs = array.slice(0), t = timeout || 15*1000, timer;
    if (!preloadImages.list) {
        preloadImages.list = [];
    }
    if (!waitForOtherResources || document.readyState === 'complete') {
        loadNow();
    } else {
        window.addEventListener("load", function() {
            clearTimeout(timer);
            loadNow();
        });
        // in case window.addEventListener doesn't get called (sometimes some resource gets stuck)
        // then preload the images anyway after some timeout time
        timer = setTimeout(loadNow, t);
    }

    function loadNow() {
        if (!loaded) {
            loaded = true;
            for (var i = 0; i < imgs.length; i++) {
                var img = new Image();
                img.onload = img.onerror = img.onabort = function() {
                    var index = list.indexOf(this);
                    if (index !== -1) {
                        // remove image from the array once it's loaded
                        // for memory consumption reasons
                        list.splice(index, 1);
                    }
                }
                list.push(img);
                img.src = imgs[i];
            }
        }
    }
}

preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"], true);
preloadImages(["url99.jpg", "url98.jpg"], true);

Globally catch exceptions in a WPF application?

AppDomain.UnhandledException Event

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

   public App()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);    
   }

   static void MyHandler(object sender, UnhandledExceptionEventArgs args) 
   {
      Exception e = (Exception) args.ExceptionObject;
      Console.WriteLine("MyHandler caught : " + e.Message);
      Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
   }

If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.

For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.

Selenium Finding elements by class name in python

Use nth-child, for example: http://www.w3schools.com/cssref/sel_nth-child.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:nth-child(1)')

or http://www.w3schools.com/cssref/sel_firstchild.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:first-child')

Fatal error: Call to a member function bind_param() on boolean

This particular error has very little to do with the actual error. Here is my similar experience and the solution...

I had a table that I use in my statement with |database-name|.login composite name. I thought this wouldn't be a problem. It was the problem indeed. Enclosing it inside square brackets solved my problem ([|database-name|].[login]). So, the problem is MySQL preserved words (other way around)... make sure your columns too are not failing to this type of error scenario...

Shorthand if/else statement Javascript

var x = y !== undefined ? y : 1;

Note that var x = y || 1; would assign 1 for any case where y is falsy (e.g. false, 0, ""), which may be why it "didn't work" for you. Also, if y is a global variable, if it's truly not defined you may run into an error unless you access it as window.y.


As vol7ron suggests in the comments, you can also use typeof to avoid the need to refer to global vars as window.<name>:

var x = typeof y != "undefined" ? y : 1;

Fastest way(s) to move the cursor on a terminal command line?

In Cygwin, you can activate such feature by right-clicking the window. In the pop-up window, select Options... -> Mouse -> activate Clicks place command line cursor -> Apply.

From now on, simply clicking the left mouse button at some position within the command line will place the cursor there.

I ran into a merge conflict. How can I abort the merge?

I think it's git reset you need.

Beware that git revert means something very different to, say, svn revert - in Subversion the revert will discard your (uncommitted) changes, returning the file to the current version from the repository, whereas git revert "undoes" a commit.

git reset should do the equivalent of svn revert, that is, discard your unwanted changes.

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

In XSLT the same <xsl:variable> can be declared only once and can be given a value only at its declaration. If more than one variables are declared at the same time, they are in fact different variables and have different scope.

Therefore, the way to achieve the wanted conditional setting of the variable and producing its value is the following:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="class">
    <xsl:variable name="subexists">
            <xsl:choose>
                <xsl:when test="joined-subclass">true</xsl:when>
                <xsl:otherwise>false</xsl:otherwise>
            </xsl:choose>
        </xsl:variable>
        subexists:  <xsl:text/>    
        <xsl:value-of select="$subexists" />
    </xsl:template>
</xsl:stylesheet>

When the above transformation is applied on the following XML document:

<class>
 <joined-subclass/>
</class>

the wanted result is produced:

    subexists:  true

npm ERR! Error: EPERM: operation not permitted, rename

In my case running npm: v6.9.0 && node: v10.16.1 on Windows, I had to run my CLI (git bash) as administrator. Then packages were installed without any warnings/errors

How to use makefiles in Visual Studio?

I actually use a makefile to build any dependencies needed before invoking devenv to build a particular project as in the following:

debug: coratools_debug
    devenv coralib.vcproj /build debug

coratools_debug: nothing
    cd ../coratools
    nmake debug
    cd $(MAKEDIR)

You can also use the msbuild tool to do the same thing:

debug: coratools_debug
    msbuild coralib.vcxproj /p:Configuration=debug

coratools_debug: nothing
    cd ../coratools
    nmake debug
    cd $(MAKEDIR)

In my opinion, this is much easier than trying to figure out the overly complicated visual studio project management scheme.

Multiple line code example in Javadoc comment

/**
 * <blockquote><pre>
 * {@code
 * public Foo(final Class<?> klass) {
 *     super();
 *     this.klass = klass;
 * }
 * }
 * </pre></blockquote>
 **/
  • <pre/> is required for preserving lines.
  • {@code must has its own line
  • <blockquote/> is just for indentation.
public Foo(final Class<?> klass) {
    super();
    this.klass = klass;
}


UPDATE with JDK8

The minimum requirements for proper codes are <pre/> and {@code}.

/**
 * test.
 *
 * <pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre>
 */

yields

 <T> void test(Class<? super T> type) {
     System.out.printf("hello, world\n");
 }

And an optional surrounding <blockquote/> inserts an indentation.

/**
 * test.
 *
 * <blockquote><pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre></blockquote>
 */

yields

     <T> void test(Class<? super T> type) {
         System.out.printf("hello, world\n");
     }

Inserting <p> or surrounding with <p> and </p> yields warnings.

How to export a CSV to Excel using Powershell

If you want to convert CSV to Excel without Excel being installed, you can use the great .NET library EPPlus (under LGPL license) to create and modify Excel Sheets and also convert CSV to Excel really fast!

Preparation

  1. Download the latest stable EPPlus version
  2. Extract EPPlus to your preferred location (e.g. to $HOME\Documents\WindowsPowerShell\Modules\EPPlus)
  3. Right Click EPPlus.dll, select Properties and at the bottom of the General Tab click "Unblock" to allow loading of this dll. If you don't have the rights to do this, try [Reflection.Assembly]::UnsafeLoadFrom($DLLPath) | Out-Null

Detailed Powershell Commands to import CSV to Excel

# Create temporary CSV and Excel file names
$FileNameCSV = "$HOME\Downloads\test.csv"
$FileNameExcel = "$HOME\Downloads\test.xlsx"

# Create CSV File (with first line containing type information and empty last line)
Get-Process | Export-Csv -Delimiter ';' -Encoding UTF8 -Path $FileNameCSV

# Load EPPlus
$DLLPath = "$HOME\Documents\WindowsPowerShell\Modules\EPPlus\EPPlus.dll"
[Reflection.Assembly]::LoadFile($DLLPath) | Out-Null

# Set CSV Format
$Format = New-object -TypeName OfficeOpenXml.ExcelTextFormat
$Format.Delimiter = ";"
# use Text Qualifier if your CSV entries are quoted, e.g. "Cell1","Cell2"
$Format.TextQualifier = '"'
$Format.Encoding = [System.Text.Encoding]::UTF8
$Format.SkipLinesBeginning = '1'
$Format.SkipLinesEnd = '1'

# Set Preferred Table Style
$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium1

# Create Excel File
$ExcelPackage = New-Object OfficeOpenXml.ExcelPackage 
$Worksheet = $ExcelPackage.Workbook.Worksheets.Add("FromCSV")

# Load CSV File with first row as heads using a table style
$null=$Worksheet.Cells.LoadFromText((Get-Item $FileNameCSV),$Format,$TableStyle,$true) 

# Load CSV File without table style
#$null=$Worksheet.Cells.LoadFromText($file,$format) 

# Fit Column Size to Size of Content
$Worksheet.Cells[$Worksheet.Dimension.Address].AutoFitColumns()

# Save Excel File
$ExcelPackage.SaveAs($FileNameExcel) 

Write-Host "CSV File $FileNameCSV converted to Excel file $FileNameExcel"

Why do you need to invoke an anonymous function on the same line?

The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.

var msg = "later dude";
window.onunload = function(msg){
  alert( msg );
};

You could namespace your msg property using a Revealing Module Pattern like:

var myScript = (function() {
    var pub = {};
    //myscript.msg
    pub.msg = "later dude";
    window.onunload = function(msg) {
        alert(msg);
    };
    //API
    return pub;
}());

How to get tf.exe (TFS command line client)?

For reference: these are the required DLLs for Visual Studio 2017 (as did @ijprest for the VS 2010)

TF.exe
TF.exe.config
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Core.WebApi.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.TeamFoundation.VersionControl.Common.dll
Microsoft.TeamFoundation.VersionControl.Controls.dll
Microsoft.VisualStudio.Services.Client.Interactive.dll
Microsoft.VisualStudio.Services.Common.dll
Microsoft.VisualStudio.Services.WebApi.dll

They will be in my base VM image. I'm going to use it to pull the latest deployment scripts from VC to a temporary local workspace folder when installing a new server.

tf workspace /new ... 
tf workfold /map ...
tf get "%WorkSpaceLocalFolder%" /recursive
tf workfold /unmap 
tf workspace /delete

<run deployment scripts from "%WorkSpaceLocalFolder%" >

rmdir "%WorkSpaceLocalFolder%"

(Sorry to post this as an answer, but I don't have enough reputation to comment, which I believe it should have been)

Converting JavaScript object with numeric keys into array

Not sure what I am missing here but simply trying the below code does the work. Am I missing anything here?

https://jsfiddle.net/vatsalpande/w3ew5bhq/

$(document).ready(function(){

var json = {
   "code" :"1", 
   "data" : { 
    "0" : {"id":"1","score":"44"},
    "1" : {"id":"1","score":"44"}
    }
  };

  createUpdatedJson();

  function createUpdatedJson(){

    var updatedJson = json;

    updatedJson.data = [updatedJson.data];

    $('#jsondata').html(JSON.stringify(updatedJson));


    console.log(JSON.stringify(updatedJson));
  }
 })

WiX tricks and tips

Add a checkbox to the exit dialog to launch the app, or the helpfile.

...

<!-- CA to launch the exe after install -->
<CustomAction Id          ="CA.StartAppOnExit"
              FileKey     ="YourAppExeId"
              ExeCommand  =""
              Execute     ="immediate"
              Impersonate ="yes"
              Return      ="asyncNoWait" />

<!-- CA to launch the help file -->
<CustomAction Id         ="CA.LaunchHelp"
              Directory  ="INSTALLDIR"
              ExeCommand ='[WindowsFolder]hh.exe IirfGuide.chm'
              Execute    ="immediate"
              Return     ="asyncNoWait" />

<Property Id="WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT"
          Value="Launch MyApp when setup exits." />

<UI>
  <Publish Dialog  ="ExitDialog"
           Control ="Finish"
           Order   ="1"
           Event   ="DoAction"
           Value   ="CA.StartAppOnExit">WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT</Publish>
</UI>

If you do it this way, the "standard" appearance isn't quite right. The checkbox is always a gray background, while the dialog is white:

alt text http://www.dizzymonkeydesign.com/blog/misc/adding-and-customizing-dlgs-in-wix-3/images/exit_dlg_1.gif

One way around this is to specify your own custom ExitDialog, with a differently-located checkbox. This works, but seems like a lot of work just to change the color of one control. Another way to solve the same thing is to post-process the generated MSI to change the X,Y fields in the Control table for that particular CheckBox control. The javascript code looks like this:

var msiOpenDatabaseModeTransact = 1;
var filespec = WScript.Arguments(0);
var installer = new ActiveXObject("WindowsInstaller.Installer");
var database = installer.OpenDatabase(filespec, msiOpenDatabaseModeTransact);
var sql = "UPDATE `Control` SET `Control`.`Height` = '18', `Control`.`Width` = '170'," +
          " `Control`.`Y`='243', `Control`.`X`='10' " +
          "WHERE `Control`.`Dialog_`='ExitDialog' AND " + 
          "  `Control`.`Control`='OptionalCheckBox'";
var view = database.OpenView(sql);
view.Execute();
view.Close();
database.Commit();

Running this code as a command-line script (using cscript.exe) after the MSI is generated (from light.exe) will produce an ExitDialog that looks more professional:

alt text http://www.dizzymonkeydesign.com/blog/misc/adding-and-customizing-dlgs-in-wix-3/images/exit_dlg_2.gif

Is there a way to check which CSS styles are being used or not used on a web page?

I'm using CSS Dig. It is made for chrome, but I think it is a great tool!

Storing WPF Image Resources

Yes, it is the right way.

You could use the image in the resource file just using the path:

<Image Source="..\Media\Image.png" />

You must set the build action of the image file to "Resource".

Spring JPA and persistence.xml

I have a test application set up using JPA/Hibernate & Spring, and my configuration mirrors yours with the exception that I create a datasource and inject it into the EntityManagerFactory, and moved the datasource specific properties out of the persistenceUnit and into the datasource. With these two small changes, my EM gets injected properly.

How to run ssh-add on windows?

In order to run ssh-add on Windows one could install git using choco install git. The ssh-add command is recognized once C:\Program Files\Git\usr\bin has been added as a PATH variable and the command prompt has been restarted:

C:\Users\user\Desktop\repository>ssh-add .ssh/id_rsa
Enter passphrase for .ssh/id_rsa:
Identity added: .ssh/id_rsa (.ssh/id_rsa)

C:\Users\user\Desktop\repository> 

Get and set position with jQuery .offset()

//Get
var p = $("#elementId");
var offset = p.offset();

//set
$("#secondElementId").offset({ top: offset.top, left: offset.left});

FIND_IN_SET() vs IN()

To get the all related companies name, not based on particular Id.

SELECT 
    (SELECT GROUP_CONCAT(cmp.cmpny_name) 
    FROM company cmp 
    WHERE FIND_IN_SET(cmp.CompanyID, odr.attachedCompanyIDs)
    ) AS COMPANIES
FROM orders odr

How to convert password into md5 in jquery?

You need additional plugin for this.

take a look at this plugin

How do I get the first element from an IEnumerable<T> in .net?

If you can use LINQ you can use:

var e = enumerable.First();

This will throw an exception though if enumerable is empty: in which case you can use:

var e = enumerable.FirstOrDefault();

FirstOrDefault() will return default(T) if the enumerable is empty, which will be null for reference types or the default 'zero-value' for value types.

If you can't use LINQ, then your approach is technically correct and no different than creating an enumerator using the GetEnumerator and MoveNext methods to retrieve the first result (this example assumes enumerable is an IEnumerable<Elem>):

Elem e = myDefault;
using (IEnumerator<Elem> enumer = enumerable.GetEnumerator()) {
    if (enumer.MoveNext()) e = enumer.Current;
}

Joel Coehoorn mentioned .Single() in the comments; this will also work, if you are expecting your enumerable to contain exactly one element - however it will throw an exception if it is either empty or larger than one element. There is a corresponding SingleOrDefault() method that covers this scenario in a similar fashion to FirstOrDefault(). However, David B explains that SingleOrDefault() may still throw an exception in the case where the enumerable contains more than one item.

Edit: Thanks Marc Gravell for pointing out that I need to dispose of my IEnumerator object after using it - I've edited the non-LINQ example to display the using keyword to implement this pattern.

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

JAX-RS / Jersey how to customize error handling?

I was facing the same issue.

I wanted to catch all the errors at a central place and transform them.

Following is the code for how I handled it.

Create the following class which implements ExceptionMapper and add @Provider annotation on this class. This will handle all the exceptions.

Override toResponse method and return the Response object populated with customised data.

//ExceptionMapperProvider.java
/**
 * exception thrown by restful endpoints will be caught and transformed here
 * so that client gets a proper error message
 */
@Provider
public class ExceptionMapperProvider implements ExceptionMapper<Throwable> {
    private final ErrorTransformer errorTransformer = new ErrorTransformer();

    public ExceptionMapperProvider() {

    }

    @Override
    public Response toResponse(Throwable throwable) {
        //transforming the error using the custom logic of ErrorTransformer 
        final ServiceError errorResponse = errorTransformer.getErrorResponse(throwable);
        final ResponseBuilder responseBuilder = Response.status(errorResponse.getStatus());

        if (errorResponse.getBody().isPresent()) {
            responseBuilder.type(MediaType.APPLICATION_JSON_TYPE);
            responseBuilder.entity(errorResponse.getBody().get());
        }

        for (Map.Entry<String, String> header : errorResponse.getHeaders().entrySet()) {
            responseBuilder.header(header.getKey(), header.getValue());
        }

        return responseBuilder.build();
    }
}

// ErrorTransformer.java
/**
 * Error transformation logic
 */
public class ErrorTransformer {
    public ServiceError getErrorResponse(Throwable throwable) {
        ServiceError serviceError = new ServiceError();
        //add you logic here
        serviceError.setStatus(getStatus(throwable));
        serviceError.setBody(getBody(throwable));
        serviceError.setHeaders(getHeaders(throwable));

    }
    private String getStatus(Throwable throwable) {
        //your logic
    }
    private Optional<String> getBody(Throwable throwable) {
        //your logic
    }
    private Map<String, String> getHeaders(Throwable throwable) {
        //your logic
    }
}

//ServiceError.java
/**
 * error data holder
 */
public class ServiceError {
    private int status;
    private Map<String, String> headers;
    private Optional<String> body;
    //setters and getters
}

Counting the number of elements with the values of x in a vector

This is a very fast solution for one-dimensional atomic vectors. It relies on match(), so it is compatible with NA:

x <- c("a", NA, "a", "c", "a", "b", NA, "c")

fn <- function(x) {
  u <- unique.default(x)
  out <- list(x = u, freq = .Internal(tabulate(match(x, u), length(u))))
  class(out) <- "data.frame"
  attr(out, "row.names") <- seq_along(u)
  out
}

fn(x)

#>      x freq
#> 1    a    3
#> 2 <NA>    2
#> 3    c    2
#> 4    b    1

You could also tweak the algorithm so that it doesn't run unique().

fn2 <- function(x) {
  y <- match(x, x)
  out <- list(x = x, freq = .Internal(tabulate(y, length(x)))[y])
  class(out) <- "data.frame"
  attr(out, "row.names") <- seq_along(x)
  out
}

fn2(x)

#>      x freq
#> 1    a    3
#> 2 <NA>    2
#> 3    a    3
#> 4    c    2
#> 5    a    3
#> 6    b    1
#> 7 <NA>    2
#> 8    c    2

In cases where that output is desirable, you probably don't even need it to re-return the original vector, and the second column is probably all you need. You can get that in one line with the pipe:

match(x, x) %>% `[`(tabulate(.), .)

#> [1] 3 2 3 2 3 1 2 2

How to get the first word of a sentence in PHP?

You could do

echo current(explode(' ',$myvalue));

What is the difference between linear regression and logistic regression?

In case of Linear Regression the outcome is continuous while in case of Logistic Regression outcome is discrete (not continuous)

To perform Linear regression we require a linear relationship between the dependent and independent variables. But to perform Logistic regression we do not require a linear relationship between the dependent and independent variables.

Linear Regression is all about fitting a straight line in the data while Logistic Regression is about fitting a curve to the data.

Linear Regression is a regression algorithm for Machine Learning while Logistic Regression is a classification Algorithm for machine learning.

Linear regression assumes gaussian (or normal) distribution of dependent variable. Logistic regression assumes binomial distribution of dependent variable.

How to convert char to int?

int val = '1' - '0';

This can be done using ascii codes where '0' is the lowest and the number characters count up from there

How to delete a line from a text file in C#?

For very large files I'd do something like this

string tempFile = Path.GetTempFileName();

using(var sr = new StreamReader("file.txt"))
using(var sw = new StreamWriter(tempFile))
{
    string line;

    while((line = sr.ReadLine()) != null)
    {
         if(line != "removeme")
             sw.WriteLine(line);
    }
}

File.Delete("file.txt");
File.Move(tempFile, "file.txt");

Update I originally wrote this back in 2009 and I thought it might be interesting with an update. Today you could accomplish the above using LINQ and deferred execution

var tempFile = Path.GetTempFileName();
var linesToKeep = File.ReadLines(fileName).Where(l => l != "removeme");

File.WriteAllLines(tempFile, linesToKeep);

File.Delete(fileName);
File.Move(tempFile, fileName);

The code above is almost exactly the same as the first example, reading line by line and while keeping a minimal amount of data in memory.

A disclaimer might be in order though. Since we're talking about text files here you'd very rarely have to use the disk as an intermediate storage medium. If you're not dealing with very large log files there should be no problem reading the contents into memory instead and avoid having to deal with the temporary file.

File.WriteAllLines(fileName, 
    File.ReadLines(fileName).Where(l => l != "removeme").ToList());

Note that The .ToList is crucial here to force immediate execution. Also note that all the examples assume the text files are UTF-8 encoded.

Android dependency has different version for the compile and runtime

You should be able to see exactly which dependency is pulling in the odd version as a transitive dependency by running the correct gradle -q dependencies command for your project as described here:

https://docs.gradle.org/current/userguide/userguide_single.html#sec:listing_dependencies

Once you track down what's pulling it in, you can add an exclude to that specific dependency in your gradle file with something like:

implementation("XXXXX") {
    exclude group: 'com.android.support', module: 'support-compat'
}

How to change the color of the axis, ticks and labels for a plot in matplotlib

If you have several figures or subplots that you want to modify, it can be helpful to use the matplotlib context manager to change the color, instead of changing each one individually. The context manager allows you to temporarily change the rc parameters only for the immediately following indented code, but does not affect the global rc parameters.

This snippet yields two figures, the first one with modified colors for the axis, ticks and ticklabels, and the second one with the default rc parameters.

import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
    # Temporary rc parameters in effect
    fig, (ax1, ax2) = plt.subplots(1,2)
    ax1.plot(range(10))
    ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))

enter image description here

enter image description here

You can type plt.rcParams to view all available rc parameters, and use list comprehension to search for keywords:

# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]

Process.start: how to get the output?

you can use shared memory for the 2 processes to communicate through, check out MemoryMappedFile

you'll mainly create a memory mapped file mmf in the parent process using "using" statement then create the second process till it terminates and let it write the result to the mmf using BinaryWriter, then read the result from the mmf using the parent process, you can also pass the mmf name using command line arguments or hard code it.

make sure when using the mapped file in the parent process that you make the child process write the result to the mapped file before the mapped file is released in the parent process

Example: parent process

    private static void Main(string[] args)
    {
        using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("memfile", 128))
        {
            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryWriter writer = new BinaryWriter(stream);
                writer.Write(512);
            }

            Console.WriteLine("Starting the child process");
            // Command line args are separated by a space
            Process p = Process.Start("ChildProcess.exe", "memfile");

            Console.WriteLine("Waiting child to die");

            p.WaitForExit();
            Console.WriteLine("Child died");

            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryReader reader = new BinaryReader(stream);
                Console.WriteLine("Result:" + reader.ReadInt32());
            }
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

Child process

    private static void Main(string[] args)
    {
        Console.WriteLine("Child process started");
        string mmfName = args[0];

        using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(mmfName))
        {
            int readValue;
            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryReader reader = new BinaryReader(stream);
                Console.WriteLine("child reading: " + (readValue = reader.ReadInt32()));
            }
            using (MemoryMappedViewStream input = mmf.CreateViewStream())
            {
                BinaryWriter writer = new BinaryWriter(input);
                writer.Write(readValue * 2);
            }
        }

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

to use this sample, you'll need to create a solution with 2 projects inside, then you take the build result of the child process from %childDir%/bin/debug and copy it to %parentDirectory%/bin/debug then run the parent project

childDir and parentDirectory are the folder names of your projects on the pc good luck :)

What is the difference between Sessions and Cookies in PHP?

The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser.

Sessions are more secure than cookies as it is stored in server. Cookie can be turned off from browser.

Data stored in cookie can be stored for months or years, depending on the life span of the cookie. But the data in the session is lost when the web browser is closed.

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

Git: How to squash all commits on branch

Checkout the branch for which you would like to squash all the commits into one commit. Let's say it's called feature_branch.

git checkout feature_branch

Step 1:

Do a soft reset of your origin/feature_branch with your local main branch (depending on your needs, you can reset with origin/main as well). This will reset all the extra commits in your feature_branch, but without changing any of your file changes locally.

git reset --soft main

Step 2:

Add all of the changes in your git repo directory, to the new commit that is going to be created. And commit the same with a message.

git add -A && git commit -m "commit message goes here"

T-SQL stored procedure that accepts multiple Id values

Try This One:

@list_of_params varchar(20) -- value 1, 2, 5, 7, 20 

SELECT d.[Name]
FROM Department d
where @list_of_params like ('%'+ CONVERT(VARCHAR(10),d.Id)  +'%')

very simple.

Could not autowire field:RestTemplate in Spring boot application

It's exactly what the error says. You didn't create any RestTemplate bean, so it can't autowire any. If you need a RestTemplate you'll have to provide one. For example, add the following to TestMicroServiceApplication.java:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Note, in earlier versions of the Spring cloud starter for Eureka, a RestTemplate bean was created for you, but this is no longer true.

Increasing the JVM maximum heap size for memory intensive applications

Below conf works for me:

JAVA_HOME=/JDK1.7.51-64/jdk1.7.0_51/
PATH=/JDK1.7.51-64/jdk1.7.0_51/bin:$PATH
export PATH
export JAVA_HOME

JVM_ARGS="-d64 -Xms1024m -Xmx15360m -server"

/JDK1.7.51-64/jdk1.7.0_51/bin/java $JVM_ARGS -jar `dirname $0`/ApacheJMeter.jar "$@"

How to exit from the application and show the home screen?

(I tried previous answers but they lacks in some points. For example if you don't do a return; after finishing activity, remaining activity code runs. Also you need to edit onCreate with return. If you doesn't run super.onCreate() you will get a runtime error)

Say you have MainActivity and ChildActivity.

Inside ChildActivity add this:

Intent intent = new Intent(ChildActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
return true;

Inside MainActivity's onCreate add this:

@Override
public void onCreate(Bundle savedInstanceState) {

    mContext = getApplicationContext();

    super.onCreate(savedInstanceState);

    if (getIntent().getBooleanExtra("EXIT", false)) {
        finish();
        return;
    }
    // your current codes
    // your current codes
}

Determine device (iPhone, iPod Touch) with iOS

For simple comparison I always like macro:

#define IS_IPOD [[UIDevice currentDevice].model containsString:@"iPod"]
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)

It's simple and easy to use.

How to get the clicked link's href with jquery?

this in your callback function refers to the clicked element.

   $(".addressClick").click(function () {
        var addressValue = $(this).attr("href");
        alert(addressValue );
    });

Calculating arithmetic mean (one type of average) in Python

Use statistics.mean:

import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335

It's available since Python 3.4. For 3.1-3.3 users, an old version of the module is available on PyPI under the name stats. Just change statistics to stats.

How to call a function from a string stored in a variable?

A few years late, but this is the best manner now imho:

$x = (new ReflectionFunction("foo"))->getClosure();
$x();

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

This FutureWarning isn't from Pandas, it is from numpy and the bug also affects matplotlib and others, here's how to reproduce the warning nearer to the source of the trouble:

import numpy as np
print(np.__version__)   # Numpy version '1.12.0'
'x' in np.arange(5)       #Future warning thrown here

FutureWarning: elementwise comparison failed; returning scalar instead, but in the 
future will perform elementwise comparison
False

Another way to reproduce this bug using the double equals operator:

import numpy as np
np.arange(5) == np.arange(5).astype(str)    #FutureWarning thrown here

An example of Matplotlib affected by this FutureWarning under their quiver plot implementation: https://matplotlib.org/examples/pylab_examples/quiver_demo.html

What's going on here?

There is a disagreement between Numpy and native python on what should happen when you compare a strings to numpy's numeric types. Notice the left operand is python's turf, a primitive string, and the middle operation is python's turf, but the right operand is numpy's turf. Should you return a Python style Scalar or a Numpy style ndarray of Boolean? Numpy says ndarray of bool, Pythonic developers disagree. Classic standoff.

Should it be elementwise comparison or Scalar if item exists in the array?

If your code or library is using the in or == operators to compare python string to numpy ndarrays, they aren't compatible, so when if you try it, it returns a scalar, but only for now. The Warning indicates that in the future this behavior might change so your code pukes all over the carpet if python/numpy decide to do adopt Numpy style.

Submitted Bug reports:

Numpy and Python are in a standoff, for now the operation returns a scalar, but in the future it may change.

https://github.com/numpy/numpy/issues/6784

https://github.com/pandas-dev/pandas/issues/7830

Two workaround solutions:

Either lockdown your version of python and numpy, ignore the warnings and expect the behavior to not change, or convert both left and right operands of == and in to be from a numpy type or primitive python numeric type.

Suppress the warning globally:

import warnings
import numpy as np
warnings.simplefilter(action='ignore', category=FutureWarning)
print('x' in np.arange(5))   #returns False, without Warning

Suppress the warning on a line by line basis.

import warnings
import numpy as np

with warnings.catch_warnings():
    warnings.simplefilter(action='ignore', category=FutureWarning)
    print('x' in np.arange(2))   #returns False, warning is suppressed

print('x' in np.arange(10))   #returns False, Throws FutureWarning

Just suppress the warning by name, then put a loud comment next to it mentioning the current version of python and numpy, saying this code is brittle and requires these versions and put a link to here. Kick the can down the road.

TLDR: pandas are Jedi; numpy are the hutts; and python is the galactic empire. https://youtu.be/OZczsiCfQQk?t=3

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

@watson

On windows forms it is available, at the top of the class put

  static void Main(string[] args)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
       //other stuff here
    }

since windows is single threaded, its all you need, in the event its a service you need to put it right above the call to the service (since there is no telling what thread you'll be on).

using System.Security.Principal 

is also needed.

Cannot connect to MySQL 4.1+ using old authentication

If you do not have control of the server

I just had this issue, and was able to work around it.

First, connect to the MySQL database with an older client that doesn't mind old_passwords. Connect using the user that your script will be using.

Run these queries:

SET SESSION old_passwords=FALSE;
SET PASSWORD = PASSWORD('[your password]');

In your PHP script, change your mysql_connect function to include the client flag 1:

define('CLIENT_LONG_PASSWORD', 1);
mysql_connect('[your server]', '[your username]', '[your password]', false, CLIENT_LONG_PASSWORD);

This allowed me to connect successfully.

Edit: as per Garland Pope's comment, it may not be necessary to set CLIENT_LONG_PASSWORD manually any more in your PHP code as of PHP 5.4!

Edit: courtesy of Antonio Bonifati, a PHP script to run the queries for you:

<?php const DB = [ 'host' => '...', # localhost may not work on some hosting 
    'user' => '...',
    'pwd' => '...', ]; 

if (!mysql_connect(DB['host'], DB['user'], DB['pwd'])) {
    die(mysql_error());
} if (!mysql_query($query = 'SET SESSION old_passwords=FALSE')) {
    die($query);
} if (!mysql_query($query = "SET PASSWORD = PASSWORD('" . DB['pwd'] . "')")) {
    die($query);
}

echo "Excellent, mysqli will now work"; 
?>

C++ error: "Array must be initialized with a brace enclosed initializer"

You cannot initialize an array to '0' like that

int cipher[Array_size][Array_size]=0;

You can either initialize all the values in the array as you declare it like this:

// When using different values
int a[3] = {10,20,30};

// When using the same value for all members
int a[3] = {0};

// When using same value for all members in a 2D array
int a[Array_size][Array_size] = { { 0 } };

Or you need to initialize the values after declaration. If you want to initialize all values to 0 for example, you could do something like:

for (int i = 0; i < Array_size; i++ ) {
    a[i] = 0;
}

How are booleans formatted in Strings in Python?

>>> print "%r, %r" % (True, False)
True, False

This is not specific to boolean values - %r calls the __repr__ method on the argument. %s (for str) should also work.

MySQL date formats - difficulty Inserting a date

An add-on to the previous answers since I came across this concern:

If you really want to insert something like 24-May-2005 to your DATE column, you could do something like this:

INSERT INTO someTable(Empid,Date_Joined)
VALUES
    ('S710',STR_TO_DATE('24-May-2005', '%d-%M-%Y'));

In the above query please note that if it's May(ie: the month in letters) the format should be %M.

NOTE: I tried this with the latest MySQL version 8.0 and it works!

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

How to move a git repository into another directory and make that directory a git repository?

To do this without any headache:

  1. Check out what's the current branch in the gitrepo1 with git status, let's say branch "development".
  2. Change directory to the newrepo, then git clone the project from repository.
  3. Switch branch in newrepo to the previous one: git checkout development.
  4. Syncronize newrepo with the older one, gitrepo1 using rsync, excluding .git folder: rsync -azv --exclude '.git' gitrepo1 newrepo/gitrepo1. You don't have to do this with rsync of course, but it does it so smooth.

The benefit of this approach: you are good to continue exactly where you left off: your older branch, unstaged changes, etc.

A method to count occurrences in a list

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

How the int.TryParse actually works

TryParse is the best way for parse or validate in single line:

int nNumber = int.TryParse("InputString", out nNumber) ? nNumber : 1;

Short description:

  1. nNumber will initialize with zero,
  2. int.TryParse() try parse "InputString" and validate it, if succeed set into nNumber.
  3. short if ?: checking int.TryParse() result, that return nNumber or 1 as default value.

Custom Input[type="submit"] style not working with jquerymobile button

I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important property.

HTML

<a href="#" class="selected_btn" data-role="button">Button name</a>

CSS

.selected_btn
{
    border:1px solid red;
    text-decoration:none;
    font-family:helvetica;
    color:red !important;            
    background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}

Here is the demo

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

time = Time.now.to_s

time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")

for increment decrement month use << >> operators

examples

datetime_month_before = DateTime.parse(time) << 1



datetime_month_before = DateTime.now << 1

How should I escape commas and speech marks in CSV files so they work in Excel?

We eventually found the answer to this.

Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...

Reference,Title,Description
1,"My little title","My description, which may contain ""speech marks"" and commas."
2,"My other little title","My other description, which may also contain ""speech marks"" and commas."

... fixed the problem. Hope this helps someone!

How to open, read, and write from serial port in C?

For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.

This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.

To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.

 cc -DDISPLAY_STRING demo.c

If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.


#define TERMINAL    "/dev/ttyUSB0"

#include <errno.h>
#include <fcntl.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}


int main()
{
    char *portname = TERMINAL;
    int fd;
    int wlen;
    char *xstr = "Hello!\n";
    int xlen = strlen(xstr);

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);
    //set_mincount(fd, 0);                /* set to pure timed read */

    /* simple output */
    wlen = write(fd, xstr, xlen);
    if (wlen != xlen) {
        printf("Error from write: %d, %d\n", wlen, errno);
    }
    tcdrain(fd);    /* delay for output */


    /* simple noncanonical input */
    do {
        unsigned char buf[80];
        int rdlen;

        rdlen = read(fd, buf, sizeof(buf) - 1);
        if (rdlen > 0) {
#ifdef DISPLAY_STRING
            buf[rdlen] = 0;
            printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
            unsigned char   *p;
            printf("Read %d:", rdlen);
            for (p = buf; rdlen-- > 0; p++)
                printf(" 0x%x", *p);
            printf("\n");
#endif
        } else if (rdlen < 0) {
            printf("Error from read: %d: %s\n", rdlen, strerror(errno));
        } else {  /* rdlen == 0 */
            printf("Timeout from read\n");
        }               
        /* repeat read to get full message */
    } while (1);
}

For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.


How can I convert a string to a number in Perl?

This is a simple solution:

Example 1

my $var1 = "123abc";
print $var1 + 0;

Result

123

Example 2

my $var2 = "abc123";
print $var2 + 0;

Result

0

Giving a border to an HTML table row, <tr>

_x000D_
_x000D_
<table cellpadding="0" cellspacing="0" width="100%" style="border: 1px;" rules="none">_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <th style="width: 96px;">Column 1</th>_x000D_
            <th style="width: 96px;">Column 2</th>_x000D_
            <th style="width: 96px;">Column 3</th>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
            <td style="border-left: thin solid; border-top: thin solid; border-bottom: thin solid;">&nbsp;</td>_x000D_
            <td style="border-top: thin solid; border-bottom: thin solid;">&nbsp;</td>_x000D_
            <td style="border-top: thin solid; border-bottom: thin solid; border-right: thin solid;">&nbsp;</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Return only string message from Spring MVC 3 Controller

Although, @Tomasz is absolutely right there is another way:

@RequestMapping(value="/controller", method=GET)
public void foo(HttpServletResponse res) {
    try {       
        PrintWriter out = res.getWriter();
        out.println("Hello, world!");
        out.close();
    } catch (IOException ex) { 
        ...
    }
}

but the first method is preferable. You can use this method if you want to return response with custom content type or return binary type (file, etc...);

Regex that matches integers in between whitespace or start/end of string only

^(-+)?[1-9][0-9]*$ starts with a - or + for 0 or 1 times, then you want a non zero number (because there is not such a thing -0 or +0) and then it continues with any number from 0 to 9

Should I always use a parallel stream when possible?

JB hit the nail on the head. The only thing I can add is that Java 8 doesn't do pure parallel processing, it does paraquential. Yes I wrote the article and I've been doing F/J for thirty years so I do understand the issue.

How to add plus one (+1) to a SQL Server column in a SQL Query

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

Tool to monitor HTTP, TCP, etc. Web Service traffic

I tried Fiddler with its reverse proxy ability which is mentioned by @marxidad and it seems to be working fine, since Fiddler is a familiar UI for me and has the ability to show request/responses in various formats (i.e. Raw, XML, Hex), I accept it as an answer to this question. One thing though. I use WCF and I got the following exception with reverse proxy thing:

The message with To 'http://localhost:8000/path/to/service' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree

I have figured out (thanks Google, erm.. I mean Live Search :p) that this is because my endpoint addresses on server and client differs by port number. If you get the same exception consult to the following MSDN forum message:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2302537&SiteID=1

which recommends to use clientVia Endpoint Behavior explained in following MSDN article:

http://msdn.microsoft.com/en-us/magazine/cc163412.aspx

How many characters in varchar(max)

For future readers who need this answer quickly:

2^31-1 = 2.147.483.647 characters

How to call any method asynchronously in c#

Check out the MSDN article Asynchronous Programming with Async and Await if you can afford to play with new stuff. It was added to .NET 4.5.

Example code snippet from the link (which is itself from this MSDN sample code project):

// Three things to note in the signature: 
//  - The method has an async modifier.  
//  - The return type is Task or Task<T>. (See "Return Types" section.)
//    Here, it is Task<int> because the return statement returns an integer. 
//  - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the 
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync. 
    //  - AccessTheWebAsync can't continue until getStringTask is complete. 
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
    //  - Control resumes here when getStringTask is complete.  
    //  - The await operator then retrieves the string result from getStringTask. 
    string urlContents = await getStringTask;

    // The return statement specifies an integer result. 
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
    return urlContents.Length;
}

Quoting:

If AccessTheWebAsync doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.

string urlContents = await client.GetStringAsync();

More details are in the link.

Cannot ping AWS EC2 instance

You have to open following security port in the security group. Each rule is for different purposes, as shown below.

enter image description here

  1. ALL ICMP for ping.

  2. HTTP for accessing URL on HTTP port.

  3. HTTPS for accessing URL on Secured HTTP port.

As per your requirement you can change SOURCE

How do I get the latest version of my code?

If you just want to throw away everything in your working folder (eg the results of a failed or aborted merge) and revert to a clean previous commit, do a git reset --hard.

How to make Twitter Bootstrap menu dropdown on hover rather than click

I created a pure on hover dropdown menu based on the latest (v2.0.2) Bootstrap framework that has support for multiple submenus and thought I'd post it for future users:

_x000D_
_x000D_
body {_x000D_
  padding-top: 60px;_x000D_
  padding-bottom: 40px;_x000D_
}_x000D_
_x000D_
.sidebar-nav {_x000D_
  padding: 9px 0;_x000D_
}_x000D_
_x000D_
.dropdown-menu .sub-menu {_x000D_
  left: 100%;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  visibility: hidden;_x000D_
  margin-top: -1px;_x000D_
}_x000D_
_x000D_
.dropdown-menu li:hover .sub-menu {_x000D_
  visibility: visible;_x000D_
}_x000D_
_x000D_
.dropdown:hover .dropdown-menu {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
.nav-tabs .dropdown-menu,_x000D_
.nav-pills .dropdown-menu,_x000D_
.navbar .dropdown-menu {_x000D_
  margin-top: 0;_x000D_
}_x000D_
_x000D_
.navbar .sub-menu:before {_x000D_
  border-bottom: 7px solid transparent;_x000D_
  border-left: none;_x000D_
  border-right: 7px solid rgba(0, 0, 0, 0.2);_x000D_
  border-top: 7px solid transparent;_x000D_
  left: -7px;_x000D_
  top: 10px;_x000D_
}_x000D_
_x000D_
.navbar .sub-menu:after {_x000D_
  border-top: 6px solid transparent;_x000D_
  border-left: none;_x000D_
  border-right: 6px solid #fff;_x000D_
  border-bottom: 6px solid transparent;_x000D_
  left: 10px;_x000D_
  top: 11px;_x000D_
  left: -6px;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="navbar navbar-fixed-top">_x000D_
  <div class="navbar-inner">_x000D_
    <div class="container-fluid">_x000D_
      <a data-target=".nav-collapse" data-toggle="collapse" class="btn btn-navbar">_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
      </a>_x000D_
      <a href="#" class="brand">Project name</a>_x000D_
      <div class="nav-collapse">_x000D_
        <ul class="nav">_x000D_
          <li class="active"><a href="#">Home</a></li>_x000D_
          <li><a href="#">Link</a></li>_x000D_
          <li><a href="#">Link</a></li>_x000D_
          <li><a href="#">Link</a></li>_x000D_
          <li class="dropdown">_x000D_
            <a data-toggle="dropdown" class="dropdown-toggle" href="#">Dropdown <b class="caret"></b></a>_x000D_
            <ul class="dropdown-menu">_x000D_
              <li>_x000D_
                <a href="#">2-level Dropdown <i class="icon-arrow-right"></i></a>_x000D_
                <ul class="dropdown-menu sub-menu">_x000D_
                  <li><a href="#">Action</a></li>_x000D_
                  <li><a href="#">Another action</a></li>_x000D_
                  <li><a href="#">Something else here</a></li>_x000D_
                  <li class="divider"></li>_x000D_
                  <li class="nav-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a></li>_x000D_
                  <li><a href="#">One more separated link</a></li>_x000D_
                </ul>_x000D_
              </li>_x000D_
              <li><a href="#">Another action</a></li>_x000D_
              <li><a href="#">Something else here</a></li>_x000D_
              <li class="divider"></li>_x000D_
              <li class="nav-header">Nav header</li>_x000D_
              <li><a href="#">Separated link</a></li>_x000D_
              <li><a href="#">One more separated link</a></li>_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
        <form action="" class="navbar-search pull-left">_x000D_
          <input type="text" placeholder="Search" class="search-query span2">_x000D_
        </form>_x000D_
        <ul class="nav pull-right">_x000D_
          <li><a href="#">Link</a></li>_x000D_
          <li class="divider-vertical"></li>_x000D_
          <li class="dropdown">_x000D_
            <a class="#" href="#">Menu</a>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </div>_x000D_
      <!-- /.nav-collapse -->_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<ul class="nav nav-pills">_x000D_
  <li class="active"><a href="#">Regular link</a></li>_x000D_
  <li class="dropdown">_x000D_
    <a href="#" data-toggle="dropdown" class="dropdown-toggle">Dropdown <b class="caret"></b></a>_x000D_
    <ul class="dropdown-menu" id="menu1">_x000D_
      <li>_x000D_
        <a href="#">2-level Menu <i class="icon-arrow-right"></i></a>_x000D_
        <ul class="dropdown-menu sub-menu">_x000D_
          <li><a href="#">Action</a></li>_x000D_
          <li><a href="#">Another action</a></li>_x000D_
          <li><a href="#">Something else here</a></li>_x000D_
          <li class="divider"></li>_x000D_
          <li class="nav-header">Nav header</li>_x000D_
          <li><a href="#">Separated link</a></li>_x000D_
          <li><a href="#">One more separated link</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Another action</a></li>_x000D_
      <li><a href="#">Something else here</a></li>_x000D_
      <li class="divider"></li>_x000D_
      <li><a href="#">Separated link</a></li>_x000D_
    </ul>_x000D_
  </li>_x000D_
  <li class="dropdown">_x000D_
    <a href="#">Menu</a>_x000D_
  </li>_x000D_
  <li class="dropdown">_x000D_
    <a href="#">Menu</a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Demo

ECMAScript 6 class destructor

I just came across this question in a search about destructors and I thought there was an unanswered part of your question in your comments, so I thought I would address that.

thank you guys. But what would be a good convention if ECMAScript doesn't have destructors? Should I create a method called destructor and call it manually when I'm done with the object? Any other idea?

If you want to tell your object that you are now done with it and it should specifically release any event listeners it has, then you can just create an ordinary method for doing that. You can call the method something like release() or deregister() or unhook() or anything of that ilk. The idea is that you're telling the object to disconnect itself from anything else it is hooked up to (deregister event listeners, clear external object references, etc...). You will have to call it manually at the appropriate time.

If, at the same time you also make sure there are no other references to that object, then your object will become eligible for garbage collection at that point.

ES6 does have weakMap and weakSet which are ways of keeping track of a set of objects that are still alive without affecting when they can be garbage collected, but it does not provide any sort of notification when they are garbage collected. They just disappear from the weakMap or weakSet at some point (when they are GCed).


FYI, the issue with this type of destructor you ask for (and probably why there isn't much of a call for it) is that because of garbage collection, an item is not eligible for garbage collection when it has an open event handler against a live object so even if there was such a destructor, it would never get called in your circumstance until you actually removed the event listeners. And, once you've removed the event listeners, there's no need for the destructor for this purpose.

I suppose there's a possible weakListener() that would not prevent garbage collection, but such a thing does not exist either.


FYI, here's another relevant question Why is the object destructor paradigm in garbage collected languages pervasively absent?. This discussion covers finalizer, destructor and disposer design patterns. I found it useful to see the distinction between the three.


Edit in 2020 - proposal for object finalizer

There is a Stage 3 EMCAScript proposal to add a user-defined finalizer function after an object is garbage collected.

A canonical example of something that would benefit from a feature like this is an object that contains a handle to an open file. If the object is garbage collected (because no other code still has a reference to it), then this finalizer scheme allows one to at least put a message to the console that an external resource has just been leaked and code elsewhere should be fixed to prevent this leak.

If you read the proposal thoroughly, you will see that it's nothing like a full-blown destructor in a language like C++. This finalizer is called after the object has already been destroyed and you have to predetermine what part of the instance data needs to be passed to the finalizer for it to do its work. Further, this feature is not meant to be relied upon for normal operation, but rather as a debugging aid and as a backstop against certain types of bugs. You can read the full explanation for these limitations in the proposal.

Check for null variable in Windows batch

Late answer, but currently the accepted one is at least suboptimal.

Using quotes is ALWAYS better than using any other characters to enclose %1.
Because when %1 contains spaces or special characters like &, the IF [%1] == simply stops with a syntax error.

But for the case that %1 contains quotes, like in myBatch.bat "my file.txt", a simple IF "%1" == "" would fail.

But as you can't know if quotes are used or not, there is the syntax %~1, this removes enclosing quotes when necessary.

Therefore, the code should look like

set "file1=%~1"
IF "%~1"=="" set "file1=default file"

type "%file1%"   --- always enclose your variables in quotes

If you have to handle stranger and nastier arguments like myBatch.bat "This & will "^&crash
Then take a look at SO:How to receive even the strangest command line parameters?

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

How to change the default charset of a MySQL table?

If someone is searching for a complete solution for changing default charset for all database tables and converting the data, this could be one:

DELIMITER $$

CREATE PROCEDURE `exec_query`(IN sql_text VARCHAR(255))
BEGIN
  SET @tquery = `sql_text`;
  PREPARE `stmt` FROM @tquery;
  EXECUTE `stmt`;
  DEALLOCATE PREPARE `stmt`;
END$$

CREATE PROCEDURE `change_character_set`(IN `charset` VARCHAR(64), IN `collation` VARCHAR(64))
BEGIN
DECLARE `done` BOOLEAN DEFAULT FALSE;
DECLARE `tab_name` VARCHAR(64);
DECLARE `charset_cursor` CURSOR FOR 
    SELECT `table_name` FROM `information_schema`.`tables`
    WHERE `table_schema` = DATABASE() AND `table_type` = 'BASE TABLE';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET `done` = TRUE;

SET foreign_key_checks = 0;
OPEN `charset_cursor`;
`change_loop`: LOOP
FETCH `charset_cursor` INTO `tab_name`;
IF `done` THEN
    LEAVE `change_loop`;
END IF;
CALL `exec_query`(CONCAT(
  'ALTER TABLE `',
  tab_name,
  '` CONVERT TO CHARACTER SET ',
  QUOTE(charset),
  ' COLLATE ',
  QUOTE(collation),
  ';'
));
CALL `exec_query`(CONCAT('REPAIR TABLE `', tab_name, '`;'));
CALL `exec_query`(CONCAT('OPTIMIZE TABLE `', tab_name, '`;'));
END LOOP `change_loop`;
CLOSE `charset_cursor`;
SET foreign_key_checks = 1;
END$$

DELIMITER ;

You can place this code inside the file e.g. chg_char_set.sql and execute it e.g. by calling it from MySQL terminal:

SOURCE ~/path-to-the-file/chg_char_set.sql

Then call defined procedure with desired input parameters e.g.

CALL change_character_set('utf8mb4', 'utf8mb4_bin');

Once you've tested the results, you can drop those stored procedures:

DROP PROCEDURE `change_character_set`;
DROP PROCEDURE `exec_query`;

Run text file as commands in Bash

You can use something like this:

for i in `cat foo.txt`
do
    sudo $i
done

Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo as a command. But it gives you an idea on how to start.

How to get the onclick calling object?

pass in this in the inline click handler

<a href="123.com" onclick="click123(this);">link</a>

or use event.target in the function (according to the W3C DOM Level 2 Event model)

function click123(event)
{
    var a = event.target;
}

But of course, IE is different, so the vanilla JavaScript way of handling this is

function doSomething(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
}

or less verbose

function doSomething(e) {

    e = e || window.event;
    var targ = e.target || e.srcElement || e;
    if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
}

where e is the event object that is passed to the function in browsers other than IE.

If you're using jQuery though, I would strongly encourage unobtrusive JavaScript and use jQuery to bind event handlers to elements.

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

In my case the reason was in this line:

Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.
In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

My project used a third-party plugin, that is incompatible with the newest gradle plugin version. So updating plugins versions may help to solve the issue.

Iterator Loop vs index loop

Iterators make your code more generic.
Every standard library container provides an iterator hence if you change your container class in future the loop wont be affected.

sending mail from Batch file

PowerShell comes with a built in command for it. So running directly from a .bat file:

powershell -ExecutionPolicy ByPass -Command Send-MailMessage ^
    -SmtpServer server.address.name ^
    -To [email protected] ^
    -From [email protected] ^
    -Subject Testing ^
    -Body 123

NB -ExecutionPolicy ByPass is only needed if you haven't set up permissions for running PS from CMD

Also for those looking to call it from within powershell, drop everything before -Command [inclusive], and ` will be your escape character (not ^)

Extract month and year from a zoo::yearmon object

The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:

cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012

How does Content Security Policy (CSP) work?

The Content-Security-Policy meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.

I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.

For brevity I won’t write the full tag in each sample. Instead I'll only show the content property, so a sample that says content="default-src 'self'" means this:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

1. How can I allow multiple sources?

You can simply list your sources after a directive as a space-separated list:

content="default-src 'self' https://example.com/js/"

Note that there are no quotes around parameters other than the special ones, like 'self'. Also, there's no colon (:) after the directive. Just the directive, then a space-separated list of parameters.

Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:

https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js

These, however, would not be valid:

http://example.com/js/file.js
^^^^ wrong protocol

https://example.com/file.js
                   ^^ above the specified path

2. How can I use different directives? What do they each do?

The most common directives are:

  • default-src the default policy for loading javascript, images, CSS, fonts, AJAX requests, etc
  • script-src defines valid sources for javascript files
  • style-src defines valid sources for css files
  • img-src defines valid sources for images
  • connect-src defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400 error

There are others, but these are the ones you're most likely to need.

3. How can I use multiple directives?

You define all your directives inside one meta-tag by terminating them with a semicolon (;):

content="default-src 'self' https://example.com/js/; style-src 'self'"

4. How can I handle ports?

Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:

content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"

The above would result in:

https://ajax.googleapis.com:123
                           ^^^^ Not ok, wrong port

https://ajax.googleapis.com - OK

http://example.com/free/stuff/file.js
                 ^^ Not ok, only the port 123 is allowed

http://example.com:123/free/stuff/file.js - OK

As I mentioned, you can also use an asterisk to explicitly allow all ports:

content="default-src example.com:*"

5. How can I handle different protocols?

By default, only standard protocols are allowed. For example to allow WebSockets ws:// you will have to allow it explicitly:

content="default-src 'self'; connect-src ws:; style-src 'self'"
                                         ^^^ web Sockets are now allowed on all domains and ports.

6. How can I allow the file protocol file://?

If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem parameter:

content="default-src filesystem"

7. How can I use inline scripts and style definitions?

Unless explicitly allowed, you can't use inline style definitions, code inside <script> tags or in tag properties like onclick. You allow them like so:

content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"

You'll also have to explicitly allow inline, base64 encoded images:

content="img-src data:"

8. How can I allow eval()?

I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:

content="script-src 'unsafe-eval'"

9. What exactly does 'self' mean?

You might take 'self' to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.

I've used 'self' in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.

But hang on a minute! Can't I just use content="default-src *" and be done with it?

No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:

content="default-src * 'unsafe-inline' 'unsafe-eval'"

... but I trust you won’t.

Further reading:

http://content-security-policy.com

http://en.wikipedia.org/wiki/Content_Security_Policy

Lightweight workflow engine for Java

The question is what you really want to achieve when you asking for a workflow engine.

The general goal which you would like to achieve by using a workflow engine, is to become more flexible in changing your business logic during runtime. The modelling part is surely one of the most important here. BPMN 2.0 is a de-facto standard in this area and all of the discussed engines support this standard.

The second goal is to control the business process in the way of describing the 'what should happen when...' questions. And this part has a lot to do with the business requirements you are confronted within your project.

Some of the workflow engines (Activity, JBPM) can help you to answer this requirement by 'coding' your processes. This means that you model the 'what should happen when..' paradigm in a way, where you decide which part of your code (e.g a task or an event) should be executed by the workflow engine in various situations. A lot of discussion is going about this concept. And developers naturally ask whether this may not even be implemented by themselves. (It is in fact not so easy as it seems at the first glance)

Some other workflow engines (Imixs-Workflow, Bonita) can help you to answer the 'what should happen when...' requirement in a more user-centric way. This is the area of Human-centric business process management, which supports human skills and activities by a task orientated workflow-engine. The focus is more on the distribution of tasks and processes inside an organisation. The workflow engine helps you to distribute a task to a certain user or user group and to secure, log and monitor a long running business process. Maybe these are the things you do not really want to implement by yourself.

So my advice is, not to mix things that need to be considered separately, because workflow covers a very wide area.

Number of regex matches

I know this is a little old, but this but here is a concise function for counting regex patterns.

def regex_cnt(string, pattern):
    return len(re.findall(pattern, string))

string = 'abc123'

regex_cnt(string, '[0-9]')

React.js, wait for setState to finish before triggering a function?

setState takes new state and optional callback function which is called after the state has been updated.

this.setState(
  {newState: 'whatever'},
  () => {/*do something after the state has been updated*/}
)

Detailed 500 error message, ASP + IIS 7.5

If you run the browser in the server and test your url of the project with the local ip you have received all errors of that project without a generally error page(for example 500 error page).

Is there a way to style a TextView to uppercase all of its letters?

It is really very disappointing that you can't do it with styles (<item name="android:textAllCaps">true</item>) or on each XML layout file with the textAllCaps attribute, and the only way to do it is actually using theString.toUpperCase() on each of the strings when you do a textViewXXX.setText(theString).

In my case, I did not wanted to have theString.toUpperCase() everywhere in my code but to have a centralized place to do it because I had some Activities and lists items layouts with TextViews that where supposed to be capitalized all the time (a title) and other who did not... so... some people may think is an overkill, but I created my own CapitalizedTextView class extending android.widget.TextView and overrode the setText method capitalizing the text on the fly.

At least, if the design changes or I need to remove the capitalized text in future versions, I just need to change to normal TextView in the layout files.

Now, take in consideration that I did this because the App's Designer actually wanted this text (the titles) in CAPS all over the App no matter the original content capitalization, and also I had other normal TextViews where the capitalization came with the the actual content.

This is the class:

package com.realactionsoft.android.widget;

import android.content.Context; 
import android.util.AttributeSet; 
import android.view.ViewTreeObserver; 
import android.widget.TextView;


public class CapitalizedTextView extends TextView implements ViewTreeObserver.OnPreDrawListener {

    public CapitalizedTextView(Context context) {
        super(context);
    }

    public CapitalizedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CapitalizedTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text.toString().toUpperCase(), type);
    }

}

And whenever you need to use it, just declare it with all the package in the XML layout:

<com.realactionsoft.android.widget.CapitalizedTextView 
        android:id="@+id/text_view_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Some will argue that the correct way to style text on a TextView is to use a SpannableString, but I think that would be even a greater overkill, not to mention more resource-consuming because you'll be instantiating another class than TextView.

Check if string contains only digits

Here's another interesting, readable way to check if a string contains only digits.

This method works by splitting the string into an array using the spread operator, and then uses the every() method to test whether all elements (characters) in the array are included in the string of digits '0123456789':

_x000D_
_x000D_
const digits_only = string => [...string].every(c => '0123456789'.includes(c));_x000D_
_x000D_
console.log(digits_only('123')); // true_x000D_
console.log(digits_only('+123')); // false_x000D_
console.log(digits_only('-123')); // false_x000D_
console.log(digits_only('123.')); // false_x000D_
console.log(digits_only('.123')); // false_x000D_
console.log(digits_only('123.0')); // false_x000D_
console.log(digits_only('0.123')); // false_x000D_
console.log(digits_only('Hello, world!')); // false
_x000D_
_x000D_
_x000D_

Remove all constraints affecting a UIView

With objectiveC

[self.superview.constraints enumerateObjectsUsingBlock:^(__kindof NSLayoutConstraint * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLayoutConstraint *constraint = (NSLayoutConstraint *)obj;
        if (constraint.firstItem == self || constraint.secondItem == self) {
            [self.superview removeConstraint:constraint];
        }
    }];
    [self removeConstraints:self.constraints];
}

How to make Java work with SQL Server?

Do not put both the old sqljdbc.jar and the new sqljdbc4.jar in your classpath - this will make it (more or less) unpredictable which classes are being used, if both of those JARs contain classes with the same qualified names.

You said you put sqljdbc4.jar in your classpath - did you remove the old sqljdbc.jar from the classpath? You said "it didn't work", what does that mean exactly? Are you sure you don't still have the old JAR in your classpath somewhere (maybe not explicitly)?

How to clear browser cache with php?

With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');

Hiding axis text in matplotlib plots

I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my image

plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

I used the tick_params call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file.

Convert String to double in Java

Used this to convert any String number to double when u need int just convert the data type from num and num2 to int ; took all the cases for any string double with Eng:"Bader Qandeel"

public static double str2doubel(String str) {
    double num = 0;
    double num2 = 0;
    int idForDot = str.indexOf('.');
    boolean isNeg = false;
    String st;
    int start = 0;
    int end = str.length();

    if (idForDot != -1) {
        st = str.substring(0, idForDot);
        for (int i = str.length() - 1; i >= idForDot + 1; i--) {
            num2 = (num2 + str.charAt(i) - '0') / 10;
        }
    } else {
        st = str;
    }

    if (st.charAt(0) == '-') {
        isNeg = true;
        start++;
    } else if (st.charAt(0) == '+') {
        start++;
    }

    for (int i = start; i < st.length(); i++) {
        if (st.charAt(i) == ',') {
            continue;
        }
        num *= 10;
        num += st.charAt(i) - '0';
    }

    num = num + num2;
    if (isNeg) {
        num = -1 * num;
    }
    return num;
}

How to take keyboard input in JavaScript?

If you are doing this in a browser, you can capture keyboard events.

  • keydown
  • keypress
  • keyup

Can all be listened to on HTML nodes in most browsers.

Webkit also supports...

  • textInput

See for more details .. http://unixpapa.com/js/key.html

Check file uploaded is in csv format

simple use "accept" and "required" in and avoiding so much typical and unwanted coding.

How to determine the version of Gradle?

I running the following in my project:

./gradlew --version

------------------------------------------------------------
Gradle 4.7
------------------------------------------------------------

Build time:   2018-04-18 09:09:12 UTC
Revision:     b9a962bf70638332300e7f810689cb2febbd4a6c

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM:          1.8.0_212 (AdoptOpenJDK 25.212-b03)
OS:           Mac OS X 10.15 x86_64

don't fail jenkins build if execute shell fails

There is another smooth way to tell Jenkins not to fail. You can isolate your commit in a build step and set the shell to not fail:

set +e
git commit -m "Bla."
set -e

Do I need a content-type header for HTTP GET requests?

The problem with not passing over the content-type on a GET message is that sure the content-type is irrelevant because the server side determines the content anyway. The problem that I have encountered is that there are now a lot of places that set up their webservices to be smart enough to pick up the content-type that you pass and return the response in the 'type' that you request. Eg. we are currently messaging with a place that defaults to JSON, however, they have set their webservice up so that if you pass a content-type of xml they will then return xml rather than their JSON default. Which I think going forward is a great idea

Composer killed while updating

DigitalOcean fix that does not require extra memory - activating swap, here is an example for 1gb:

in terminal run below

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
sudo /sbin/swapon /var/swap.1

The above solution will work until the next reboot, after that the swap would have to be reactivated. To persist it between the reboots add the swap file to fstab:

sudo nano /etc/fstab

open the above file add add below line to the file

/var/swap.1 swap swap sw 0 0

now restart the server. Composer require works fine.

Android: Quit application when press back button

Use this code very simple solution

 @Override
    public void onBackPressed() {
      super.onBackPressed(); // this line close the  app on backpress
 }

How can I set the aspect ratio in matplotlib?

After many years of success with the answers above, I have found this not to work again - but I did find a working solution for subplots at

https://jdhao.github.io/2017/06/03/change-aspect-ratio-in-mpl

With full credit of course to the author above (who can perhaps rather post here), the relevant lines are:

ratio = 1.0
xleft, xright = ax.get_xlim()
ybottom, ytop = ax.get_ylim()
ax.set_aspect(abs((xright-xleft)/(ybottom-ytop))*ratio)

The link also has a crystal clear explanation of the different coordinate systems used by matplotlib.

Thanks for all great answers received - especially @Yann's which will remain the winner.

How to get a variable value if variable name is stored as string?

Based on the answer: https://unix.stackexchange.com/a/111627

###############################################################################
# Summary: Returns the value of a variable given it's name as a string.
# Required Positional Argument: 
#   variable_name - The name of the variable to return the value of
# Returns: The value if variable exists; otherwise, empty string ("").
###############################################################################
get_value_of()
{
    variable_name=$1
    variable_value=""
    if set | grep -q "^$variable_name="; then
        eval variable_value="\$$variable_name"
    fi
    echo "$variable_value"
}

test=123
get_value_of test
# 123
test="\$(echo \"something nasty\")"
get_value_of test
# $(echo "something nasty")

How can I programmatically check whether a keyboard is present in iOS app?

Using the window subview hierarchy as indication for keyboard showing is a hack. If Apple changers their underlying implementation all these answers would break.

The correct way would be to monitor Keyboard show and hide notifications application wide such as inside your App Delegate:

In AppDelegate.h:

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (assign, nonatomic) BOOL keyboardIsShowing;

@end

In AppDelegate.m:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Monitor keyboard status application wide
    self.keyboardIsShowing = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:)
                                             name:UIKeyboardWillHideNotification object:nil];

    return YES;
}

- (void)keyboardWillShow:(NSNotification*)aNotification
{
    self.keyboardIsShowing = YES;
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    self.keyboardIsShowing = NO;
}

Then you can check using:

BOOL keyboardIsShowing = ((AppDelegate*)[UIApplication sharedApplication].delegate).keyboardIsShowing;

It should be noted the keyboard show/hide notifications will not fire when user is using a bluetooth or external keyboard.

Run function in script from command line (Node JS)

No comment on why you want to do this, or what might be a more standard practice: here is a solution to your question.... Keep in mind that the type of quotes required by your command line may vary.

In your db.js, export the init function. There are many ways, but for example:

module.exports.init = function () {
  console.log('hi');
};

Then call it like this, assuming your db.js is in the same directory as your command prompt:

node -e 'require("./db").init()'

To other readers, the OP's init function could have been called anything, it is not important, it is just the specific name used in the question.

Difference between web reference and service reference?

Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)

They are designed to work with WCF.

If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP

Javascript: Easier way to format numbers?

No, there is no built-in support for number formatting, but googling will turn up loads of code snippets that will do this for you.

EDIT: I missed the last sentence of your post. Try http://code.google.com/p/jquery-utils/wiki/StringFormat for a jQuery solution.

Access is denied when attaching a database

enter image description here

USE [master]
GO
CREATE DATABASE [DataBasename] ON 
( FILENAME = N'C:\data\DataBasename.mdf' )
 FOR ATTACH
GO

change to FOR ATTACH -- > FOR ATTACH_FORCE_REBUILD_LOG

USE [master]
GO
CREATE DATABASE [DataBasename] ON 
( FILENAME = N'C:\data\DataBasename.mdf' )
 FOR ATTACH_FORCE_REBUILD_LOG
GO

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

I used the header("Access-Control-Allow-Origin: *"); method but still received the CORS error. It turns out that the PHP script that was being requested had an error in it (I had forgotten to add a period (.) when concatenating two variables). Once I fixed that typo, it worked!

So, It seems that the remote script being called cannot have errors within it.

How to put a symbol above another in LaTeX?

${a \atop \#}$

or

${a \above 0pt \#}$

How can I create basic timestamps or dates? (Python 3.4)

Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:

import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

The output:

Timestamp: 2014-10-18 21:31:12

Timestamp: 2014-Oct-18 21:31:12

Date now: 2014-10-18 21:31:12.318340

Date today: 2014-10-18

Today's date is Oct, 18 2014

Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific

Maintenance: October, 18 2014 - 1 PM to 6 PM Central

Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior

ReactJS: Maximum update depth exceeded error

I know this has plenty of answers but since most of them are old (well, older), none is mentioning approach I grow very fond of really quick. In short:

Use functional components and hooks.

In longer:

Try to use as much functional components instead class ones especially for rendering, AND try to keep them as pure as possible (yes, data is dirty by default I know).

Two bluntly obvious benefits of functional components (there are more):

  • Pureness or near pureness makes debugging so much easier
  • Functional components remove the need for constructor boiler code

Quick proof for 2nd point - Isn't this absolutely disgusting?

constructor(props) {
        super(props);     
        this.toggle= this.toggle.bind(this);
        this.state = {
            details: false
        } 
    }  

If you are using functional components for more then rendering you are gonna need the second part of great duo - hooks. Why are they better then lifecycle methods, what else can they do and much more would take me a lot of space to cover so I recommend you to listen to the man himself: Dan preaching the hooks

In this case you need only two hooks:

A callback hook conveniently named useCallback. This way you are preventing the binding the function over and over when you re-render.

A state hook, called useState, for keeping the state despite entire component being function and executing in its entirety (yes, this is possible due to magic of hooks). Within that hook you will store the value of toggle.

If you read to this part you probably wanna see all I have talked about in action and applied to original problem. Here you go: Demo

For those of you that want only to glance the component and WTF is this about, here you are:

const Item = () => {

    // HOOKZ
  const [isVisible, setIsVisible] = React.useState('hidden');

  const toggle = React.useCallback(() => {
    setIsVisible(isVisible === 'visible' ? 'hidden': 'visible');
  }, [isVisible, setIsVisible]);

    // RENDER
  return (
  <React.Fragment>
    <div style={{visibility: isVisible}}>
        PLACEHOLDER MORE INFO
    </div>
    <button onClick={toggle}>Details</button>
  </React.Fragment>
  )
};

PS: I wrote this in case many people land here with similar problem. Hopefully, they will like what I have shown here, at least well enough to google it a bit more. This is NOT me saying other answers are wrong, this is me saying that since the time they have been written, there is another way (IMHO, a better one) of dealing with this.