Programs & Examples On #Hdfs

Hadoop Distributed File System (HDFS) is the primary storage system used by Hadoop applications. HDFS creates multiple replicas of data blocks and distributes them on compute nodes throughout a cluster to enable reliable, extremely rapid computations.

Spark - load CSV file as DataFrame?

Parse CSV and load as DataFrame/DataSet with Spark 2.x

First, initialize SparkSession object by default it will available in shells as spark

val spark = org.apache.spark.sql.SparkSession.builder
        .master("local") # Change it as per your cluster
        .appName("Spark CSV Reader")
        .getOrCreate;

Use any one of the following ways to load CSV as DataFrame/DataSet

1. Do it in a programmatic way

 val df = spark.read
         .format("csv")
         .option("header", "true") //first line in file has headers
         .option("mode", "DROPMALFORMED")
         .load("hdfs:///csv/file/dir/file.csv")

Update: Adding all options from here in case the link will be broken in future

  • path: location of files. Similar to Spark can accept standard Hadoop globbing expressions.
  • header: when set to true the first line of files will be used to name columns and will not be included in data. All types will be assumed string. The default value is false.
  • delimiter: by default columns are delimited using, but delimiter can be set to any character
  • quote: by default the quote character is ", but can be set to any character. Delimiters inside quotes are ignored
  • escape: by default, the escape character is , but can be set to any character. Escaped quote characters are ignored
  • parserLib: by default, it is "commons" that can be set to "univocity" to use that library for CSV parsing.
  • mode: determines the parsing mode. By default it is PERMISSIVE. Possible values are:
    • PERMISSIVE: tries to parse all lines: nulls are inserted for missing tokens and extra tokens are ignored.
    • DROPMALFORMED: drops lines which have fewer or more tokens than expected or tokens which do not match the schema
    • FAILFAST: aborts with a RuntimeException if encounters any malformed line charset: defaults to 'UTF-8' but can be set to other valid charset names
  • inferSchema: automatically infers column types. It requires one extra pass over the data and is false by default comment: skip lines beginning with this character. Default is "#". Disable comments by setting this to null.
  • nullValue: specifies a string that indicates a null value, any fields matching this string will be set as nulls in the DataFrame
  • dateFormat: specifies a string that indicates the date format to use when reading dates or timestamps. Custom date formats follow the formats at java.text.SimpleDateFormat. This applies to both DateType and TimestampType. By default, it is null which means trying to parse times and date by java.sql.Timestamp.valueOf() and java.sql.Date.valueOf().

2. You can do this SQL way as well

 val df = spark.sql("SELECT * FROM csv.`hdfs:///csv/file/dir/file.csv`")

Dependencies:

 "org.apache.spark" % "spark-core_2.11" % 2.0.0,
 "org.apache.spark" % "spark-sql_2.11" % 2.0.0,

Spark version < 2.0

val df = sqlContext.read
    .format("com.databricks.spark.csv")
    .option("header", "true") 
    .option("mode", "DROPMALFORMED")
    .load("csv/file/path"); 

Dependencies:

"org.apache.spark" % "spark-sql_2.10" % 1.6.0,
"com.databricks" % "spark-csv_2.10" % 1.6.0,
"com.univocity" % "univocity-parsers" % LATEST,

Where does Hive store files in HDFS?

Hive tables may not necessarily be stored in a warehouse (since you can create tables located anywhere on the HDFS).

You should use DESCRIBE FORMATTED <table_name> command.

hive -S -e "describe formatted <table_name> ;" | grep 'Location' | awk '{ print $NF }'

Please note that partitions may be stored in different places and to get the location of the alpha=foo/beta=bar partition you'd have to add partition(alpha='foo',beta='bar') after <table_name>.

Name node is in safe mode. Not able to leave

use below command to turn off the safe mode

$> hdfs dfsadmin -safemode leave

hadoop copy a local file system folder to HDFS

In Short

hdfs dfs -put <localsrc> <dest>

In detail with example:

Checking source and target before placing files into HDFS

[cloudera@quickstart ~]$ ll files/
total 132
-rwxrwxr-x 1 cloudera cloudera  5387 Nov 14 06:33 cloudera-manager
-rwxrwxr-x 1 cloudera cloudera  9964 Nov 14 06:33 cm_api.py
-rw-rw-r-- 1 cloudera cloudera   664 Nov 14 06:33 derby.log
-rw-rw-r-- 1 cloudera cloudera 53655 Nov 14 06:33 enterprise-deployment.json
-rw-rw-r-- 1 cloudera cloudera 50515 Nov 14 06:33 express-deployment.json

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 1 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging

Copy files HDFS using -put or -copyFromLocal command

[cloudera@quickstart ~]$ hdfs dfs -put files/ files

Verify the result in HDFS

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 2 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 06:34 files

[cloudera@quickstart ~]$ hdfs dfs -ls files
Found 5 items
-rw-r--r--   1 cloudera cloudera       5387 2017-11-14 06:34 files/cloudera-manager
-rw-r--r--   1 cloudera cloudera       9964 2017-11-14 06:34 files/cm_api.py
-rw-r--r--   1 cloudera cloudera        664 2017-11-14 06:34 files/derby.log
-rw-r--r--   1 cloudera cloudera      53655 2017-11-14 06:34 files/enterprise-deployment.json
-rw-r--r--   1 cloudera cloudera      50515 2017-11-14 06:34 files/express-deployment.json

How to fix corrupt HDFS FIles

If you just want to get your HDFS back to normal state and don't worry much about the data, then

This will list the corrupt HDFS blocks:

hdfs fsck -list-corruptfileblocks

This will delete the corrupted HDFS blocks:

hdfs fsck / -delete

Note that, you might have to use sudo -u hdfs if you are not the sudo user (assuming "hdfs" is name of the sudo user)

Namenode not getting started

If you facing this issue after rebooting the system, Then below steps will work fine

For workaround.

1) format the namenode: bin/hadoop namenode -format

2) start all processes again:bin/start-all.sh

For Perm fix: -

1) go to /conf/core-site.xml change fs.default.name to your custom one.

2) format the namenode: bin/hadoop namenode -format

3) start all processes again:bin/start-all.sh

The way to check a HDFS directory's size?

Extending to Matt D and others answers, the command can be till Apache Hadoop 3.0.0

hadoop fs -du [-s] [-h] [-v] [-x] URI [URI ...]

It displays sizes of files and directories contained in the given directory or the length of a file in case it's just a file.

Options:

  • The -s option will result in an aggregate summary of file lengths being displayed, rather than the individual files. Without the -s option, the calculation is done by going 1-level deep from the given path.
  • The -h option will format file sizes in a human-readable fashion (e.g 64.0m instead of 67108864)
  • The -v option will display the names of columns as a header line.
  • The -x option will exclude snapshots from the result calculation. Without the -x option (default), the result is always calculated from all INodes, including all snapshots under the given path.

du returns three columns with the following format:

 +-------------------------------------------------------------------+ 
 | size  |  disk_space_consumed_with_all_replicas  |  full_path_name | 
 +-------------------------------------------------------------------+ 

##Example command:

hadoop fs -du /user/hadoop/dir1 \
    /user/hadoop/file1 \
    hdfs://nn.example.com/user/hadoop/dir1 

Exit Code: Returns 0 on success and -1 on error.

source: Apache doc

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Some of the data processing requirements doesn't need sort at all. Syncsort had made the sorting in Hadoop pluggable. Here is a nice blog from them on sorting. The process of moving the data from the mappers to the reducers is called shuffling, check this article for more information on the same.

How to copy file from HDFS to the local file system

If your source "file" is split up among multiple files (maybe as the result of map-reduce) that live in the same directory tree, you can copy that to a local file with:

hadoop fs -getmerge /hdfs/source/dir_root/ local/destination

How to list all files in a directory and its subdirectories in hadoop hdfs

Here is a code snippet, that counts number of files in a particular HDFS directory (I used this to determine how many reducers to use in a particular ETL code). You can easily modify this to suite your needs.

private int calculateNumberOfReducers(String input) throws IOException {
    int numberOfReducers = 0;
    Path inputPath = new Path(input);
    FileSystem fs = inputPath.getFileSystem(getConf());
    FileStatus[] statuses = fs.globStatus(inputPath);
    for(FileStatus status: statuses) {
        if(status.isDirectory()) {
            numberOfReducers += getNumberOfInputFiles(status, fs);
        } else if(status.isFile()) {
            numberOfReducers ++;
        }
    }
    return numberOfReducers;
}

/**
 * Recursively determines number of input files in an HDFS directory
 *
 * @param status instance of FileStatus
 * @param fs instance of FileSystem
 * @return number of input files within particular HDFS directory
 * @throws IOException
 */
private int getNumberOfInputFiles(FileStatus status, FileSystem fs) throws IOException  {
    int inputFileCount = 0;
    if(status.isDirectory()) {
        FileStatus[] files = fs.listStatus(status.getPath());
        for(FileStatus file: files) {
            inputFileCount += getNumberOfInputFiles(file, fs);
        }
    } else {
        inputFileCount ++;
    }

    return inputFileCount;
}

Permission denied at hdfs

I've solved this problem by using following steps

su hdfs
hadoop fs -put /usr/local/input-data/ /input
exit

Hive load CSV with commas in quoted fields

Add a backward slash in FIELDS TERMINATED BY '\;'

For Example:

CREATE  TABLE demo_table_1_csv
COMMENT 'my_csv_table 1'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\;'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION 'your_hdfs_path'
AS 
select a.tran_uuid,a.cust_id,a.risk_flag,a.lookback_start_date,a.lookback_end_date,b.scn_name,b.alerted_risk_category,
CASE WHEN (b.activity_id is not null ) THEN 1 ELSE 0 END as Alert_Flag 
FROM scn1_rcc1_agg as a LEFT OUTER JOIN scenario_activity_alert as b ON a.tran_uuid = b.activity_id;

I have tested it, and it worked.

What are the pros and cons of parquet format compared to other formats?

Avro is a row-based storage format for Hadoop.

Parquet is a column-based storage format for Hadoop.

If your use case typically scans or retrieves all of the fields in a row in each query, Avro is usually the best choice.

If your dataset has many columns, and your use case typically involves working with a subset of those columns rather than entire records, Parquet is optimized for that kind of work.

Source

How to copy data from one HDFS to another HDFS?

Try dtIngest, it's developed on top of Apache Apex platform. This tool copies data from different sources like HDFS, shared drive, NFS, FTP, Kafka to different destinations. Copying data from remote HDFS cluster to local HDFS cluster is supported by dtIngest. dtIngest runs yarn jobs to copy data in parallel fashion, so it's very fast. It takes care of failure handling, recovery etc. and supports polling directories periodically to do continious copy.

Usage: dtingest [OPTION]... SOURCEURL... DESTINATIONURL example: dtingest hdfs://nn1:8020/source hdfs://nn2:8020/dest

How to insert a character in a string at a certain position?

  public static void main(String[] args) {
    char ch='m';
    String str="Hello",k=String.valueOf(ch),b,c;

    System.out.println(str);

    int index=3;
    b=str.substring(0,index-1 );
    c=str.substring(index-1,str.length());
    str=b+k+c;
}

what's data-reactid attribute in html?

The data-reactid attribute is a custom attribute used so that React can uniquely identify its components within the DOM.

This is important because React applications can be rendered at the server as well as the client. Internally React builds up a representation of references to the DOM nodes that make up your application (simplified version is below).

{
  id: '.1oqi7occu80',
  node: DivRef,
  children: [
    {
      id: '.1oqi7occu80.0',
      node: SpanRef,
      children: [
        {
          id: '.1oqi7occu80.0.0',
          node: InputRef,
          children: []
        }
      ]
    }
  ]
}

There's no way to share the actual object references between the server and the client and sending a serialized version of the entire component tree is potentially expensive. When the application is rendered at the server and React is loaded at the client, the only data it has are the data-reactid attributes.

<div data-reactid='.loqi70ccu80'>
  <span data-reactid='.loqi70ccu80.0'>
    <input data-reactid='.loqi70ccu80.0' />
  </span>
</div>

It needs to be able to convert that back into the data structure above. The way it does that is with the unique data-reactid attributes. This is called inflating the component tree.

You might also notice that if React renders at the client-side, it uses the data-reactid attribute, even though it doesn't need to lose its references. In some browsers, it inserts your application into the DOM using .innerHTML then it inflates the component tree straight away, as a performance boost.

The other interesting difference is that client-side rendered React ids will have an incremental integer format (like .0.1.4.3), whereas server-rendered ones will be prefixed with a random string (such as .loqi70ccu80.1.4.3). This is because the application might be rendered across multiple servers and it's important that there are no collisions. At the client-side, there is only one rendering process, which means counters can be used to ensure unique ids.

React 15 uses document.createElement instead, so client rendered markup won't include these attributes anymore.

Eclipse count lines of code

One possible way to count lines of code in Eclipse:

using the Search / File... menu, select File Search tab, specify \n[\s]* for Containing text (this will not count empty lines), and tick Regular expression.

Hat tip: www.monblocnotes.com/node/2030

Let JSON object accept bytes or let urlopen output strings

I have come to opinion that the question is the best answer :)

import json
from urllib.request import urlopen

response = urlopen("site.com/api/foo/bar").read().decode('utf8')
obj = json.loads(response)

PHP if not statements

I think this is the best and easiest way to do it:

if (!(isset($action) && ($action == "add" || $action == "delete")))

Merge development branch with master

1) On branch Development, check git status using following command:

git status

There should be no uncommitted code. If it is, push your code on Development branch:

git add *

git commit -m "My initial commit message"

git push origin Development

2) On Development branch, run following two commands:

git branch -f master HEAD

git push -f origin master

It will push your Development branch code to master branch.

find all subsets that sum to a particular value

I have found that so many interviews are asking for this so I implemented a really quite simple and understandable solution. First I generate all the possible combinations, and from there, you can do whatever you want. Check this out:

public static void main(String[] args) {
        int[] numbers = new int[]{1, 2, 3, 4, 5};
        List<int[]> allPossibleCombinatiosForNumbers = new ArrayList<>();
        for (int i = 2; i < numbers.length; i++) {
            allPossibleCombinatiosForNumbers.addAll(getCombinationsOfNElements(numbers, i));
        }
        for (int[] combination : allPossibleCombinatiosForNumbers) {
            printArray(combination);
            printArrayIfNumbersSumExpectedValue(combination, 6);
        }
    }


    private static List<int[]> getCombinationsOfNElements(int[] numbers, int n) {
        int elementsKnown = n - 1;
        List<int[]> allCombinationsOfNElements = new ArrayList<>();
        for (int i = 0; i < numbers.length - elementsKnown; i++) {
            int[] combination = new int[n];
            for (int j = 0; j < n; j++) {
                combination[j] = numbers[i + j];
            }
            allCombinationsOfNElements.addAll(generationCombinations(combination, i + elementsKnown, numbers));
        }
        return allCombinationsOfNElements;
    }

    private static List<int[]> generationCombinations(int[] knownElements, int index, int[] numbers) {
        List<int[]> combinations = new ArrayList<>();
        for (int i = index; i < numbers.length; i++) {
            int[] combinationComplete = Arrays.copyOf(knownElements, knownElements.length);
            combinationComplete[knownElements.length - 1] = numbers[i];
            combinations.add(combinationComplete);
        }
        return combinations;
    }

    private static void printArray(int[] numbers) {
        System.out.println();
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");
        }
    }

    private static void printArrayIfNumbersSumExpectedValue(int[] numbers, int expectedValue) {
        int total = 0;
        for (int i = 0; i < numbers.length; i++) {
            total += numbers[i];
        }
        if (total == expectedValue) {
            System.out.print("\n ----- Here is a combination you are looking for -----");
            printArray(numbers);
            System.out.print("\n -------------------------------");
        }
    }

The 'packages' element is not declared

Use <packages xmlns="urn:packages">in the place of <packages>

How to execute the start script with Nodemon

Nodemon emits events upon every change in state; start, restart crash, etc. You can add a Nodemon configuration file (nodemon.json) like so:

{
   "events": {
       "start": "npm run *your_file*"
   }
}

Read more in Nodemon events — run tasks at server start, restart, crash, exit.

Download text/csv content as files from server in Angular

This is what worked for me for IE 11+, Firefox and Chrome. In safari it downloads a file but as unknown and the filename is not set.

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvDataString]);  //csv data string as an array.
    // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
    window.navigator.msSaveBlob(blob, fileName);
} else {
    var anchor = angular.element('<a/>');
    anchor.css({display: 'none'}); // Make sure it's not visible
    angular.element(document.body).append(anchor); // Attach to document for FireFox

    anchor.attr({
        href: 'data:attachment/csv;charset=utf-8,' + encodeURI(csvDataString),
        target: '_blank',
        download: fileName
})[0].click();
anchor.remove();
}

JavaScript moving element in the DOM

jQuery.fn.swap = function(b){ 
    b = jQuery(b)[0]; 
    var a = this[0]; 
    var t = a.parentNode.insertBefore(document.createTextNode(''), a); 
    b.parentNode.insertBefore(a, b); 
    t.parentNode.insertBefore(b, t); 
    t.parentNode.removeChild(t); 
    return this; 
};

and use it like this:

$('#div1').swap('#div2');

if you don't want to use jQuery you could easily adapt the function.

How do I make a C++ macro behave like a function?

If you're willing to adopt the practice of always using curly braces in your if statements,

Your macro would simply be missing the last semicolon:

#define MACRO(X,Y)                       \
cout << "1st arg is:" << (X) << endl;    \
cout << "2nd arg is:" << (Y) << endl;    \
cout << "Sum is:" << ((X)+(Y)) << endl

Example 1: (compiles)

if (x > y) {
    MACRO(x, y);
}
do_something();

Example 2: (compiles)

if (x > y) {
    MACRO(x, y);
} else {
    MACRO(y - x, x - y);
}

Example 3: (doesn't compile)

do_something();
MACRO(x, y)
do_something();

How to open .mov format video in HTML video Tag?

Unfortunately .mov files are not supported with html5 video playback. You can see what filetypes are supported here:

https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats

If you need to be able to play these formats with your html5 video player, you'll need to first convert your videofile--perhaps with something like this:

https://www.npmjs.com/package/html5-media-converter

How to Migrate to WKWebView?

Swift 4

    let webView = WKWebView()   // Set Frame as per requirment, I am leaving it for you
    let url = URL(string: "http://www.google.com")!
    webView.load(URLRequest(url: url))
    view.addSubview(webView)

Loop through all the resources in a .resx file

Use ResXResourceReader Class

ResXResourceReader rsxr = new ResXResourceReader("your resource file path");

// Iterate through the resources and display the contents to the console.
foreach (DictionaryEntry d in rsxr)
{
    Console.WriteLine(d.Key.ToString() + ":\t" + d.Value.ToString());
}

Launch Failed. Binary not found. CDT on Eclipse Helios

Go to the Run->Run Configuration-> now

Under C/C++ Application you will see the name of your executable + Debug (if not, click over C/C++ Application a couple of times). Select the name (in this case projectTitle+Debug).

Under this in main Tab -> C/C++ application -> Search your project -> in binaries select your binary titled by your project....

How to install Android app on LG smart TV?

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

How to fill color in a cell in VBA?

  1. Select all cells by left-top corner
  2. Choose [Home] >> [Conditional Formatting] >> [New Rule]
  3. Choose [Format only cells that contain]
  4. In [Format only cells with:], choose "Errors"
  5. Choose proper formats in [Format..] button

Rails 3.1 and Image Assets

In rails 4 you can now use a css and sass helper image-url:

div.logo {background-image: image-url("logo.png");}

If your background images aren't showing up consider looking at how you're referencing them in your stylesheets.

Including a .js file within a .js file

I use @gnarf's method, though I fall back on document.writelning a <script> tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:

if (horus.script.broken) {
    document.writeln('<script type="text/javascript" src="'+script+'"></script>');   
    horus.script.loaded(script);
} else {
    var s=document.createElement('script');
    s.type='text/javascript';
    s.src=script;
    s.async=true;

    if (horus.brokenDOM){
        s.onreadystatechange=
            function () {
                if (this.readyState=='loaded' || this.readyState=='complete'){
                    horus.script.loaded(script);
                }
        }
    }else{
        s.onload=function () { horus.script.loaded(script) };
    }

    document.head.appendChild(s);
}

where horus.script.loaded() notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).

Getting a POST variable

Use this for GET values:

Request.QueryString["key"]

And this for POST values

Request.Form["key"]

Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:

Request["key"]

Another thing to note (if you need it) is you can check the type of request by using:

Request.RequestType

Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

How to cin to a vector

#include<bits/stdc++.h>
using namespace std;

int main()
{
int x,n;
cin>>x;
vector<int> v;

cout<<"Enter numbers:\n";

for(int i=0;i<x;i++)
 {
  cin>>n;
  v.push_back(n);
 }


//displaying vector contents

 for(int p : v)
 cout<<p<<" ";
}

A simple way to take input in vector.

CSS float right not working correctly

you need to wrap your text inside div and float it left while wrapper div should have height, and I've also added line height for vertical alignment

<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray;height:30px;">
   <div style="float:left;line-height:30px;">Contact Details</div>

    <button type="button" class="edit_button" style="float: right;">My Button</button>

</div>

also js fiddle here =) http://jsfiddle.net/xQgSm/

typesafe select onChange event using reactjs and typescript

it works:

type HtmlEvent = React.ChangeEvent<HTMLSelectElement>

const onChange: React.EventHandler<HtmlEvent> = 
   (event: HtmlEvent) => { 
       console.log(event.target.value) 
   }

How to detect Windows 64-bit platform with .NET?

Here is the direct approach in C# using DllImport from this page.

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)] 
[return: MarshalAs(UnmanagedType.Bool)] 
public static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo); 

public static bool Is64Bit() 
{ 
    bool retVal; 

    IsWow64Process(Process.GetCurrentProcess().Handle, out retVal); 

    return retVal; 
} 

BackgroundWorker vs background Thread

A background worker is a class that works in a separate thread, but it provides additional functionality that you don't get with a simple Thread (like task progress report handling).

If you don't need the additional features given by a background worker - and it seems you don't - then a Thread would be more appropriate.

CSS root directory

/Images/myImage.png

this has to be in root of your domain/subdomain

http://website.to/Images/myImage.png

and it will work

However, I think it would work like this, too

  • images
    • yourimage.png
  • styles
    • style.css

style.css:

body{
    background: url(../images/yourimage.png);
}

Access 2013 - Cannot open a database created with a previous version of your application

You can do all these things but the underlying problem will be incompatibility with Windows updates of library files. Eventually you will have problems again. .ocx and .dll files will be clobbered and replaced: your database will not be able to cope with the new versions and it will not build or it will malfunction unexpectedly.

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

Remove ':hover' CSS behavior from element

I would use two classes. Keep your test class and add a second class called testhover which you only add to those you want to hover - alongside the test class. This isn't directly what you asked but without more context it feels like the best solution and is possibly the cleanest and simplest way of doing it.

Example:

_x000D_
_x000D_
.test {  border: 0px; }_x000D_
.testhover:hover {  border: 1px solid red; }
_x000D_
<div class="test"> blah </div>_x000D_
<div class="test"> blah </div>_x000D_
<div class="test testhover"> blah </div>
_x000D_
_x000D_
_x000D_

How to detect orientation change?

Here is an easy way to detect the device orientation: (Swift 3)

override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
            handleViewRotaion(orientation: toInterfaceOrientation)
        }

    //MARK: - Rotation controls
    func handleViewRotaion(orientation:UIInterfaceOrientation) -> Void {
        switch orientation {
        case .portrait :
            print("portrait view")
            break
        case .portraitUpsideDown :
            print("portraitUpsideDown view")
            break
        case .landscapeLeft :
            print("landscapeLeft view")
            break
        case .landscapeRight :
            print("landscapeRight view")
            break
        case .unknown :
            break
        }
    }

How to update single value inside specific array item in redux

You can use map. Here is an example implementation:

case 'SOME_ACTION':
   return { 
       ...state, 
       contents: state.contents.map(
           (content, i) => i === 1 ? {...content, text: action.payload}
                                   : content
       )
    }

Edit In Place Content Editing

I was looking for a inline editing solution and I found a plunker that seemed promising, but it didn't work for me out of the box. After some tinkering with the code I got it working. Kudos to the person who made the initial effort to code this piece.

The example is available here http://plnkr.co/edit/EsW7mV?p=preview

Here goes the code:

app.controller('MainCtrl', function($scope) {

  $scope.updateTodo = function(indx) {
    console.log(indx);
  };

  $scope.cancelEdit = function(value) {
    console.log('Canceled editing', value);
  };

  $scope.todos = [
    {id:123, title: 'Lord of the things'},
    {id:321, title: 'Hoovering heights'},
    {id:231, title: 'Watership brown'}
  ];
});

// On esc event
app.directive('onEsc', function() {
  return function(scope, elm, attr) {
    elm.bind('keydown', function(e) {
      if (e.keyCode === 27) {
        scope.$apply(attr.onEsc);
      }
    });
  };
});

// On enter event
app.directive('onEnter', function() {
  return function(scope, elm, attr) {
    elm.bind('keypress', function(e) {
      if (e.keyCode === 13) {
        scope.$apply(attr.onEnter);
      }
    });
  };
});

// Inline edit directive
app.directive('inlineEdit', function($timeout) {
  return {
    scope: {
      model: '=inlineEdit',
      handleSave: '&onSave',
      handleCancel: '&onCancel'
    },
    link: function(scope, elm, attr) {
      var previousValue;

      scope.edit = function() {
        scope.editMode = true;
        previousValue = scope.model;

        $timeout(function() {
          elm.find('input')[0].focus();
        }, 0, false);
      };
      scope.save = function() {
        scope.editMode = false;
        scope.handleSave({value: scope.model});
      };
      scope.cancel = function() {
        scope.editMode = false;
        scope.model = previousValue;
        scope.handleCancel({value: scope.model});
      };
    },
    templateUrl: 'inline-edit.html'
  };
});

Directive template:

<div>
  <input type="text" on-enter="save()" on-esc="cancel()" ng-model="model" ng-show="editMode">
  <button ng-click="cancel()" ng-show="editMode">cancel</button>
  <button ng-click="save()" ng-show="editMode">save</button>
  <span ng-mouseenter="showEdit = true" ng-mouseleave="showEdit = false">
    <span ng-hide="editMode" ng-click="edit()">{{model}}</span>
    <a ng-show="showEdit" ng-click="edit()">edit</a>
  </span>
</div>

To use it just add water:

<div ng-repeat="todo in todos" 
     inline-edit="todo.title" 
     on-save="updateTodo($index)" 
     on-cancel="cancelEdit(todo.title)"></div>

UPDATE:

Another option is to use the readymade Xeditable for AngularJS:

http://vitalets.github.io/angular-xeditable/

How to update Identity Column in SQL Server?

copy your table to a new table without identity column.

    select columns into newtable from yourtable

add an identity column to newtable with new seed and make it as a primary key

    ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

in my case was a wrong path in a config file: file was not found (path was wrong) and it came out with this exception:

Error configuring from input stream. Initial cause was The processing instruction target matching "[xX][mM][lL]" is not allowed.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

Change content of div - jQuery

There are 2 jQuery functions that you'll want to use here.

1) click. This will take an anonymous function as it's sole parameter, and will execute it when the element is clicked.

2) html. This will take an html string as it's sole parameter, and will replace the contents of your element with the html provided.

So, in your case, you'll want to do the following:

$('#content-container a').click(function(e){
    $(this).parent().html('<a href="#">I\'m a new link</a>');
    e.preventDefault();
});

If you only want to add content to your div, rather than replacing everything in it, you should use append:

$('#content-container a').click(function(e){
    $(this).parent().append('<a href="#">I\'m a new link</a>');
    e.preventDefault();
});

If you want the new added links to also add new content when clicked, you should use event delegation:

$('#content-container').on('click', 'a', function(e){
    $(this).parent().append('<a href="#">I\'m a new link</a>');
    e.preventDefault();
});

Why does PEP-8 specify a maximum line length of 79 characters?

Printing a monospaced font at default sizes is (on A4 paper) 80 columns by 66 lines.

Fatal error: Call to undefined function mysqli_connect()

There is no error in the, but the mysqli PHP extension is not installed on your machine. Please contact your service provider to fix this issue.

Custom circle button

if you want use VectorDrawable and ConstraintLayout

<FrameLayout
            android:id="@+id/ok_button"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:foreground="?attr/selectableItemBackgroundBorderless"
            android:background="@drawable/circle_button">
                <android.support.constraint.ConstraintLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                    <ImageView
                        android:id="@+id/icon_of_button"
                        android:layout_width="32dp"
                        android:layout_height="32dp"
                        app:layout_constraintBottom_toBottomOf="parent"
                        app:layout_constraintTop_toTopOf="parent"
                        app:layout_constraintRight_toRightOf="parent"
                        app:layout_constraintLeft_toLeftOf="parent"
                        app:srcCompat="@drawable/ic_thumbs_up"/>
                    <TextView
                        android:id="@+id/text_of_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        app:layout_constraintTop_toBottomOf="@+id/icon_of_button"
                        app:layout_constraintRight_toRightOf="parent"
                        app:layout_constraintLeft_toLeftOf="parent"
                        android:layout_marginTop="5dp"
                        android:textColor="@android:color/white"
                        android:text="ok"
                        />
                </android.support.constraint.ConstraintLayout>
            </FrameLayout>

circle background: circle_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="1000dp" />
<solid android:color="#41ba7a" />
<stroke
    android:width="2dip"
    android:color="#03ae3c" />
<padding
    android:bottom="4dp"
    android:left="4dp"
    android:right="4dp"
    android:top="4dp" />
</shape>

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

Can't find SDK folder inside Android studio path, and SDK manager not opening

So I was trying to root one of my old phones and process required Android SDK. When I searched Android SDK, all i could do was download and install Android Studio. Everything went fine and smooth, till I tried to look for SDK in installation. I could not find it under Android Studio installation. But after a little search on Google and Android Studio configuration on my computer, I was able to find it at

        C:\Users\username\Android\sdk

I hope that helps.

iterating over each character of a String in ruby 1.8.6 (each_char)

I have the same problem. I usually resort to String#split:

"ABCDEFG".split("").each do |i|
  puts i
end

I guess you could also implement it yourself like this:

class String
  def each_char
    self.split("").each { |i| yield i }
  end
end

Edit: yet another alternative is String#each_byte, available in Ruby 1.8.6, which returns the ASCII value of each char in an ASCII string:

"ABCDEFG".each_byte do |i|
  puts i.chr # Fixnum#chr converts any number to the ASCII char it represents
end

What is the { get; set; } syntax in C#?

They are the accessors for the public property Name.

You would use them to get/set the value of that property in an instance of Genre.

Call jQuery Ajax Request Each X Minutes

You have a couple options, you could setTimeout() or setInterval(). Here's a great article that elaborates on how to use them.

The magic is that they're built in to JavaScript, you can use them with any library.

How to use HTML to print header and footer on every printed page of a document?

I found one solution. The basic idea is to make a table and in thead section place the data of header in tr and by css force to show that tr only in print not in screen then your normal header should be force to show only in screen not in print. 100% working on many pages print. sample code is here

<style> 
    @media screen {
        .only_print{
            display:none;
        }
    }
    @media print {
        .no-print {
            display: none !important;
        }
    }
    TABLE{border-collapse: collapse;}
    TH, TD {border:1px solid grey;}
</style>
<div class="no-print">  <!-- This is header for screen and will not be printed -->
    <div>COMPANY NAME FOR SCREEN</div>
    <div>DESCRIPTION FOR SCREEN</div>
</div>

<table>
    <thead>
        <tr class="only_print"> <!-- This is header for print and will not be shown on screen -->
            <td colspan="100" style="border: 0px;">
                <div>COMPANY NAME FOR PRINT</div>
                <div>DESCRIPTION FOR PRINT</div>
            </td>
        </tr>
        <!-- From here Actual Data of table start -->
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1-1</td>
            <td>1-2</td>
            <td>1-3</td>
        </tr>
        <tr>
            <td>2-1</td>
            <td>2-2</td>
            <td>2-3</td>
        </tr>
    </tbody>
</table>

Screenshot sizes for publishing android app on Google Play

It has to be any one of the given sizes and a minimum of 2 but up to 8 screenshots are accepted in Google Playstore.

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

Great question... I wish there was an answer, but this is the closest you can get with CSS these days. No ellipsis, but still pretty usable.

overflow: hidden;
line-height: 1.2em;
height: 3.6em;      // 3 lines * line-height

How do I set up cron to run a file just once at a specific time?

You really want to use at. It is exactly made for this purpose.

echo /usr/bin/the_command options | at now + 1 day

However if you don't have at, or your hosting company doesn't provide access to it, you can have a cron job include code that makes sure it only runs once.

Set up a cron entry with a very specific time:

0 0 2 12 * /home/adm/bin/the_command options

Next /home/adm/bin/the_command needs to either make sure it only runs once.

#! /bin/bash

COMMAND=/home/adm/bin/the_command
DONEYET="${COMMAND}.alreadyrun"

export PATH=/usr/bin:$PATH

if [[ -f $DONEYET ]]; then
  exit 1
fi
touch "$DONEYET"

# Put the command you want to run exactly once here:
echo 'You will only get this once!' | mail -s 'Greetings!' [email protected]

Send email using the GMail SMTP server from a PHP page

The code as listed in the question needs two changes

$host = "ssl://smtp.gmail.com";
$port = "465";

Port 465 is required for an SSL connection.

How to pass variables from one php page to another without form?

check to make sure the variable is set. Then clean it before using it:

isset($_GET['var'])?$var=mysql_escape_string($_GET['var']):$var='SomeDefaualtValue';

Otherwise, assign it a default value ($var='' is fine) to avoid the error you mentioned.

javascript regex - look behind alternative?

This is an equivalent solution to Tim Pietzcker's answer (see also comments of same answer):

^(?!.*filename\.js$).*\.js$

It means, match *.js except *filename.js.

To get to this solution, you can check which patterns the negative lookbehind excludes, and then exclude exactly these patterns with a negative lookahead.

How do I cancel form submission in submit button onclick event?

you should change the type from submit to button:

<input type='button' value='submit request'>

instead of

<input type='submit' value='submit request'>

you then get the name of your button in javascript and associate whatever action you want to it

var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};

worked for me hope it helps.

How to get active user's UserDetails

Spring Security is intended to work with other non-Spring frameworks, hence it is not tightly integrated with Spring MVC. Spring Security returns the Authentication object from the HttpServletRequest.getUserPrincipal() method by default so that's what you get as the principal. You can obtain your UserDetails object directly from this by using

UserDetails ud = ((Authentication)principal).getPrincipal()

Note also that the object types may vary depending on the authentication mechanism used (you may not get a UsernamePasswordAuthenticationToken, for example) and the Authentication doesn't strictly have to contain a UserDetails. It can be a string or any other type.

If you don't want to call SecurityContextHolder directly, the most elegant approach (which I would follow) is to inject your own custom security context accessor interface which is customized to match your needs and user object types. Create an interface, with the relevant methods, for example:

interface MySecurityAccessor {

    MyUserDetails getCurrentUser();

    // Other methods
}

You can then implement this by accessing the SecurityContextHolder in your standard implementation, thus decoupling your code from Spring Security entirely. Then inject this into the controllers which need access to security information or information on the current user.

The other main benefit is that it is easy to make simple implementations with fixed data for testing, without having to worry about populating thread-locals and so on.

Best practice for Django project working directory structure

As per the Django Project Skeleton, the proper directory structure that could be followed is :

[projectname]/                  <- project root
+-- [projectname]/              <- Django root
¦   +-- __init__.py
¦   +-- settings/
¦   ¦   +-- common.py
¦   ¦   +-- development.py
¦   ¦   +-- i18n.py
¦   ¦   +-- __init__.py
¦   ¦   +-- production.py
¦   +-- urls.py
¦   +-- wsgi.py
+-- apps/
¦   +-- __init__.py
+-- configs/
¦   +-- apache2_vhost.sample
¦   +-- README
+-- doc/
¦   +-- Makefile
¦   +-- source/
¦       +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦   +-- media/
¦   ¦   +-- README
¦   +-- README
¦   +-- static/
¦       +-- README
+-- static/
¦   +-- README
+-- templates/
    +-- base.html
    +-- core
    ¦   +-- login.html
    +-- README

Refer https://django-project-skeleton.readthedocs.io/en/latest/structure.html for the latest directory structure.

What's the difference between TRUNCATE and DELETE in SQL

In short, truncate doesn't log anything (so is much faster but can't be undone) whereas delete is logged (and can be part of a larger transaction, will rollback etc). If you have data that you don't want in a table in dev it is normally better to truncate as you don't run the risk of filling up the transaction log

Java: Sending Multiple Parameters to Method

The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?

If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:

public class MyClass
{
  public void doSomething(int i) 
  {
    ...
  }

  public void doSomething(int i, String s) 
  {
    ...
  }

  public void doSomething(int i, String s, boolean b) 
  {
    ...
  }
}

If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:

public MyClass 
{
  public void doSomething(int... integers)
  {
    for (int i : integers) 
    {
      ...
    }
  }
}

Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.

How do I assign a port mapping to an existing Docker container?

I'm also interested in this problem.

As @Thasmo mentioned, port forwardings can be specified ONLY with docker run (and docker create) command.
Other commands, docker start does not have -p option and docker port only displays current forwardings.

To add port forwardings, I always follow these steps,

  1. stop running container

    docker stop test01
    
  2. commit the container

    docker commit test01 test02
    

    NOTE: The above, test02 is a new image that I'm constructing from the test01 container.

  3. re-run from the commited image

    docker run -p 8080:8080 -td test02
    

Where the first 8080 is the local port and the second 8080 is the container port.

Send password when using scp to copy files from one server to another

Here is how I resolved it.

It is not the most secure way however it solved my problem as security was not an issue on internal servers.

Create a new file say password.txt and store the password for the server where the file will be pasted. Save this to a location on the host server.

scp -W location/password.txt copy_file_location paste_file_location

Cheers!

What is the best workaround for the WCF client `using` block issue?

If you don't need IoC or are using an autogenerated client (Service Reference), then you can simple use a wrapper to manage the closing and let the GC take the clientbase when it is in a safe state that will not throw any exception. The GC will call Dispose in serviceclient, and this will call Close. Since it is alread closed, it cannot cause any damage. I am using this without problems in production code.

public class AutoCloseWcf : IDisposable
{

    private ICommunicationObject CommunicationObject;

    public AutoDisconnect(ICommunicationObject CommunicationObject)
    {
        this.CommunicationObject = CommunicationObject;
    }

    public void Dispose()
    {
        if (CommunicationObject == null)
            return;
        try {
            if (CommunicationObject.State != CommunicationState.Faulted) {
                CommunicationObject.Close();
            } else {
                CommunicationObject.Abort();
            }
        } catch (CommunicationException ce) {
            CommunicationObject.Abort();
        } catch (TimeoutException toe) {
            CommunicationObject.Abort();
        } catch (Exception e) {
            CommunicationObject.Abort();
            //Perhaps log this

        } finally {
            CommunicationObject = null;
        }
    }
}

Then when you are accessing the server, you create the client and use using in the autodisconect:

var Ws = new ServiceClient("netTcpEndPointName");
using (new AutoCloseWcf(Ws)) {

    Ws.Open();

    Ws.Test();
}

Bash tool to get nth line from a file

With awk it is pretty fast:

awk 'NR == num_line' file

When this is true, the default behaviour of awk is performed: {print $0}.


Alternative versions

If your file happens to be huge, you'd better exit after reading the required line. This way you save CPU time See time comparison at the end of the answer.

awk 'NR == num_line {print; exit}' file

If you want to give the line number from a bash variable you can use:

awk 'NR == n' n=$num file
awk -v n=$num 'NR == n' file   # equivalent

See how much time is saved by using exit, specially if the line happens to be in the first part of the file:

# Let's create a 10M lines file
for ((i=0; i<100000; i++)); do echo "bla bla"; done > 100Klines
for ((i=0; i<100; i++)); do cat 100Klines; done > 10Mlines

$ time awk 'NR == 1234567 {print}' 10Mlines
bla bla

real    0m1.303s
user    0m1.246s
sys 0m0.042s
$ time awk 'NR == 1234567 {print; exit}' 10Mlines
bla bla

real    0m0.198s
user    0m0.178s
sys 0m0.013s

So the difference is 0.198s vs 1.303s, around 6x times faster.

Get the string value from List<String> through loop for display

Try following if your looking for while loop implementation.

List<String> myString = new ArrayList<String>();

// How you add your data in string list
myString.add("Test 1");
myString.add("Test 2");
myString.add("Test 3");
myString.add("Test 4");

int i = 0;
while (i < myString.size()) {
    System.out.println(myString.get(i));
    i++;
}

What is the difference between JDK and JRE?

If you want to run Java programs, but not develop them, download the Java Run-time Environment, or JRE. If you want to develop them, download the Java Development kit, or JDK

JDK

Let's called JDK is a kit, which include what are those things need to developed and run java applications.

JDK is given as development environment for building applications, component s and applets.

JRE

It contains everything you need to run Java applications in compiled form. You don't need any libraries and other stuffs. All things you need are compiled.

JRE is can not used for development, only used for run the applications.

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

Rob Napier had already given a awesome answer using subscript. But i felt one drawback in that as there is no check for out of bound conditions. This can tend to crash. So i modified the extension and here it is

extension String {
    subscript (r: Range<Int>) -> String? { //Optional String as return value
        get {
            let stringCount = self.characters.count as Int
            //Check for out of boundary condition
            if (stringCount < r.endIndex) || (stringCount < r.startIndex){
                return nil
            }
            let startIndex = self.startIndex.advancedBy(r.startIndex)

            let endIndex = self.startIndex.advancedBy(r.endIndex - r.startIndex)

            return self[Range(start: startIndex, end: endIndex)]
        }
    }
}

Output below

var str2 = "Hello, World"

var str3 = str2[0...5]
//Hello,
var str4 = str2[0..<5]
//Hello
var str5 = str2[0..<15]
//nil

So i suggest always to check for the if let

if let string = str[0...5]
{
    //Manipulate your string safely
}

How to create a new branch from a tag?

If you simply want to create a new branch without immediately changing to it, you could do the following:

git branch newbranch v1.0

How to find current transaction level?

SELECT CASE  
          WHEN transaction_isolation_level = 1 
             THEN 'READ UNCOMMITTED' 
          WHEN transaction_isolation_level = 2 
               AND is_read_committed_snapshot_on = 1 
             THEN 'READ COMMITTED SNAPSHOT' 
          WHEN transaction_isolation_level = 2 
               AND is_read_committed_snapshot_on = 0 THEN 'READ COMMITTED' 
          WHEN transaction_isolation_level = 3 
             THEN 'REPEATABLE READ' 
          WHEN transaction_isolation_level = 4 
             THEN 'SERIALIZABLE' 
          WHEN transaction_isolation_level = 5 
             THEN 'SNAPSHOT' 
          ELSE NULL
       END AS TRANSACTION_ISOLATION_LEVEL 
FROM   sys.dm_exec_sessions AS s
       CROSS JOIN sys.databases AS d
WHERE  session_id = @@SPID
  AND  d.database_id = DB_ID();

android.content.Context.getPackageName()' on a null object reference

My class is not extends to Activiti. I solved the problem this way.

class MyOnBindViewHolder : LogicViewAdapterModel.LogicAdapter {
          ...
 holder.title.setOnClickListener({v->
                v.context.startActivity(Intent(context,  HomeActivity::class.java))
            })
          ...
    }

How to prevent Right Click option using jquery

$(document).mousedown(function(e) {
    if( e.button == 2 ) {
         e.preventDefault();
        return false;
    } 
});

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

Here is a SO thread where @Matt renders only the desired pixel into a 1x1 context by displacing the image so that the desired pixel aligns with the one pixel in the context.

error: ‘NULL’ was not declared in this scope

NULL isn't a keyword; it's a macro substitution for 0, and comes in stddef.h or cstddef, I believe. You haven't #included an appropriate header file, so g++ sees NULL as a regular variable name, and you haven't declared it.

Detecting an "invalid date" Date instance in JavaScript

A ready function based on top rated answer:

  /**
   * Check if date exists and is valid.
   *
   * @param {String} dateString Date in YYYY-mm-dd format.
   */
  function isValidDate(dateString) {
  var isValid = false;
  var date;

  date =
    new Date(
      dateString);

  if (
    Object.prototype.toString.call(
      date) === "[object Date]") {

    if (isNaN(date.getTime())) {

      // Date is unreal.

    } else {
      // Date is real if month and day match each other in date and string (otherwise may be shifted):
      isValid =
        date.getUTCMonth() + 1 === dateString.split("-")[1] * 1 &&
        date.getUTCDate() === dateString.split("-")[2] * 1;
    }
  } else {
    // It's not a date.
  }

  return isValid;
}

Common MySQL fields and their appropriate data types

Any Table ID

Use: INT(11).

MySQL indexes will be able to parse through an int list fastest.

Anything Security

Use: BINARY(x), or BLOB(x).

You can store security tokens, etc., as hex directly in BINARY(x) or BLOB(x). To retrieve from binary-type, use SELECT HEX(field)... or SELECT ... WHERE field = UNHEX("ABCD....").

Anything Date

Use: DATETIME, DATE, or TIME.

Always use DATETIME if you need to store both date and time (instead of a pair of fields), as a DATETIME indexing is more amenable to date-comparisons in MySQL.

Anything True-False

Use: BIT(1) (MySQL 8-only.) Otherwise, use BOOLEAN(1).

BOOLEAN is actually just an alias of TINYINT(1), which actually stores 0 to 255 (not exactly a true/false, is it?).

Anything You Want to call `SUM()`, `MAX()`, or similar functions on

Use: INT(11).

VARCHAR or other types of fields won't work with the SUM(), etc., functions.

Anything Over 1,000 Characters

Use: TEXT.

Max limit is 65,535.

Anything Over 65,535 Characters

Use: MEDIUMTEXT.

Max limit is 16,777,215.

Anything Over 16,777,215 Characters

Use: LONGTEXT.

Max limit is 4,294,967,295.

FirstName, LastName

Use : VARCHAR(255).

UTF-8 characters can take up three characters per visible character, and some cultures do not distinguish firstname and lastname. Additionally, cultures may have disagreements about which name is first and which name is last. You should name these fields Person.GivenName and Person.FamilyName.

Email Address

Use : VARCHAR(256).

The definition of an e-mail path is set in RFC821 in 1982. The maximum limit of an e-mail was set by RFC2821 in 2001, and these limits were kept unchanged by RFC5321 in 2008. (See the section: 4.5.3.1. Size Limits and Minimums.) RFC3696, published 2004, mistakenly cites the email address limit as 320 characters, but this was an "info-only" RFC that explicitly "defines no standards" according to its intro, so disregard it.

Phone

Use: VARCHAR(255).

You never know when the phone number will be in the form of "1800...", or "1-800", or "1-(800)", or if it will end with "ext. 42", or "ask for susan".

ZipCode

Use: VARCHAR(10).

You'll get data like 12345 or 12345-6789. Use validation to cleanse this input.

URL

Use: VARCHAR(2000).

Official standards support URL's much longer than this, but few modern browsers support URL's over 2,000 characters. See this SO answer: What is the maximum length of a URL in different browsers?

Price

Use: DECIMAL(11,2).

It goes up to 11.

What should I set JAVA_HOME environment variable on macOS X 10.6?

Nowadays Java seems to be installed in /Library/Java/JavaVirtualMachines

Min and max value of input in angular4 application

Actually when you use type="number" your input control populate with up/down arrow to increment/decrement numeric value, so when you update textbox value with those button it will not pass limit of 100, but when you manually give input like 120/130 and so on, it will not validate for max limit, so you have to validate it by code.

You can disable manual input OR you have to write some code on valueChange/textChange/key* event.

Can I hide/show asp:Menu items based on role?

This is best done in the MenuItemDataBound.

protected void NavigationMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
    if (!Page.User.IsInRole("Admin"))
    {
        if (e.Item.NavigateUrl.Equals("/admin"))
        {
            if (e.Item.Parent != null)
            {
                MenuItem menu = e.Item.Parent;

                menu.ChildItems.Remove(e.Item);
            }
            else
            {
                Menu menu = (Menu)sender;

                menu.Items.Remove(e.Item);
            }               
        }
    }
}

Because the example used the NavigateUrl it is not language specific and works on sites with localized site maps.

How to use nan and inf in C?

You can test if your implementation has it:

#include <math.h>
#ifdef NAN
/* NAN is supported */
#endif
#ifdef INFINITY
/* INFINITY is supported */
#endif

The existence of INFINITY is guaranteed by C99 (or the latest draft at least), and "expands to a constant expression of type float representing positive or unsigned infinity, if available; else to a positive constant of type float that overflows at translation time."

NAN may or may not be defined, and "is defined if and only if the implementation supports quiet NaNs for the float type. It expands to a constant expression of type float representing a quiet NaN."

Note that if you're comparing floating point values, and do:

a = NAN;

even then,

a == NAN;

is false. One way to check for NaN would be:

#include <math.h>
if (isnan(a)) { ... }

You can also do: a != a to test if a is NaN.

There is also isfinite(), isinf(), isnormal(), and signbit() macros in math.h in C99.

C99 also has nan functions:

#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);

(Reference: n1256).

Docs INFINITY Docs NAN

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.

Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

The answer from Constantin is spot on but for more background this behavior is inherited from Matlab.

The Matlab behavior is explained in the Figure Setup - Displaying Multiple Plots per Figure section of the Matlab documentation.

subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ithe subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

How to hash a password

@csharptest.net's and Christian Gollhardt's answers are great, thank you very much. But after running this code on production with millions of record, I discovered there is a memory leak. RNGCryptoServiceProvider and Rfc2898DeriveBytes classes are derived from IDisposable but we don't dispose of them. I will write my solution as an answer if someone needs with disposed version.

public static class SecurePasswordHasher
{
    /// <summary>
    /// Size of salt.
    /// </summary>
    private const int SaltSize = 16;

    /// <summary>
    /// Size of hash.
    /// </summary>
    private const int HashSize = 20;

    /// <summary>
    /// Creates a hash from a password.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <param name="iterations">Number of iterations.</param>
    /// <returns>The hash.</returns>
    public static string Hash(string password, int iterations)
    {
        // Create salt
        using (var rng = new RNGCryptoServiceProvider())
        {
            byte[] salt;
            rng.GetBytes(salt = new byte[SaltSize]);
            using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations))
            {
                var hash = pbkdf2.GetBytes(HashSize);
                // Combine salt and hash
                var hashBytes = new byte[SaltSize + HashSize];
                Array.Copy(salt, 0, hashBytes, 0, SaltSize);
                Array.Copy(hash, 0, hashBytes, SaltSize, HashSize);
                // Convert to base64
                var base64Hash = Convert.ToBase64String(hashBytes);

                // Format hash with extra information
                return $"$HASH|V1${iterations}${base64Hash}";
            }
        }

    }

    /// <summary>
    /// Creates a hash from a password with 10000 iterations
    /// </summary>
    /// <param name="password">The password.</param>
    /// <returns>The hash.</returns>
    public static string Hash(string password)
    {
        return Hash(password, 10000);
    }

    /// <summary>
    /// Checks if hash is supported.
    /// </summary>
    /// <param name="hashString">The hash.</param>
    /// <returns>Is supported?</returns>
    public static bool IsHashSupported(string hashString)
    {
        return hashString.Contains("HASH|V1$");
    }

    /// <summary>
    /// Verifies a password against a hash.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <param name="hashedPassword">The hash.</param>
    /// <returns>Could be verified?</returns>
    public static bool Verify(string password, string hashedPassword)
    {
        // Check hash
        if (!IsHashSupported(hashedPassword))
        {
            throw new NotSupportedException("The hashtype is not supported");
        }

        // Extract iteration and Base64 string
        var splittedHashString = hashedPassword.Replace("$HASH|V1$", "").Split('$');
        var iterations = int.Parse(splittedHashString[0]);
        var base64Hash = splittedHashString[1];

        // Get hash bytes
        var hashBytes = Convert.FromBase64String(base64Hash);

        // Get salt
        var salt = new byte[SaltSize];
        Array.Copy(hashBytes, 0, salt, 0, SaltSize);

        // Create hash with given salt
        using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations))
        {
            byte[] hash = pbkdf2.GetBytes(HashSize);

            // Get result
            for (var i = 0; i < HashSize; i++)
            {
                if (hashBytes[i + SaltSize] != hash[i])
                {
                    return false;
                }
            }

            return true;
        }

    }
}

Usage:

// Hash
var hash = SecurePasswordHasher.Hash("mypassword");

// Verify
var result = SecurePasswordHasher.Verify("mypassword", hash);

Delegates in swift?

In swift 4.0

Create a delegate on class that need to send some data or provide some functionality to other classes

Like

protocol GetGameStatus {
    var score: score { get }
    func getPlayerDetails()
}

After that in the class that going to confirm to this delegate

class SnakesAndLadders: GetGameStatus {
    func getPlayerDetails() {

 }
}

How do I specify unique constraint for multiple columns in MySQL?

I have a MySQL table:

CREATE TABLE `content_html` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_box_elements` int(11) DEFAULT NULL,
  `id_router` int(11) DEFAULT NULL,
  `content` mediumtext COLLATE utf8_czech_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_box_elements` (`id_box_elements`,`id_router`)
);

and the UNIQUE KEY works just as expected, it allows multiple NULL rows of id_box_elements and id_router.

I am running MySQL 5.1.42, so probably there was some update on the issue discussed above. Fortunately it works and hopefully it will stay that way.

How to kill MySQL connections

mysql> SHOW PROCESSLIST;
+-----+------+-----------------+------+---------+------+-------+---------------+
| Id  | User | Host            | db   | Command | Time | State | Info      |
+-----+------+-----------------+------+---------+------+-------+----------------+
| 143 | root | localhost:61179 | cds  | Query   |    0 | init  | SHOW PROCESSLIST |
| 192 | root | localhost:53793 | cds  | Sleep   |    4 |       | NULL      |
+-----+------+-----------------+------+---------+------+-------+----------------+
2 rows in set (0.00 sec)

mysql> KILL 192;
Query OK, 0 rows affected (0.00 sec)

USER 192 :

mysql> SELECT * FROM exept;
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.00 sec)

mysql> SELECT * FROM exept;
ERROR 2013 (HY000): Lost connection to MySQL server during query

Alternative to mysql_real_escape_string without connecting to DB

It is impossible to safely escape a string without a DB connection. mysql_real_escape_string() and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.

If you are only testing, then you may as well use mysql_escape_string(), it's not 100% guaranteed against SQL injection attacks, but it's impossible to build anything safer without a DB connection.

How to check if a float value is a whole number

Wouldn't it be easier to test the cube roots? Start with 20 (20**3 = 8000) and go up to 30 (30**3 = 27000). Then you have to test fewer than 10 integers.

for i in range(20, 30):
    print("Trying {0}".format(i))
    if i ** 3 > 12000:
        print("Maximum integral cube root less than 12000: {0}".format(i - 1))
        break

React.js: Identifying different inputs with one onChange handler

Hi have improved ssorallen answer. You don't need to bind function because you can access to the input without it.

var Hello = React.createClass({
    render: function() {
        var total = this.state.input1 + this.state.input2;
        return (
             <div>{total}<br/>
                  <input type="text" 
                    value={this.state.input1}
                    id="input1"  
                    onChange={this.handleChange} />
                 <input type="text" 
                    value={this.state.input2}
                    id="input2" 
                    onChange={this.handleChange} />
            </div>
       );
   },
   handleChange: function (name, value) {
       var change = {};
       change[name] = value;
       this.setState(change);
   }
});

React.renderComponent(<Hello />, document.getElementById('content'));

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

As of April 2014, FileSytem APIs may not be standardized in W3C. Anyone looking at the solution with blob should thread with caution, I guess.

HTML5 rocks heads up

W3C Mailing List on FileSytem API

How do I change a tab background color when using TabLayout?

Add atribute in xml:

<android.support.design.widget.TabLayout
    ....
    app:tabBackground="@drawable/tab_color_selector"
    ...
    />

And create in drawable folder, tab_color_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
    <item android:drawable="@color/tab_background_unselected"/>
</selector>

How to start debug mode from command prompt for apache tomcat server?

For windows first set variables:

set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket

to start server in debug mode:

%TOMCAT_HOME%/bin/catalina.bat jpda start

For unix first export variables:

export JPDA_ADDRESS=8000
export JPDA_TRANSPORT=dt_socket

and to start server in debug mode:

%TOMCAT_HOME%/bin/catalina.sh jpda start

Identifying country by IP address

You can try using https://ip-api.io - geo location api that returns country among other IP information.

For example with Node.js

const request = require('request-promise')

request('http://ip-api.io/api/json/1.2.3.4')
  .then(response => console.log(JSON.parse(response)))
  .catch(err => console.log(err))

Markdown to create pages and table of contents?

There is a Ruby script called mdtoc.rb that can auto-generate a GFM Markdown Table of Contents, and it is similar but slightly different to some other scripts posted here.

Given an input Markdown file like:

# Lorem Ipsum

Lorem ipsum dolor sit amet, mei alienum adipiscing te, has no possit delicata. Te nominavi suavitate sed, quis alia cum no, has an malis dictas explicari. At mel nonumes eloquentiam, eos ea dicat nullam. Sed eirmod gubergren scripserit ne, mei timeam nonumes te. Qui ut tale sonet consul, vix integre oportere an. Duis ullum at ius.

## Et cum

Et cum affert dolorem habemus. Sale malis at mel. Te pri copiosae hendrerit. Cu nec agam iracundia necessitatibus, tibique corpora adipisci qui cu. Et vix causae consetetur deterruisset, ius ea inermis quaerendum.

### His ut

His ut feugait consectetuer, id mollis nominati has, in usu insolens tractatos. Nemore viderer torquatos qui ei, corpora adipiscing ex nec. Debet vivendum ne nec, ipsum zril choro ex sed. Doming probatus euripidis vim cu, habeo apeirian et nec. Ludus pertinacia an pro, in accusam menandri reformidans nam, sed in tantas semper impedit.

### Doctus voluptua

Doctus voluptua his eu, cu ius mazim invidunt incorrupte. Ad maiorum sensibus mea. Eius posse sonet no vim, te paulo postulant salutatus ius, augue persequeris eum cu. Pro omnesque salutandi evertitur ea, an mea fugit gloriatur. Pro ne menandri intellegam, in vis clita recusabo sensibus. Usu atqui scaevola an.

## Id scripta

Id scripta alterum pri, nam audiam labitur reprehendunt at. No alia putent est. Eos diam bonorum oportere ad. Sit ad admodum constituto, vide democritum id eum. Ex singulis laboramus vis, ius no minim libris deleniti, euismod sadipscing vix id.

It generates this table of contents:

$ mdtoc.rb FILE.md 
#### Table of contents

1. [Et cum](#et-cum)
    * [His ut](#his-ut)
    * [Doctus voluptua](#doctus-voluptua)
2. [Id scripta](#id-scripta)

See also my blog post on this topic.

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

it can also be in your capistrano config (Capfile):

set :rbenv_ruby, "2.7.1"

Generate a random number in a certain range in MATLAB

If you need a floating random number between 13 and 20

(20-13).*rand(1) + 13

If you need an integer random number between 13 and 20

floor((21-13).*rand(1) + 13)

Note: Fix problem mentioned in comment "This excludes 20" by replacing 20 with 21

Run a Python script from another Python script, passing in arguments

import subprocess
subprocess.call(" python script2.py 1", shell=True)

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

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

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

Difference between a theta join, equijoin and natural join

Cartesian product of two tables gives all the possible combinations of tuples like the example in mathematics the cross product of two sets . since many a times there are some junk values which occupy unnecessary space in the memory too so here joins comes to rescue which give the combination of only those attribute values which are required and are meaningful.

inner join gives the repeated field in the table twice whereas natural join here solves the problem by just filtering the repeated columns and displaying it only once.else, both works the same. natural join is more efficient since it preserves the memory .Also , redundancies are removed in natural join .

equi join of two tables are such that they display only those tuples which matches the value in other table . for example : let new1 and new2 be two tables . if sql query select * from new1 join new2 on new1.id = new.id (id is the same column in two tables) then start from new2 table and join which matches the id in second table . besides , non equi join do not have equality operator they have <,>,and between operator .

theta join consists of all the comparison operator including equality and others < , > comparison operator. when it uses equality(=) operator it is known as equi join .

Is it possible to ignore one single specific line with Pylint?

I believe you're looking for...

import config.logging_settings  # @UnusedImport

Note the double space before the comment to avoid hitting other formatting warnings.

Also, depending on your IDE (if you're using one), there's probably an option to add the correct ignore rule (e.g., in Eclipse, pressing Ctrl + 1, while the cursor is over the warning, will auto-suggest @UnusedImport).

How to check if click event is already bound - JQuery

As of June 2019, I've updated the function (and it's working for what I need)

$.fn.isBound = function (type) {
    var data = $._data($(this)[0], 'events');

    if (data[type] === undefined || data.length === 0) {
        return false;
    }
    return true;
};

How to check if a process is running via a batch script

Another possibility I came up with, inspired by using grep, is:

tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Program is running

It doesn't need to save an extra file, so I prefer this method.

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I was importing also some projects from VS2010 to VS 2012. I had the same errors. The errors disappeared when I set back Properties > Config. Properties > General > Platform Toolset to v100 (VS2010). That might not be the correct approach, however.

How to wrap text around an image using HTML/CSS

you have to float your image container as follows:

HTML

<div id="container">
    <div id="floated">...some other random text</div>
    ...
    some random text
    ...
</div>

CSS

#container{
    width: 400px;
    background: yellow;
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

FIDDLE

http://jsfiddle.net/kYDgL/

How to add border radius on table row

You can only apply border-radius to td, not tr or table. I've gotten around this for rounded corner tables by using these styles:

table { border-collapse: separate; }
td { border: solid 1px #000; }
tr:first-child td:first-child { border-top-left-radius: 10px; }
tr:first-child td:last-child { border-top-right-radius: 10px; }
tr:last-child td:first-child { border-bottom-left-radius: 10px; }
tr:last-child td:last-child { border-bottom-right-radius: 10px; }

Be sure to provide all the vendor prefixes. Here's an example of it in action.

Using Git with Visual Studio

I find that Git, working on whole trees as it does, benefits less from IDE integration than source control tools that are either file based or follow a checkout-edit-commit pattern. Of course there are instances when it can be nice to click on a button to do some history examination, but I don't miss that very much.

The real must-do is to get your .gitignore file full of the things that shouldn't be in a shared repository. Mine generally contain (amongst other stuff) the following:

*.vcproj.*.user
*.ncb
*.aps
*.suo

but this is heavily C++ biased with little or no use of any class wizard style functionality.

My usage pattern is something like the following.

  1. Code, code, code in Visual Studio.

  2. When happy (sensible intermediate point to commit code, switch to Git, stage changes and review diffs. If anything's obviously wrong switch back to Visual Studio and fix, otherwise commit.

Any merge, branch, rebase or other fancy SCM stuff is easy to do in Git from the command prompt. Visual Studio is normally fairly happy with things changing under it, although it can sometimes need to reload some projects if you've altered the project files significantly.

I find that the usefulness of Git outweighs any minor inconvenience of not having full IDE integration but it is, to some extent, a matter of taste.

What's the canonical way to check for type in Python?

You can check for type of a variable using __name__ of a type.

Ex:

>>> a = [1,2,3,4]  
>>> b = 1  
>>> type(a).__name__
'list'
>>> type(a).__name__ == 'list'
True
>>> type(b).__name__ == 'list'
False
>>> type(b).__name__
'int'

Facebook Open Graph Error - Inferred Property

UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.


There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/

But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.

So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/

It allows you to Fetch new scrape information and refresh the Facebook cache:

Open Graph Object Debugger

Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)


Use 'property'-attrs

I also noted that some developers use the name attribute instead of property. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property, not name:

<meta property="og:url" content="http://www.mywebaddress.com"/>

Use full URLs

The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image. So use the full one:

<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>

Can I redirect the stdout in python into some sort of string buffer?

There is contextlib.redirect_stdout() function in Python 3.4:

import io
from contextlib import redirect_stdout

with io.StringIO() as buf, redirect_stdout(buf):
    print('redirected')
    output = buf.getvalue()

Here's code example that shows how to implement it on older Python versions.

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

I've solved this issue adding user and password in Transport.send call:

Transport.send(msg, "user", "password");

According to this signature of the send function in javax.mail (from version 1.5):

public static void send(Message msg, String user, String password)

Also, if you use this signature it's not necessary to set up any Authenticator, and to set user and password in the Properties (only the host is needed). So your code could be:

private void sendMail(){
  try{
      Properties prop = System.getProperties();
      prop.put("mail.smtp.host", "yourHost");
      Session session = Session.getInstance(prop);
      Message msg = #createYourMsg(session, from, to, subject, mailer, yatta yatta...)#;
      Transport.send(msg, "user", "password");
  }catch(Exception exc) {
      // Deal with it! :)
  }
}

SQL Server: Importing database from .mdf?

If you do not have an LDF file then:

1) put the MDF in the C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\

2) In ssms, go to Databases -> Attach and add the MDF file. It will not let you add it this way but it will tell you the database name contained within.

3) Make sure the user you are running ssms.exe as has acccess to this MDF file.

4) Now that you know the DbName, run

EXEC sp_attach_single_file_db @dbname = 'DbName', 
@physname = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\yourfile.mdf';

Reference: https://dba.stackexchange.com/questions/12089/attaching-mdf-without-ldf

Amazon S3 exception: "The specified key does not exist"

Step 1: Get the latest aws-java-sdk

<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-aws -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.660</version>
</dependency>

Step 2: The correct imports

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;

If you are sure the bucket exists, Specified key does not exists error would mean the bucketname is not spelled correctly ( contains slash or special characters). Refer the documentation for naming convention.

The document quotes:

If the requested object is available in the bucket and users are still getting the 404 NoSuchKey error from Amazon S3, check the following:

Confirm that the request matches the object name exactly, including the capitalization of the object name. Requests for S3 objects are case sensitive. For example, if an object is named myimage.jpg, but Myimage.jpg is requested, then requester receives a 404 NoSuchKey error. Confirm that the requested path matches the path to the object. For example, if the path to an object is awsexamplebucket/Downloads/February/Images/image.jpg, but the requested path is awsexamplebucket/Downloads/February/image.jpg, then the requester receives a 404 NoSuchKey error. If the path to the object contains any spaces, be sure that the request uses the correct syntax to recognize the path. For example, if you're using the AWS CLI to download an object to your Windows machine, you must use quotation marks around the object path, similar to: aws s3 cp "s3://awsexamplebucket/Backup Copy Job 4/3T000000.vbk". Optionally, you can enable server access logging to review request records in further detail for issues that might be causing the 404 error.

AWSCredentials credentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
ObjectListing objects = s3Client.listObjects("bigdataanalytics");
System.out.println(objects.getObjectSummaries());

Running a Python script from PHP

To clarify which command to use based on the situation

exec() - Execute an external program

system() - Execute an external program and display the output

passthru() - Execute an external program and display raw output

Source: http://php.net/manual/en/function.exec.php

Check whether user has a Chrome extension installed

Chrome now has the ability to send messages from the website to the extension.

So in the extension background.js (content.js will not work) add something like:

chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
        if (request) {
            if (request.message) {
                if (request.message == "version") {
                    sendResponse({version: 1.0});
                }
            }
        }
        return true;
    });

This will then let you make a call from the website:

var hasExtension = false;

chrome.runtime.sendMessage(extensionId, { message: "version" },
    function (reply) {
        if (reply) {
            if (reply.version) {
                if (reply.version >= requiredVersion) {
                    hasExtension = true;
                }
            }
        }
        else {
          hasExtension = false;
        }
    });

You can then check the hasExtension variable. The only drawback is the call is asynchronous, so you have to work around that somehow.

Edit: As mentioned below, you'll need to add an entry to the manifest.json listing the domains that can message your addon. Eg:

"externally_connectable": {
    "matches": ["*://localhost/*", "*://your.domain.com/*"]
},

Make Div Draggable using CSS

This is the best you can do without JavaScript:

_x000D_
_x000D_
[draggable=true] {_x000D_
  cursor: move;_x000D_
}_x000D_
_x000D_
.resizable {_x000D_
  overflow: scroll;_x000D_
  resize: both;_x000D_
  max-width: 300px;_x000D_
  max-height: 460px;_x000D_
  border: 1px solid black;_x000D_
  min-width: 50px;_x000D_
  min-height: 50px;_x000D_
  background-color: skyblue;_x000D_
}
_x000D_
<div draggable="true" class="resizable"></div>
_x000D_
_x000D_
_x000D_

Demo

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

On particular table

_x000D_
_x000D_
<table style="border-collapse: separate; border-spacing: 10px;" >_x000D_
    <tr>_x000D_
      <td>Hi</td>_x000D_
      <td>Hello</td>_x000D_
    <tr/>_x000D_
    <tr>_x000D_
      <td>Hola</td>_x000D_
      <td>Oi!</td>_x000D_
    <tr/>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Sending HTTP POST Request In Java

String rawData = "id=10";
String type = "application/x-www-form-urlencoded";
String encodedData = URLEncoder.encode( rawData, "UTF-8" ); 
URL u = new URL("http://www.example.com/page.php");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());

Junit - run set up method once

You can use the BeforeClass annotation:

@BeforeClass
public static void setUpClass() {
    //executed only once, before the first test
}

Github: Can I see the number of downloads for a repo?

I have written a small web application in javascript for showing count of the number of downloads of all the assets in the available releases of any project on Github. You can try out the application over here: http://somsubhra.github.io/github-release-stats/

Pretty printing JSON from Jackson 2.2's ObjectMapper

If others who view this question only have a JSON string (not in an object), then you can put it into a HashMap and still get the ObjectMapper to work. The result variable is your JSON string.

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

// Pretty-print the JSON result
try {
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> response = objectMapper.readValue(result, HashMap.class);
    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
} catch (JsonParseException e) {
    e.printStackTrace();
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} 

How to remove time portion of date in C# in DateTime object only?

Have a look at the DateTime.Date property.

Gets the date component of this instance.

Concatenating string and integer in python

if you only want to print yo can do this:

print(s , i)

PHP - iterate on string characters

Most of the answers forgot about non English characters !!!

strlen counts BYTES, not characters, that is why it is and it's sibling functions works fine with English characters, because English characters are stored in 1 byte in both UTF-8 and ASCII encodings, you need to use the multibyte string functions mb_*

This will work with any character encoded in UTF-8

// 8 characters in 12 bytes
$string = "abcd????";

$charsCount = mb_strlen($string, 'UTF-8');
for($i = 0; $i < $charsCount; $i++){
    $char = mb_substr($string, $i, 1, 'UTF-8');
    var_dump($char);
}

This outputs

string(1) "a"
string(1) "b"
string(1) "c"
string(1) "d"
string(2) "?"
string(2) "?"
string(2) "?"
string(2) "?"

In Python, how do you convert a `datetime` object to seconds?

Starting from Python 3.3 this becomes super easy with the datetime.timestamp() method. This of course will only be useful if you need the number of seconds from 1970-01-01 UTC.

from datetime import datetime
dt = datetime.today()  # Get timezone naive now
seconds = dt.timestamp()

The return value will be a float representing even fractions of a second. If the datetime is timezone naive (as in the example above), it will be assumed that the datetime object represents the local time, i.e. It will be the number of seconds from current time at your location to 1970-01-01 UTC.

What's the best way to get the last element of an array without deleting it?

One more possible solution...

$last_element = array_reverse( $array )[0];

Is there a good jQuery Drag-and-drop file upload plugin?

If you're looking for one that doesn't rely on Flash then dropzonejs is a good shout. It supports multiple files and drag and drop.

http://www.dropzonejs.com/

Get the first N elements of an array?

You can use array_slice as:

$sliced_array = array_slice($array,0,$N);

Entity Framework Join 3 Tables

This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.

var fullEntries = dbContext.tbl_EntryPoint
    .Join(
        dbContext.tbl_Entry,
        entryPoint => entryPoint.EID,
        entry => entry.EID,
        (entryPoint, entry) => new { entryPoint, entry }
    )
    .Join(
        dbContext.tbl_Title,
        combinedEntry => combinedEntry.entry.TID,
        title => title.TID,
        (combinedEntry, title) => new 
        {
            UID = combinedEntry.entry.OwnerUID,
            TID = combinedEntry.entry.TID,
            EID = combinedEntry.entryPoint.EID,
            Title = title.Title
        }
    )
    .Where(fullEntry => fullEntry.UID == user.UID)
    .Take(10);

Change Default branch in gitlab

In 8.0+ it looks like this was moved into the project. If you open your project and go to the gear icon on the right, then "Edit Project" you can set the default branch for the project.

Converting String to Cstring in C++

.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.

Determine a string's encoding in C#

My finally working approach is to try potential candidates of expected encodings by detecting invalid characters in the strings created from the byte array by the encodings. If I don't encounter invalid characters, I suppose the tested encoding works fine for the tested data.

For me, having only Latin and German special characters to consider, in order to determine the proper encoding for a byte array, I try to detect invalid characters in a string with this method:

    /// <summary>
    /// detect invalid characters in string, use to detect improper encoding
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static bool DetectInvalidChars(string s)
    {
        const string specialChars = "\r\n\t .,;:-_!\"'?()[]{}&%$§=*+~#@|<>äöüÄÖÜß/\\^€";
        return s.Any(ch => !(
            specialChars.Contains(ch) ||
            (ch >= '0' && ch <= '9') ||
            (ch >= 'a' && ch <= 'z') ||
            (ch >= 'A' && ch <= 'Z')));
    }

(NB: if you have other Latin-based languages to consider, you might want to adapt the specialChars const string in the code)

Then I use it like this (I only expect UTF-8 or Default encoding):

        // determine encoding by detecting invalid characters in string
        var invoiceXmlText = Encoding.UTF8.GetString(invoiceXmlBytes); // try utf-8 first
        if (StringFuncs.DetectInvalidChars(invoiceXmlText))
            invoiceXmlText = Encoding.Default.GetString(invoiceXmlBytes); // fallback to default

What is the difference between a URI, a URL and a URN?

Here is my simplification:

URN: unique resource name, i.e. "what" (eg urn:issn:1234-5678 ). This is meant to be unique .. as in no two different docs can have the same urn. A bit like "uuid"

URL: "where" to find it ( eg https://google.com/pub?issnid=1234-5678 .. or ftp://somesite.com/doc8.pdf )

URI: can be either a URN or a URL. This fuzzy definition is thanks to RFC 3986 produced by W3C and IETF.

The definition of URI has changed over the years, so it makes sense for most people to be confused. However, you can now take solace in the fact that you can refer to http://somesite.com/something as either a URL or URI ... an you will be right either way (at least fot the time being anyway...)

Does not contain a static 'main' method suitable for an entry point

If you are using a class library project then set Class Library as output type in properties under application section of project.

What is the difference between Cygwin and MinGW?

As a simplification, it's like this:

  • Compile something in Cygwin and you are compiling it for Cygwin.

  • Compile something in MinGW and you are compiling it for Windows.

About Cygwin

The purpose of Cygwin is to make porting Unix-based applications to Windows much easier, by emulating many of the small details that Unix-based operating systems provide, and are documented by the POSIX standards. Your application can use Unix feature such as pipes, Unix-style file and directory access, and so forth, and it can be compiled with Cygwin which will act as a compatibility layer around your application, so that many of those Unix-specific paradigms can continue to be used.

When you distribute your software, the recipient will need to run it along with the Cygwin run-time environment (provided by the file cygwin1.dll). You may distribute this with your software, but your software will have to comply with its open source license. It may even be the case that even just linking your software with it, but distributing the dll separately, may still require you to honor the open source license.

About MinGW

MinGW aims to simply be a Windows port of the GNU compiler tools, such as GCC, Make, Bash, and so on. It does not attempt to emulate or provide comprehensive compatibility with Unix, but instead it provides the minimum necessary environment to use GCC (the GNU compiler) and a small number of other tools on Windows. It does not have a Unix emulation layer like Cygwin, but as a result your application needs to specifically be programmed to be able to run in Windows, which may mean significant alteration if it was created to rely on being run in a standard Unix environment and uses Unix-specific features such as those mentioned earlier. By default, code compiled in MinGW's GCC will compile to a native Windows X86 target, including .exe and .dll files, though you could also cross-compile with the right settings, since you are basically using the GNU compiler tools suite.

MinGW is essentially an alternative to the Microsoft Visual C++ compiler and its associated linking/make tools. It may be possible in some cases to use MinGW to compile something that was intended for compiling with Microsoft Visual C++, with the right libraries and in some cases with other modifications.

MinGW includes some basic standard libraries for interacting with the Windows operating system, but as with the normal standard libraries included in the GNU compiler collection these don't impose licensing restrictions on software you have created.

For non-trivial software applications, making them cross-platform can be a considerable challenge unless you use a comprehensive cross-platform framework. At the time I wrote this the Qt framework was one of the most popular for this purpose, allowing the building of graphical applications that work across operating systems including Windows, but there are other options too. If you use such a framework from the start, you can not only reduce your headaches when it comes time to port to another platform but you can use the same graphical widgets - windows, menus and controls - across all platforms if you're writing a GUI app, and have them appear native to the user.

System.Runtime.InteropServices.COMException (0x800A03EC)

Found Answer.......!!!!!!!

Officially Microsoft Office 2003 Interop is not supported on Windows server 2008 by Microsoft.

But after a lot of permutations & combinations with the code and search, we came across one solution which works for our scenario.

The solution is to plug the difference between the way Windows 2003 and 2008 maintains its folder structure, because Office Interop depends on the desktop folder for file open/save intermediately. The 2003 system houses the desktop folder under systemprofile which is absent in 2008.

So when we create this folder on 2008 under the respective hierarchy as indicated below; the office Interop is able to save the file as required. This Desktop folder is required to be created under

C:\Windows\System32\config\systemprofile

AND

C:\Windows\SysWOW64\config\systemprofile

This worked for me...

Also do check if .NET 1.1 is installed because its needed by Interop and ot preinstalled by Windows Server 2008

Or you can also Use SaveCopyas() method ist just take onargument as filename string)

Thanks Guys..!

Remove Last Comma from a string

Remove last comma. Working example

_x000D_
_x000D_
function truncateText() {_x000D_
  var str= document.getElementById('input').value;_x000D_
  str = str.replace(/,\s*$/, "");_x000D_
  console.log(str);_x000D_
}
_x000D_
<input id="input" value="address line one,"/>_x000D_
<button onclick="truncateText()">Truncate</button>
_x000D_
_x000D_
_x000D_

How to install pip with Python 3?

Single Python in system

To install packages in Python always follow these steps:

  1. If the package is for python 2.x: sudo python -m pip install [package]
  2. If the package is for python 3.x: sudo python3 -m pip install [package]

Note: This is assuming no alias is set for python

Through this method, there will be no confusion regarding which python version is receiving the package.

Multiple Pythons

Say you have python3 ? python3.6 and python3.7 ? python3.7

  1. To install for python3.6: sudo python3 -m pip install [package]
  2. To instal for python3.7: sudo python3.7 -m pip install [package]

This is essentially the same method as shown previously.

Note 1

How to find which python, your python3 command spawns:

ganesh@Ganesh:~$ python3 # Type in terminal
Python 3.6.6 (default, Sep 12 2018, 18:26:19) # Your python3 version
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Notice python 3.6.6 in the second line.

Note 2

Change what python3 or python points to: https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3

Promise.all().then() resolve?

Your return data approach is correct, that's an example of promise chaining. If you return a promise from your .then() callback, JavaScript will resolve that promise and pass the data to the next then() callback.

Just be careful and make sure you handle errors with .catch(). Promise.all() rejects as soon as one of the promises in the array rejects.

Generate a sequence of numbers in Python

Assuming your sequence alternates increments between 1 and 3

numbers = [1]
while numbers[-1] < 100:
    numbers.append(numbers[-1] + 1)
    numbers.append(numbers[-1] + 3)

print ', '.join(map(str, numbers))

This could be easier to modify if your sequence is different but I think poke or BlaXpirit are nicer answers than mine.

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

Try changing server name to "localhost"

pymssql.connect(server="localhost", user="myusername", password="mypwd", database="temp",port="1433")

Java synchronized method lock on object, or method?

Yes, it will block the other method because synchronized method applies to the WHOLE class object as pointed .... but anyway it will block the other thread execution ONLY while performing the sum in whatever method addA or addB it enters, because when it finish ... the one thread will FREE the object and the other thread will access the other method and so on perfectly working.

I mean the "synchronized" is made precisely for blocking the other thread from accessing another while in a specific code execution. SO FINALLY THIS CODE WILL WORK FINE.

As a final note, if there is an 'a' and 'b' variables, not just an unique variable 'a' or whatever other name, there is no need to synchronize this methods cause it is perfectly safe accesing other var (Other memory location).

class X {

private int a;
private int b;

public void addA(){
    a++;
}

public void addB(){
    b++;
}}

Will work as well

How do you select a particular option in a SELECT element in jQuery?

   $(elem).find('option[value="' + value + '"]').attr("selected", "selected");

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

I wouldn't use JavaScript navigator.userAgent or $.browser (which uses navigator.userAgent) since it can be spoofed.

To target Internet Explorer 9, 10 and 11 (Note: also the latest Chrome):

@media screen and (min-width:0\0) { 
    /* Enter CSS here */
}

To target Internet Explorer 10:

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    /* IE10+ CSS here */
}

To target Edge Browser:

@supports (-ms-accelerator:true) {
  .selector { property:value; } 
}

Sources:

Programmatically get own phone number in iOS

As you probably all ready know if you use the following line of code, your app will be rejected by Apple

NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];

here is a reference

http://ayeapi.blogspot.com/2009/12/sbformatphonenumber-is-lie.html

you can use the following information instead

NSString *phoneName = [[UIDevice currentDevice] name];

NSString *phoneUniqueIdentifier = [[UIDevice currentDevice] uniqueIdentifier];

and so on

@property(nonatomic,readonly,retain) NSString    *name;              // e.g. "My iPhone"
@property(nonatomic,readonly,retain) NSString    *model;             // e.g. @"iPhone", @"iPod Touch"
@property(nonatomic,readonly,retain) NSString    *localizedModel;    // localized version of model
@property(nonatomic,readonly,retain) NSString    *systemName;        // e.g. @"iPhone OS"
@property(nonatomic,readonly,retain) NSString    *systemVersion;     // e.g. @"2.0"
@property(nonatomic,readonly) UIDeviceOrientation orientation;       // return current device orientation
@property(nonatomic,readonly,retain) NSString    *uniqueIdentifier;  // a string unique to each device based on various hardware info.

Hope this helps!

How to navigate back to the last cursor position in Visual Studio Code?

?+U Undo last cursor operation

You can also try ctrl+-

BTW all the shortcuts is here https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf This is really useful!

Statically rotate font-awesome icons

New Font-Awesome v5 has Power Transforms

You can rotate any icon by adding attribute data-fa-transform to icon

<i class="fas fa-magic" data-fa-transform="rotate-45"></i>

Here is a fiddle

For more information, check this out : Font-Awesome5 Power Tranforms

.htaccess not working on localhost with XAMPP

for xampp vm on MacOS capitan, high sierra, MacOS Mojave (10.12+), you can follow these

1. mount /opt/lampp
2. explore the folder
3. open terminal from the folder
4. cd to `htdocs`>yourapp (ex: techaz.co)
5. vim .htaccess
6. paste your .htaccess content (that is suggested on options-permalink.php)

enter image description here

Python: Importing urllib.quote

Use six:

from six.moves.urllib.parse import quote

six will simplify compatibility problems between Python 2 and Python 3, such as different import paths.

Interview question: Check if one string is a rotation of other string

Here's one using regex just for fun:

boolean isRotation(String s1, String s2) {
   return (s1.length() == s2.length()) && (s1 + s2).matches("(.*)(.*)\\2\\1");
}

You can make it a bit simpler if you can use a special delimiter character guaranteed not to be in either strings.

boolean isRotation(String s1, String s2) {
   // neither string can contain "="
   return (s1 + "=" + s2).matches("(.*)(.*)=\\2\\1");
}

You can also use lookbehind with finite repetition instead:

boolean isRotation(String s1, String s2) {
   return (s1 + s2).matches(
      String.format("(.*)(.*)(?<=^.{%d})\\2\\1", s1.length())
   );
}

How to access the ith column of a NumPy multidimensional array?

And if you want to access more than one column at a time you could do:

>>> test = np.arange(9).reshape((3,3))
>>> test
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> test[:,[0,2]]
array([[0, 2],
       [3, 5],
       [6, 8]])

How do I create a link using javascript?

_x000D_
_x000D_
    <script>_x000D_
      _$ = document.querySelector  .bind(document) ;_x000D_
_x000D_
        var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs_x000D_
        var a   =  document.createElement( 'a' )_x000D_
        a.text  = "Download example" _x000D_
        a.href  = "//bit\.do/DeezerDL"_x000D_
_x000D_
        AppendLinkHere.appendChild( a )_x000D_
        _x000D_
_x000D_
     // a.title = 'Well well ... _x000D_
        a.setAttribute( 'title', _x000D_
                         'Well well that\'s a link'_x000D_
                      );_x000D_
    </script>
_x000D_
_x000D_
_x000D_

  1. The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear! Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. Leave the protocol open. Instead of http://example.com/path consider to just use //example.com/path. Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.

  3. OffTopic: That's not really relevant about creating links in JS but maybe good to know: Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.

How can I get a JavaScript stack trace when I throw an exception?

Here is an answer that gives you max performance (IE 6+) and max compatibility. Compatible with IE 6!

_x000D_
_x000D_
    function stacktrace( log_result ) {_x000D_
     var trace_result;_x000D_
    // IE 6 through 9 compatibility_x000D_
    // this is NOT an all-around solution because_x000D_
    // the callee property of arguments is depredicated_x000D_
    /*@cc_on_x000D_
     // theese fancy conditinals make this code only run in IE_x000D_
     trace_result = (function st2(fTmp) {_x000D_
      // credit to Eugene for this part of the code_x000D_
      return !fTmp ? [] :_x000D_
       st2(fTmp.caller).concat([fTmp.toString().split('(')[0].substring(9) + '(' + fTmp.arguments.join(',') + ')']);_x000D_
     })(arguments.callee.caller);_x000D_
     if (log_result) // the ancient way to log to the console_x000D_
      Debug.write( trace_result );_x000D_
     return trace_result;_x000D_
    @*/_x000D_
     console = console || Console; // just in case_x000D_
     if (!(console && console.trace) || !log_result){_x000D_
      // for better performance in IE 10_x000D_
      var STerror=new Error();_x000D_
      var unformated=(STerror.stack || STerror.stacktrace);_x000D_
      trace_result = "\u25BC console.trace" + unformated.substring(unformated.indexOf('\n',unformated.indexOf('\n'))); _x000D_
     } else {_x000D_
      // IE 11+ and everyone else compatibility_x000D_
      trace_result = console.trace();_x000D_
     }_x000D_
     if (log_result)_x000D_
      console.log( trace_result );_x000D_
     _x000D_
     return trace_result;_x000D_
    }_x000D_
// test code_x000D_
(function testfunc(){_x000D_
 document.write( "<pre>" + stacktrace( false ) + "</pre>" );_x000D_
})();
_x000D_
_x000D_
_x000D_

What is the difference between json.dump() and json.dumps() in python?

There isn't much else to add other than what the docs say. If you want to dump the JSON into a file/socket or whatever, then you should go with dump(). If you only need it as a string (for printing, parsing or whatever) then use dumps() (dump string)

As mentioned by Antti Haapala in this answer, there are some minor differences on the ensure_ascii behaviour. This is mostly due to how the underlying write() function works, being that it operates on chunks rather than the whole string. Check his answer for more details on that.

json.dump()

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object

If ensure_ascii is False, some chunks written to fp may be unicode instances

json.dumps()

Serialize obj to a JSON formatted str

If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance

Passing $_POST values with cURL

<?php
    function executeCurl($arrOptions) {

        $mixCH = curl_init();

        foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
            curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
        }

        $mixResponse = curl_exec($mixCH);
        curl_close($mixCH);
        return $mixResponse;
    }

    // If any HTTP authentication is needed.
    $username = 'http-auth-username';
    $password = 'http-auth-password';

    $requestType = 'POST'; // This can be PUT or POST

    // This is a sample array. You can use $arrPostData = $_POST
    $arrPostData = array(
        'key1'  => 'value-1-for-k1y-1',
        'key2'  => 'value-2-for-key-2',
        'key3'  => array(
                'key31'   => 'value-for-key-3-1',
                'key32'   => array(
                    'key321' => 'value-for-key321'
                )
        ),
        'key4'  => array(
            'key'   => 'value'
        )
    );

    // You can set your post data
    $postData = http_build_query($arrPostData); // Raw PHP array

    $postData = json_encode($arrPostData); // Only USE this when request JSON data.

    $mixResponse = executeCurl(array(
        CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPGET => true,
        CURLOPT_VERBOSE => true,
        CURLOPT_AUTOREFERER => true,
        CURLOPT_CUSTOMREQUEST => $requestType,
        CURLOPT_POSTFIELDS  => $postData,
        CURLOPT_HTTPHEADER  => array(
            "X-HTTP-Method-Override: " . $requestType,
            'Content-Type: application/json', // Only USE this when requesting JSON data
        ),

        // If HTTP authentication is required, use the below lines.
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
        CURLOPT_USERPWD  => $username. ':' . $password
    ));

    // $mixResponse contains your server response.

Fit cell width to content

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

That works in new browsers i.e. IE11+ see table at the bottom of the article.

How do I rename a column in a database table using SQL?

The standard would be ALTER TABLE, but that's not necessarily supported by every DBMS you're likely to encounter, so if you're looking for an all-encompassing syntax, you may be out of luck.

Double decimal formatting in Java

You can do it as follows:

double d = 4.0;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

test if event handler is bound to an element in jQuery

This solution is no more supported since jQuery 1.8 as we can read on the blog here:

$(element).data(“events”): This is now removed in 1.8, but you can still get to the events data for debugging purposes via $._data(element, "events"). Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.

So, you should unbind/rebind it or simply, use a boolean to determine if your event as been attached or not (which is in my opinion the best solution).

Getting "cannot find Symbol" in Java project in Intellij

I know this is an old question, but as per my recent experience, this happens because the build resources are either deleted or Idea cannot recognize them as the source.

Wherever the error appears, provide sources for the folder/directory and this error must be resolved.

Sometimes even when we assign sources for the whole folder, individual classes might still be unavailable. For novice users simple solution is to import a fresh copy and build the application again to be good to go.

It is advisable to do a clean install after this.

Oracle : how to subtract two dates and get minutes of the result

I think you can adapt the function to substract the two timestamps:

return  EXTRACT(MINUTE FROM 
  TO_TIMESTAMP(to_char(p_date1,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
-
  TO_TIMESTAMP(to_char(p_date2,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
);

I think you could simplify it by just using CAST(p_date as TIMESTAMP).

return  EXTRACT(MINUTE FROM cast(p_date1 as TIMESTAMP) - cast(p_date2 as TIMESTAMP));

Remember dates and timestamps are big ugly numbers inside Oracle, not what we see in the screen; we don't need to tell him how to read them. Also remember timestamps can have a timezone defined; not in this case.

Add CSS to <head> with JavaScript?

If you don't want to rely on a javascript library, you can use document.write() to spit out the required css, wrapped in style tags, straight into the document head:

<head>
  <script type="text/javascript">
    document.write("<style>body { background-color:#000 }</style>");
  </script>
  # other stuff..
</head>

This way you avoid firing an extra HTTP request.

There are other solutions that have been suggested / added / removed, but I don't see any point in overcomplicating something that already works fine cross-browser. Good luck!

http://jsbin.com/oqede3/edit

How do I find duplicate values in a table in Oracle?

Here is an SQL request to do that:

select column_name, count(1)
from table
group by column_name
having count (column_name) > 1;

What are all codecs and formats supported by FFmpeg?

Codecs proper:

ffmpeg -codecs

Formats:

ffmpeg -formats

Installed SSL certificate in certificate store, but it's not in IIS certificate list

Had the same problem and found the easy solution thanks to inspiration from the above answers. Here's a quick step-by-step summary:

  1. First open MMC with the Certificates plug in.
  2. Drag-n-drop your new certificate (missing the key on the upper left part of the certificate icon) to the "Personal" certificate store. This I did because the name of the "Web Hosting" store is a so called friendly name and not the real name of the store, and I could not remember the real name which is needed for the command prompt utility certutil. Instead I just remembered that the real name of "Personal" is "My". Makes the rest easy, and once done I just move the certificate back into "Web Hosting".
  3. Once the new certificate (missing the key) is in the "Personal" store, start a command prompt and issue the following command: certutil -store "My" (assuming the quotes are needed)
  4. Note the serial number of your certificate. It's in the first line of the certificate dump. If you have other certificates in the "My" store, then you need to find the one you just moved. Look at expiration date and name for example. Mark and copy the serial number.
  5. Now issue the command certutil -repairstore "My" <paste serial number here> and note the private key is verified.
  6. Move the certificate back to the "Web Hosting" store and refresh. You should now see the certificate icon overlaid with a small key icon in the upper left part.
  7. Now you should be able to choose the certificate from inside the IIS bindings dialog.

Have fun!

How do you create a Spring MVC project in Eclipse?

You don't necessarily have to create a Spring project. Almost all Java web applications have he same project structure. In almost every project I create, I automatically add these source folder:

  • src/main/java
  • src/main/resources
  • src/test/java
  • src/test/resources
  • src/main/webapp*

src/main/webapp isn't actually a source folder. The web.xml file under src/main/webapp/WEB-INF will allow you to run your java application on any Java enabled web server (Tomcat, Jetty, etc.). I typically add the Jetty Plugin to my POM (assuming you use Maven), and launch the web app in development using mvn clean jetty:run.

Android: Expand/collapse animation

This is really simple with droidQuery. For starts, consider this layout:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/v1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="View 1" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/v2"
        android:layout_width="wrap_content"
        android:layout_height="0dp" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="View 2" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="View 3" />
    </LinearLayout>
</LinearLayout>

We can animate the height to the desired value - say 100dp - using the following code:

//convert 100dp to pixel value
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());

Then use droidQuery to animate. The simplest way is with this:

$.animate("{ height: " + height + "}", new AnimationOptions());

To make the animation more appealing, consider adding an easing:

$.animate("{ height: " + height + "}", new AnimationOptions().easing($.Easing.BOUNCE));

You can also change the duration on AnimationOptions using the duration() method, or handle what happens when the animation ends. For a complex example, try:

$.animate("{ height: " + height + "}", new AnimationOptions().easing($.Easing.BOUNCE)
                                                             .duration(1000)
                                                             .complete(new Function() {
                                                                 @Override
                                                                 public void invoke($ d, Object... args) {
                                                                     $.toast(context, "finished", Toast.LENGTH_SHORT);
                                                                 }
                                                             }));

Bootstrap combining rows (rowspan)

Note: This was for Bootstrap 2 (relevant when the question was asked).

You can accomplish this by using row-fluid to make a fluid (percentage) based row inside an existing block.

<div class="row">
   <div class="span5">span5</div>
   <div class="span3">span3</div>
   <div class="span2">
      <div class="row-fluid">
         <div class="span12">span2</div>
         <div class="span12">span2</div>
      </div>
   </div>
   <div class="span2">span2</div>
</div>
<div class="row">
   <div class="span6">
      <div class="row-fluid">
         <div class="span12">span6</div>
         <div class="span12">span6</div>
      </div>
   </div>
   <div class="span6">span6</div>
</div>

Here's a JSFiddle example.

I did notice that there was an odd left margin that appears (or does not appear) for the spans inside of the row-fluid after the first one. This can be fixed with a small CSS tweak (it's the same CSS that is applied to the first child, expanded to those past the first child):

.row-fluid [class*="span"] {
    margin-left: 0;
}

How do I save JSON to local text file

Node.js:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
    if (err) {
        console.log(err);
    }
});

Browser (webapi):

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}
download(jsonData, 'json.txt', 'text/plain');

Emulate/Simulate iOS in Linux

The only solution I can think of is to install VMWare or any other VT then install OSX on a VM.

It works pretty good for testing.

get the value of DisplayName attribute

From within a view that has Class1 as it's strongly typed view model:

ModelMetadata.FromLambdaExpression<Class1, string>(x => x.Name, ViewData).DisplayName;

How can I change the language (to english) in Oracle SQL Developer?

With SQL Developer 4.x, the language option is to be added to ..\sqldeveloper\bin\sqldeveloper.conf, rather than ..\sqldeveloper\bin\ide.conf:

# ----- MODIFICATION BEGIN -----
AddVMOption -Duser.language=en
# ----- MODIFICATION END -----

How to make the background image to fit into the whole page without repeating using plain css?

Depending on what kind of image you have, it might be better to rework the design so that the main image fades to a set solid color or repeatable pattern. If you center the image in the page and have the solid color as the backgroud.

See http://www.webdesignerwall.com/trends/80-large-background-websites/ for examples of sites using large or scalable backgrounds.

Handling the TAB character in Java

Yes the tab character is one character. You can match it in java with "\t".

Can I multiply strings in Java to repeat sequences?

I created a method that do the same thing you want, feel free to try this:

public String repeat(String s, int count) {
    return count > 0 ? s + repeat(s, --count) : "";
}

C# Get/Set Syntax Usage

You are not able to access those properties as they are marked as protected meaning:

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

How to pass an event object to a function in Javascript?

I would change your binding to be:

<button type="button" value="click me" onclick="check_me" />

I would then change your check_me() function declaration to be:

function check_me() {   
  //event.preventDefault();
  var hello = document.myForm.username.value;
  var err = '';

  if(hello == '' || hello == null) {
    err = 'User name required';
  }

  if(err != '') { 
     alert(err); 
     $('username').focus(); 
     event.preventDefault(); 
   } else { 
    return true; }
}

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

No.

If the user is sophisticated or determined enough to:

  1. Open the Excel VBA editor
  2. Use the object browser to see the list of all sheets, including VERYHIDDEN ones
  3. Change the property of the sheet to VISIBLE or just HIDDEN

then they are probably sophisticated or determined enough to:

  1. Search the internet for "remove Excel 2007 project password"
  2. Apply the instructions they find.

So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.

Should I use px or rem value units in my CSS?

em's are the way forward, not just for fonts but you can use them with boxes, line thickness and other stuff too, why?

Put simply em's are the only ones that scale in unison with the alt+ and alt- keys in the browser for zooming.

Other measurements scale, but not as cleanly as an em.

On a side note if you want the best in scaling, also convert your graphics to vector based SVG where possible too as these will also cleanly scale with the browsers zoom ratio.

printing all contents of array in C#

The easiest one e.g. if you have a string array declared like this string[] myStringArray = new string[];

Console.WriteLine("Array : ");
Console.WriteLine("[{0}]", string.Join(", ", myStringArray));

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I couldn't find an off-the-shelf module that added this function, so I wrote one:

In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:

Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String

Substring_Index = delims

start = 0
test = ""

For i = 1 To intCount
    oldstart = start + 1
    start = InStr(oldstart, strWord, strDelim)
    Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i

End Function

Save the module as module1 (the default). You can now use statements like:

SELECT Substring_Index([fieldname],",",2) FROM table

How do I pass along variables with XMLHTTPRequest

If you want to pass variables to the server using GET that would be the way yes. Remember to escape (urlencode) them properly!

It is also possible to use POST, if you dont want your variables to be visible.

A complete sample would be:

var url = "bla.php";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();

http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(null);

To test this, (using PHP) you could var_dump $_GET to see what you retrieve.

justify-content property isn't working

justify-content only has an effect if there's space left over after your flex items have flexed to absorb the free space. In most/many cases, there won't be any free space left, and indeed justify-content will do nothing.

Some examples where it would have an effect:

  • if your flex items are all inflexible (flex: none or flex: 0 0 auto), and smaller than the container.

  • if your flex items are flexible, BUT can't grow to absorb all the free space, due to a max-width on each of the flexible items.

In both of those cases, justify-content would be in charge of distributing the excess space.

In your example, though, you have flex items that have flex: 1 or flex: 6 with no max-width limitation. Your flexible items will grow to absorb all of the free space, and there will be no space left for justify-content to do anything with.

How can I import a database with MySQL from terminal?

Directly from var/www/html

mysql -u username -p database_name < /path/to/file.sql

From within mysql:

mysql> use db_name;
mysql> source backup-file.sql

Convert `List<string>` to comma-separated string

In .NET 4 you don't need the ToArray() call - string.Join is overloaded to accept IEnumerable<T> or just IEnumerable<string>.

There are potentially more efficient ways of doing it before .NET 4, but do you really need them? Is this actually a bottleneck in your code?

You could iterate over the list, work out the final size, allocate a StringBuilder of exactly the right size, then do the join yourself. That would avoid the extra array being built for little reason - but it wouldn't save much time and it would be a lot more code.

Why does Vim save files with a ~ extension?

You're correct that the .swp file is used by vim for locking and as a recovery file.

Try putting set nobackup in your vimrc if you don't want these files. See the Vim docs for various backup related options if you want the whole scoop, or want to have .bak files instead...

How to check if array is not empty?

len(self.table) checks for the length of the array, so you can use if-statements to find out if the length of the list is greater than 0 (not empty):

Python 2:

if len(self.table) > 0:
    #Do code here

Python 3:

if(len(self.table) > 0):
    #Do code here

It's also possible to use

if self.table:
    #Execute if self.table is not empty
else:
    #Execute if self.table is empty

to see if the list is not empty.

Converting string to double in C#

In your string I see: 15.5859949000000662452.23862099999999 which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?

You may also want to figure out if your last String will be empty, and account for that situation.

Convert Swift string to array

You can also create an extension:

var strArray = "Hello, playground".Letterize()

extension String {
    func Letterize() -> [String] {
        return map(self) { String($0) }
    }
}

Call ASP.NET function from JavaScript?

The simplest and best way to achieve this is to use the onmouseup() JavaScript event rather than onclick()

That way you will fire JavaScript after you click and it won't interfere with the ASP OnClick() event.

How can I create persistent cookies in ASP.NET?

FWIW be very careful with storing something like a userid in a cookie unencrypted. Doing this makes your site very prone to cookie poisoning where users can easily impersonate another user. If you are considering something like this I would highly recommend using the forms authentication cookie directly.

bool persist = true;

var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);

cookie.Expires = DateTime.Now.AddMonths(3);

var ticket = FormsAuthentication.Decrypt(cookie.Value);

var userData = "store any string values you want inside the ticket
                 extra than user id that will be encrypted"

var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
     ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);

cookie.Value = FormsAuthentication.Encrypt(newTicket);

Response.Cookies.Add(cookie);

Then you can read this at any time from an ASP.NET page by doing

string userId = null;
if (this.Context.User.Identity.IsAuthenticated) 
{
    userId = this.Context.User.Identity.Name;
}

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

The consequence of this is that you may need a rather insane-looking query, e. g.,

SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID]            AS lngRecordID
          ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]  AS vcrSourceWorkbookName
          ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]      AS vcrImportFileName
          ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]       AS dtmLastWriteTime
          ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]            AS lngNRecords
          ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]          AS lngSizeOnDisk
          ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]        AS lngLastIdentity
          ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
          ,MIN ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodFirstWorkDate
          ,MAX ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodLastWorkDate
          ,SUM ( [tblTimeRecords].[decMan_Hours_Actual] )           AS decHoursWorked
          ,SUM ( [tblTimeRecords].[decAdjusted_Hours] )             AS decHoursBilled
      FROM [dbo].[tblTimeSheetExportFiles]
      LEFT JOIN   [dbo].[tblTimeRecords]
              ON  [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
        GROUP BY  [dbo].[tblTimeSheetExportFiles].[lngRecordID]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
                 ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
                 ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
                 ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]

Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.

Current time in microseconds in java

As other posters already indicated; your system clock is probably not synchronized up to microseconds to actual world time. Nonetheless are microsecond precision timestamps useful as a hybrid for both indicating current wall time, and measuring/profiling the duration of things.

I label all events/messages written to a log files using timestamps like "2012-10-21 19:13:45.267128". These convey both when it happened ("wall" time), and can also be used to measure the duration between this and the next event in the log file (relative difference in microseconds).

To achieve this, you need to link System.currentTimeMillis() with System.nanoTime() and work exclusively with System.nanoTime() from that moment forward. Example code:

/**
 * Class to generate timestamps with microsecond precision
 * For example: MicroTimestamp.INSTANCE.get() = "2012-10-21 19:13:45.267128"
 */ 
public enum MicroTimestamp 
{  INSTANCE ;

   private long              startDate ;
   private long              startNanoseconds ;
   private SimpleDateFormat  dateFormat ;

   private MicroTimestamp()
   {  this.startDate = System.currentTimeMillis() ;
      this.startNanoseconds = System.nanoTime() ;
      this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;
   }

   public String get()
   {  long microSeconds = (System.nanoTime() - this.startNanoseconds) / 1000 ;
      long date = this.startDate + (microSeconds/1000) ;
      return this.dateFormat.format(date) + String.format("%03d", microSeconds % 1000) ;
   }
}

How to connect Robomongo to MongoDB

Note: Commenting out bind_ip can make your system vulnerable to security flaws. Please see Security Checklist. It is a better idea to add more IP addresses than to open up your system to everything.

You need to edit your /etc/mongod.conf file's bind_ip variable to include the IP of the computer you're using, or eliminate it altogether.

I was able to connect using the following mongod.conf file. I commented out bind_ip and uncommented port.

# mongod.conf

# Where to store the data.

# Note: if you run MongoDB as a non-root user (recommended) you may
# need to create and set permissions for this directory manually.
# E.g., if the parent directory isn't mutable by the MongoDB user.

dbpath=/var/lib/mongodb

# Where to log
logpath=/var/log/mongodb/mongod.log

logappend=true

port = 27017

# Listen to local interface only. Comment out to listen on all
interfaces.

#bind_ip = 127.0.0.1


# Disables write-ahead journaling
# nojournal = true

# Enables periodic logging of CPU utilization and I/O wait
#cpu = true

# Turn on/off security.  Off is currently the default
#noauth = true

#auth = true

# Verbose logging output.
#verbose = true

# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck = true

# Enable db quota management
#quota = true

# Set oplogging level where n is
#   0=off (default)
#   1=W
#   2=R
#   3=both
#   7=W+some reads
#diaglog = 0

# Ignore query hints
#nohints = true

# Enable the HTTP interface (Defaults to port 28017).
#httpinterface = true

# Turns off server-side scripting.  This will result in greatly limited
# functionality
#noscripting = true

# Turns off table scans.  Any query that would do a table scan fails.
#notablescan = true

# Disable data file preallocation.
#noprealloc = true

# Specify .ns file size for new databases.
# nssize = <size>

# Replication Options
# In replicated MongoDB databases, specify the replica set name here
#replSet=setname

# Maximum size in megabytes for replication operation log
#oplogSize=1024

# Path to a key file storing authentication info for connections
# between replica set members
#keyFile=/path/to/keyfile

Don't forget to restart the mongod service before trying to connect:

service mongod restart

From Robomongo, I used the following connection settings:

Connection Tab:

  • Address: [VPS IP] : 27017

SSH Tab:

  • SSH Address: [VPS IP] : 22

  • SSH User Name: [Username for sudo enabled user]

  • SSH Auth Method: Password

  • User Password: Supersecret

Update a column value, replacing part of a string

UPDATE urls
SET url = REPLACE(url, 'domain1.com/images/', 'domain2.com/otherfolder/')

Create code first, many to many, with additional fields in association table

The code provided by this answer is right, but incomplete, I've tested it. There are missing properties in "UserEmail" class:

    public UserTest UserTest { get; set; }
    public EmailTest EmailTest { get; set; }

I post the code I've tested if someone is interested. Regards

using System.Data.Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

#region example2
public class UserTest
{
    public int UserTestID { get; set; }
    public string UserTestname { get; set; }
    public string Password { get; set; }

    public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }

    public static void DoSomeTest(ApplicationDbContext context)
    {

        for (int i = 0; i < 5; i++)
        {
            var user = context.UserTest.Add(new UserTest() { UserTestname = "Test" + i });
            var address = context.EmailTest.Add(new EmailTest() { Address = "address@" + i });
        }
        context.SaveChanges();

        foreach (var user in context.UserTest.Include(t => t.UserTestEmailTests))
        {
            foreach (var address in context.EmailTest)
            {
                user.UserTestEmailTests.Add(new UserTestEmailTest() { UserTest = user, EmailTest = address, n1 = user.UserTestID, n2 = address.EmailTestID });
            }
        }
        context.SaveChanges();
    }
}

public class EmailTest
{
    public int EmailTestID { get; set; }
    public string Address { get; set; }

    public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }
}

public class UserTestEmailTest
{
    public int UserTestID { get; set; }
    public UserTest UserTest { get; set; }
    public int EmailTestID { get; set; }
    public EmailTest EmailTest { get; set; }
    public int n1 { get; set; }
    public int n2 { get; set; }


    //Call this code from ApplicationDbContext.ConfigureMapping
    //and add this lines as well:
    //public System.Data.Entity.DbSet<yournamespace.UserTest> UserTest { get; set; }
    //public System.Data.Entity.DbSet<yournamespace.EmailTest> EmailTest { get; set; }
    internal static void RelateFluent(System.Data.Entity.DbModelBuilder builder)
    {
        // Primary keys
        builder.Entity<UserTest>().HasKey(q => q.UserTestID);
        builder.Entity<EmailTest>().HasKey(q => q.EmailTestID);

        builder.Entity<UserTestEmailTest>().HasKey(q =>
            new
            {
                q.UserTestID,
                q.EmailTestID
            });

        // Relationships
        builder.Entity<UserTestEmailTest>()
            .HasRequired(t => t.EmailTest)
            .WithMany(t => t.UserTestEmailTests)
            .HasForeignKey(t => t.EmailTestID);

        builder.Entity<UserTestEmailTest>()
            .HasRequired(t => t.UserTest)
            .WithMany(t => t.UserTestEmailTests)
            .HasForeignKey(t => t.UserTestID);
    }
}
#endregion

Calling a function every 60 seconds

Call a Javascript function every 2 second continuously for 10 second.

_x000D_
_x000D_
var intervalPromise;_x000D_
$scope.startTimer = function(fn, delay, timeoutTime) {_x000D_
    intervalPromise = $interval(function() {_x000D_
        fn();_x000D_
        var currentTime = new Date().getTime() - $scope.startTime;_x000D_
        if (currentTime > timeoutTime){_x000D_
            $interval.cancel(intervalPromise);_x000D_
          }                  _x000D_
    }, delay);_x000D_
};_x000D_
_x000D_
$scope.startTimer(hello, 2000, 10000);_x000D_
_x000D_
hello(){_x000D_
  console.log("hello");_x000D_
}
_x000D_
_x000D_
_x000D_

Is it possible to style html5 audio tag?

Ken had it right as well.

a css tag:

audio {

}

will get you some results. seems it doesnt want the player any height above or below 25px but the width can be shortened or lengthened to an extent.

this was good enough for me; see this example (warning, audio plays automatically): www.thenewyorkerdeliinc.com