Programs & Examples On #Formats

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

phpMyAdmin - Error > Incorrect format parameter?

This issue is not because of corrupt database. I found the solution from this video -

It is suggested to increase the values of two variables in php.ini file. Change following in php.ini


Then restart the server.

This solved my issue. Hope solves yours too.

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

Put in head link to google styles

<link href="" rel="stylesheet">

and in body something like this

<i class="material-icons-outlined">bookmarks</i>

Adding an .env file to React Project

Webpack Users

If you are using webpack, you can install and use dotenv-webpack plugin, to do that follow steps below:

Install the package

yarn add dotenv-webpack

Create a .env file

// .env
API_KEY='my secret api key'

Add it to webpack.config.js file

// webpack.config.js
const Dotenv = require('dotenv-webpack');

module.exports = {
  plugins: [
    new Dotenv()

Use it in your code as


For more information and configuration information, visit here

What is pipe() function in Angular

You have to look to official ReactiveX documentation:

This is a good article about piping in RxJS:

In short .pipe() allows chaining multiple pipeable operators.

Starting in version 5.5 RxJS has shipped "pipeable operators" and renamed some operators:

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.

  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

Error: the entity type requires a primary key

Yet another reason may be that your entity class has several properties named somhow /.*id/i - so ending with ID case insensitive AND elementary type AND there is no [Key] attribute.

EF will namely try to figure out the PK by itself by looking for elementary typed properties ending in ID.

See my case:

public class MyTest, IMustHaveTenant
  public long Id { get; set; }
  public int TenantId { get; set; }
  public virtual string Signum{ get; set; }
  public virtual string ID { get; set; }
  public virtual string ID_Other { get; set; }

don't ask - lecacy code. The Id was even inherited, so I could not use [Key] (just simplifying the code here)

But here EF is totally confused.

What helped was using modelbuilder this in DBContext class.

            modelBuilder.Entity<MyTest>(f =>
                f.HasKey(e => e.Id);
                f.HasIndex(e => new { e.TenantId });
                f.HasIndex(e => new { e.TenantId, e.ID_Other });

the index on PK is implicit.

How to Pass data from child to parent component Angular

In order to send data from child component create property decorated with output() in child component and in the parent listen to the created event. Emit this event with new values in the payload when ever it needed.

@Output() public eventName:EventEmitter = new EventEmitter();

to emit this event:


Deprecation warning in Moment.js - Not in a recognized ISO format

I ran into this error because I was trying to pass in a date from localStorage. Passing the date into a new Date object, and then calling .toISOString() did the trick for me:

const dateFromStorage = localStorage.getItem('someDate');
const date = new Date(dateFromStorage);
const momentDate = moment(date.toISOString());

This suppressed any warnings in the console.

How do you format code on save in VS Code

To automatically format code on save:

  • Press Ctrl , to open user preferences
  • Enter the following code in the opened settings file

        "editor.formatOnSave": true
  • Save file


How to change the datetime format in pandas

Below is the code worked for me, And we need to be very careful for format. Below link will be definitely useful for knowing your exiting format and changing into desired format(Follow strftime() and strptime() Format Codes on below link):

data['date_new_format'] = pd.to_datetime(data['date_to_be_changed'] , format='%b-%y')

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

Choosing the right file format is important to building performant data applications. The concepts outlined in this post carry over to Pandas, Dask, Spark, and Presto / AWS Athena.

Column pruning

Column pruning is a big performance improvement that's possible for column-based file formats (Parquet, ORC) and not possible for row-based file formats (CSV, Avro).

Suppose you have a dataset with 100 columns and want to read two of them into a DataFrame. Here's how you can perform this with Pandas if the data is stored in a Parquet file.

import pandas as pd

pd.read_parquet('some_file.parquet', columns = ['id', 'firstname'])

Parquet is a columnar file format, so Pandas can grab the columns relevant for the query and can skip the other columns. This is a massive performance improvement.

If the data is stored in a CSV file, you can read it like this:

import pandas as pd

pd.read_csv('some_file.csv', usecols = ['id', 'firstname'])

usecols can't skip over entire columns because of the row nature of the CSV file format.

Spark doesn't require users to explicitly list the columns that'll be used in a query. Spark builds up an execution plan and will automatically leverage column pruning whenever possible. Of course, column pruning is only possible when the underlying file format is column oriented.


Spark and Pandas have built-in readers writers for CSV, JSON, ORC, Parquet, and text files. They don't have built-in readers for Avro.

Avro is popular within the Hadoop ecosystem. Parquet has gained significant traction outside of the Hadoop ecosystem. For example, the Delta Lake project is being built on Parquet files.

Arrow is an important project that makes it easy to work with Parquet files with a variety of different languages (C, C++, Go, Java, JavaScript, MATLAB, Python, R, Ruby, Rust), but doesn't support Avro. Parquet files are easier to work with because they are supported by so many different projects.


Parquet stores the file schema in the file metadata. CSV files don't store file metadata, so readers need to either be supplied with the schema or the schema needs to be inferred. Supplying a schema is tedious and inferring a schema is error prone / expensive.

Avro also stores the data schema in the file itself. Having schema in the files is a huge advantage and is one of the reasons why a modern data project should not rely on JSON or CSV.

Column metadata

Parquet stores metadata statistics for each column and lets users add their own column metadata as well.

The min / max column value metadata allows for Parquet predicate pushdown filtering that's supported by the Dask & Spark cluster computing frameworks.

Here's how to fetch the column statistics with PyArrow.

import pyarrow.parquet as pq

parquet_file = pq.ParquetFile('some_file.parquet')
<pyarrow._parquet.Statistics object at 0x11ac17eb0>
  has_min_max: True
  min: 1
  max: 9
  null_count: 0
  distinct_count: 0
  num_values: 3
  physical_type: INT64
  logical_type: None
  converted_type (legacy): NONE

Complex column types

Parquet allows for complex column types like arrays, dictionaries, and nested schemas. There isn't a reliable method to store complex types in simple file formats like CSVs.


Columnar file formats store related types in rows, so they're easier to compress. This CSV file is relatively hard to compress.


This data is easier to compress when the related types are stored in the same row:


Parquet files are most commonly compressed with the Snappy compression algorithm. Snappy compressed files are splittable and quick to inflate. Big data systems want to reduce file size on disk, but also want to make it quick to inflate the flies and run analytical queries.

Mutable nature of file

Parquet files are immutable, as described here. CSV files are mutable.

Adding a row to a CSV file is easy. You can't easily add a row to a Parquet file.

Data lakes

In a big data environment, you'll be working with hundreds or thousands of Parquet files. Disk partitioning of the files, avoiding big files, and compacting small files is important. The optimal disk layout of data depends on your query patterns.

How to display .svg image using swift

You can use this pod called 'SVGParser'.

After adding it in your pod file, all you have to do is to import this module to the class that you want to use it. You should show the SVG image in an ImageView.

There are three cases you can show this SVGimage:

  1. Load SVG from local path as Data
  2. Load SVG from local path
  3. Load SVG from remote URL

You can also find an example project in GitHub: Just download the project and run it to see how it works.

How to save .xlsx data to file as a blob

The answer above is correct. Please be sure that you have a string data in base64 in the data variable without any prefix or stuff like that just raw data.

Here's what I did on the server side ( mvc core):

string path = Path.Combine(folder, fileName);
Byte[] bytes = System.IO.File.ReadAllBytes(path);
string base64 = Convert.ToBase64String(bytes);

On the client side, I did the following code:

const xhr = new XMLHttpRequest();"GET", url);
xhr.setRequestHeader("Content-Type", "text/plain");

xhr.onload = () => {
    var bin = atob(xhr.response);
    var ab = s2ab(bin); // from example above
    var blob = new Blob([ab], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });

    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob); = 'demo.xlsx';




And it works perfectly for me.

Format y axis as percent

This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):

import ...
import matplotlib.ticker as mtick

ax = df['myvar'].plot(kind='bar')

PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0).

The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None and '%', respectively. decimals=None will automatically set the number of decimal points based on how much of the axes you are showing.


PercentFormatter was introduced into Matplotlib proper in version 2.1.0.

How can I print out just the index of a pandas dataframe?

.index.tolist() is another function which you can get the index as a list:

In [1391]: datasheet.head(20).index.tolist()
Out[1391]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

It should be:


instead of


then restart mysqld service.

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

Light red fill with dark red text.

{'bg_color':   '#FFC7CE', 'font_color': '#9C0006'})

Light yellow fill with dark yellow text.

{'bg_color':   '#FFEB9C', 'font_color': '#9C6500'})

Green fill with dark green text.

{'bg_color':   '#C6EFCE', 'font_color': '#006100'})

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.

return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);

How do I format a date as ISO 8601 in moment.js?

Also possible with vanilla JS

new Date().toISOString() // "2017-08-26T16:31:02.349Z"

How to auto adjust the div size for all mobile / tablet display formats?

Whilst I was looking for my answer for the same question, I found this:

<img src="img.png" style=max-
width:100%;overflow:hidden;border:none;padding:0;margin:0 auto;display:block;" marginheight="0" marginwidth="0">

You can use it inside a tag (iframe or img) the image will adjust based on it's device.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The Accept Ranges header (the bit in writeHead()) is required for the HTML5 video controls to work.

I think instead of just blindly send the full file, you should first check the Accept Ranges header in the REQUEST, then read in and send just that bit. fs.createReadStream support start, and end option for that.

So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream to send the requested part to the client.

var fs = require("fs"),
    http = require("http"),
    url = require("url"),
    path = require("path");

http.createServer(function (req, res) {
  if (req.url != "/movie.mp4") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
  } else {
    var file = path.resolve(__dirname,"movie.mp4");
    fs.stat(file, function(err, stats) {
      if (err) {
        if (err.code === 'ENOENT') {
          // 404 Error if file not found
          return res.sendStatus(404);
      var range = req.headers.range;
      if (!range) {
       // 416 Wrong range
       return res.sendStatus(416);
      var positions = range.replace(/bytes=/, "").split("-");
      var start = parseInt(positions[0], 10);
      var total = stats.size;
      var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
      var chunksize = (end - start) + 1;

      res.writeHead(206, {
        "Content-Range": "bytes " + start + "-" + end + "/" + total,
        "Accept-Ranges": "bytes",
        "Content-Length": chunksize,
        "Content-Type": "video/mp4"

      var stream = fs.createReadStream(file, { start: start, end: end })
        .on("open", function() {
        }).on("error", function(err) {

Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.

# Change minor ticks to show every 5. (20/4 = 5)

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

ORA-00907: missing right parenthesis

I would recommend separating out all of the foreign-key constraints from your CREATE TABLE statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.

You can add an FK constraint to a table using SQL like the following:

  FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);

In particular, your formats and library tables both have foreign-key constraints on one another. The two CREATE TABLE statements to create these two tables can never run successfully, as each will only work when the other table has already been created.

Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.

Angular bootstrap datepicker date format does not format ng-model value

Defining a new directive to work around a bug is not really ideal.

Because the datepicker displays later dates correctly, one simple workaround could be just setting the model variable to null first, and then to the current date after a while:

$scope.dt = null;
$timeout( function(){
    $scope.dt = new Date();

Get month and year from date cells Excel

I had a requirement to provide a report showing details by month where the date field was formatted as date & time, I simply changed the formatting of the date column to "General" and then used the following formula in a new column,


What is the best way to trigger onchange event in react js

You can simulate events using ReactTestUtils but that's designed for unit testing.

I'd recommend not using valueLink for this case and simply listening to change events fired by the plugin and updating the input's state in response. The two-way binding utils more as a demo than anything else; they're included in addons only to emphasize the fact that pure two-way binding isn't appropriate for most applications and that you usually need more application logic to describe the interactions in your app.

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

JPG vs. JPEG image formats

There's no difference between the file extensions, and they are used interchangeably. I guess the 3-letter version stems from the DOS era...

However, there are different "flavors" of JPEG files. Most notably the JFIF standard and the EXIF standard. Most often these just use .jpg or .jpeg as file extensions, JFIF sometimes uses .jif or .jfif.

Converting between datetime and Pandas Timestamp objects

Pandas Timestamp to datetime.datetime:

pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()

datetime.datetime to Timestamp

pd.Timestamp(datetime(2014, 1, 23))

What is difference between png8 and png24

You have asked two questions, one in the title about the difference between PNG8 and PNG24, which has received a few answers, namely that PNG24 has 8-bit red, green, and blue channels, and PNG-8 has a single 8-bit index into a palette. Naturally, PNG24 usually has a larger filesize than PNG8. Furthermore, PNG8 usually means that it is opaque or has only binary transparency (like GIF); it's defined that way in ImageMagick/GraphicsMagick.

This is an answer to the other one, "I would like to know that if I use either type in my html page, will there be any error? Or is this only quality matter?"

You can put either type on an HTML page and no, this won't cause an error; the files should all be named with the ".png" extension and referred to that way in your HTML. Years ago, early versions of Internet Explorer would not handle PNG with an alpha channel (PNG32) or indexed-color PNG with translucent pixels properly, so it was useful to convert such images to PNG8 (indexed-color with binary transparency conveyed via a PNG tRNS chunk) -- but still use the .png extension, to be sure they would display properly on IE. I think PNG24 was always OK on Internet Explorer because PNG24 is either opaque or has GIF-like single-color transparency conveyed via a PNG tRNS chunk.

The names PNG8 and PNG24 aren't mentioned in the PNG specification, which simply calls them all "PNG". Other names, invented by others, include

  • PNG8 or PNG-8 (indexed-color with 8-bit samples, usually means opaque or with GIF-like, binary transparency, but sometimes includes translucency)
  • PNG24 or PNG-24 (RGB with 8-bit samples, may have GIF-like transparency via tRNS)
  • PNG32 (RGBA with 8-bit samples, opaque, transparent, or translucent)
  • PNG48 (Like PNG24 but with 16-bit R,G,B samples)
  • PNG64 (like PNG32 but with 16-bit R,G,B,A samples)

There are many more possible combinations including grayscale with 1, 2, 4, 8, or 16-bit samples and indexed PNG with 1, 2, or 4-bit samples (and any of those with transparent or translucent pixels), but those don't have special names.

Get first and last day of month using threeten, LocalDate

Jon Skeets answer is right and has deserved my upvote, just adding this slightly different solution for completeness:

import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.with(lastDayOfMonth());

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

This is not a problem with XAML. The error message is saying that it tried to create an instance of DVRClientInterface.MainWindow and your constructor threw an exception.

You will need to look at the "Inner Exception" property to determine the underlying cause. It could be quite literally anything, but should provide direction.

example of an inner exception shown in Visual Studio

An example would be that if you are connecting to a database in the constructor for your window, and for some reason that database is unavailable, the inner exception may be a TimeoutException or a SqlException or any other exception thrown by your database code.

If you are throwing exceptions in static constructors, the exception could be generated from any class referenced by the MainWindow. Class initializers are also run, if any MainWindow fields are calling a method which may throw.

How to prepare a Unity project for git?

Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository
  2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save scene and project from File menu

Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

More information about keeping Unity Project under source control you can find in this post.

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

How to use Select2 with JSON via Ajax request?

My ajax never gets fired until I wrapped the whole thing in

setTimeout(function(){ .... }, 3000);

I was using it in mounted section of Vue. it needs more time.

Excel VBA: Copying multiple sheets into new workbook

Try do something like this (the problem was that you trying to use MyBook.Worksheets, but MyBook is not a Workbook object, but string, containing workbook name. I've added new varible Set WB = ActiveWorkbook, so you can use WB.Worksheets instead MyBook.Worksheets):

Sub NewWBandPasteSpecialALLSheets()
   MyBook = ActiveWorkbook.Name ' Get name of this book
   Workbooks.Add ' Open a new workbook
   NewBook = ActiveWorkbook.Name ' Save name of new book

   Workbooks(MyBook).Activate ' Back to original book

   Set WB = ActiveWorkbook

   Dim SH As Worksheet

   For Each SH In WB.Worksheets



       With SH.Range("A1")
        .PasteSpecial (xlPasteColumnWidths)
        .PasteSpecial (xlFormats)
        .PasteSpecial (xlValues)

       End With


End Sub

But your code doesn't do what you want: it doesen't copy something to a new WB. So, the code below do it for you:

Sub NewWBandPasteSpecialALLSheets()
   Dim wb As Workbook
   Dim wbNew As Workbook
   Dim sh As Worksheet
   Dim shNew As Worksheet

   Set wb = ThisWorkbook
   Workbooks.Add ' Open a new workbook
   Set wbNew = ActiveWorkbook

   On Error Resume Next

   For Each sh In wb.Worksheets

      'add new sheet into new workbook with the same name
      With wbNew.Worksheets

          Set shNew = Nothing
          Set shNew = .Item(sh.Name)

          If shNew Is Nothing Then
              .Add After:=.Item(.Count)
              .Item(.Count).Name = sh.Name
              Set shNew = .Item(.Count)
          End If
      End With

      With shNew.Range("A1")
          .PasteSpecial (xlPasteColumnWidths)
          .PasteSpecial (xlFormats)
          .PasteSpecial (xlValues)
      End With
End Sub

Intellij idea subversion checkout error: `Cannot run program "svn"`

If you're using IntelliJ 13 with SVN 1.8, you have to install SVN command line client. Please see more information here:

Unlike its earlier versions, Subversion 1.8 support uses the native command line client instead of SVNKit to run commands. This approach is more flexible and makes the support of upcoming versions much easier. Now, IntelliJ IDEA offers different integration options for each specific Subversion:

1.6 – SVNKit only

1.7 – SVNKit and command line client

1.8 – Command line client only

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

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

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

Similarly, fully qualify all your Cells object.

Excel VBA date formats

Format converts the values to strings. IsDate still returns true because it can parse that string and get a valid date.

If you don't want to change the cells to string, don't use Format. (IOW, don't convert them to strings in the first place.) Use the Cell.NumberFormat, and set it to the date format you want displayed.

ActiveCell.NumberFormat = "mm/dd/yy"   ' Outputs 10/28/13
ActiveCell.NumberFormat = "dd/mm/yyyy" ' Outputs 28/10/2013

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I had the same error with python runserver.

For me, it turned out that it was because of a stale compiled binary (.pyc) file. After deleting all such files in my project, server started running again. :)

So if you get this error, out of nowhere, i.e without making any change seemingly-related to django-settings, this could be a good first measure.

Compare two date formats in javascript/jquery

To comapre dates of string format (mm-dd-yyyy).

    var job_start_date = "10-1-2014"; // Oct 1, 2014
    var job_end_date = "11-1-2014"; // Nov 1, 2014
    job_start_date = job_start_date.split('-');
    job_end_date = job_end_date.split('-');

    var new_start_date = new Date(job_start_date[2],job_start_date[0],job_start_date[1]);
    var new_end_date = new Date(job_end_date[2],job_end_date[0],job_end_date[1]);

    if(new_end_date <= new_start_date) {
      // your code

Trigger an action after selection select2

See the documentation events section

Depending on the version, one of the snippets below should give you the event you want, alternatively just replace "select2-selecting" with "change".

Version 4.0 +

Events are now in format: select2:selecting (instead of select2-selecting)

Thanks to snakey for the notification that this has changed as of 4.0

$('#yourselect').on("select2:selecting", function(e) { 
   // what you would like to happen

Version Before 4.0

$('#yourselect').on("select2-selecting", function(e) { 
   // what you would like to happen

Just to clarify, the documentation for select2-selecting reads:

select2-selecting Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. This event is used to allow the user to reject selection by calling event.preventDefault()

whereas change has:

change Fired when selection is changed.

So change may be more appropriate for your needs, depending on whether you want the selection to complete and then do your event, or potentially block the change.

Why isn't .ico file defined when setting window's icon?

Both codes are working fine with me on python 3.7..... hope will work for u as well

import tkinter as tk
m.title("SALAH Tutorials")

and do not forget to keep "myfavicon.ico" in the same folder where your project script file is present

Another method

from tkinter import *
m.title("SALAH Tutorials")

[*NOTE:- python version-3 works with tkinter and below version-3 i.e version-2 works with Tkinter]

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

All you have to do is apply the format you want in the html helper call, ie.

@Html.TextBoxFor(m => m.RegistrationDate, "{0:dd/MM/yyyy}")

You don't need to provide the date format in the model class.

SimpleDateFormat parse loses timezone


what is the way to retrieve a Date object so that its always in GMT? 


You are using troublesome confusing old date-time classes that are now supplanted by the java.time classes.

Instant = UTC

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = ; // Current moment in UTC.

ISO 8601

To exchange this data as text, use the standard ISO 8601 formats exclusively. These formats are sensibly designed to be unambiguous, easy to process by machine, and easy to read across many cultures by people.

The java.time classes use the standard formats by default when parsing and generating strings.

String output = instant.toString() ;  


Time zone

If you want to see that same moment as presented in the wall-clock time of a particular region, apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Asia/Singapore" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same simultaneous moment, same point on the timeline.

See this code live at

Notice the eight hour difference, as the time zone of Asia/Singapore currently has an offset-from-UTC of +08:00. Same moment, different wall-clock time.

instant.toString(): 2017-01-23T12:34:56.123456789Z

zdt.toString(): 2017-01-23T20:34:56.123456789+08:00[Asia/Singapore]


Avoid the legacy java.util.Date class. But if you must, you can convert. Look to new methods added to the old classes.

java.util.Date date = Date.from( instant ) ;

…going the other way…

Instant instant = myJavaUtilDate.toInstant() ;


For date-only, use LocalDate.

LocalDate ld = zdt.toLocalDate() ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

I've used ng-change:

Date.prototype.addDays = function(days) {_x000D_
  var dat = new Date(this.valueOf());_x000D_
  dat.setDate(dat.getDate() + days);_x000D_
  return dat;_x000D_
var app = angular.module('myApp', []);_x000D_
app.controller('DateController', ['$rootScope', '$scope',_x000D_
  function($rootScope, $scope) {_x000D_
    function init() {_x000D_
      $scope.startDate = new Date();_x000D_
      $scope.endDate = $scope.startDate.addDays(14);_x000D_
    function load() {_x000D_
    // public methods_x000D_
    $scope.load = load;_x000D_
    $scope.setStart = function(date) {_x000D_
      $scope.startDate = date;_x000D_
    $scope.setEnd = function(date) {_x000D_
      $scope.endDate = date;_x000D_
<script src=""></script>_x000D_
<div data-ng-controller="DateController">_x000D_
  <label class="item-input"> <span class="input-label">Start</span>_x000D_
    <input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
  <label class="item-input"> <span class="input-label">End</span>_x000D_
    <input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
  <button button="button" ng-disabled="planningForm.$invalid" ng-click="load()" class="button button-positive">_x000D_
</div <label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
  <input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_

Reset select2 value and show placeholder

You can clear te selection by


But it wont turn you back to your placeholder.

So its a half solution

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I set up a simple 3-column range on Sheet1 with Country, City, and Language in columns A, B, and C. The following code autofilters the range and then pastes only one of the columns of autofiltered data to another sheet. You should be able to modify this for your purposes:

Sub CopyPartOfFilteredRange()
    Dim src As Worksheet
    Dim tgt As Worksheet
    Dim filterRange As Range
    Dim copyRange As Range
    Dim lastRow As Long

    Set src = ThisWorkbook.Sheets("Sheet1")
    Set tgt = ThisWorkbook.Sheets("Sheet2")

    ' turn off any autofilters that are already set
    src.AutoFilterMode = False

    ' find the last row with data in column A
    lastRow = src.Range("A" & src.Rows.Count).End(xlUp).Row

    ' the range that we are auto-filtering (all columns)
    Set filterRange = src.Range("A1:C" & lastRow)

    ' the range we want to copy (only columns we want to copy)
    ' in this case we are copying country from column A
    ' we set the range to start in row 2 to prevent copying the header
    Set copyRange = src.Range("A2:A" & lastRow)

    ' filter range based on column B
    filterRange.AutoFilter field:=2, Criteria1:="Rio de Janeiro"

    ' copy the visible cells to our target range
    ' note that you can easily find the last populated row on this sheet
    ' if you don't want to over-write your previous results
    copyRange.SpecialCells(xlCellTypeVisible).Copy tgt.Range("A1")

End Sub

Note that by using the syntax above to copy and paste, nothing is selected or activated (which you should always avoid in Excel VBA) and the clipboard is not used. As a result, Application.CutCopyMode = False is not necessary.

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

You should use setTimestamp instead, if you hardcode it:

$start_date = new DateTime();

in your case

$start_date = new DateTime();

Difference between java HH:mm and hh:mm on SimpleDateFormat

Use the built-in localized formats

If this is for showing a time of day to a user, then in at least 19 out of 20 you don’t need to care about kk, HH nor hh. I suggest that you use something like this:

    DateTimeFormatter defaultTimeFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
    System.out.format("%s: %s%n",
            Locale.getDefault(), LocalTime.MIN.format(defaultTimeFormatter));

The point is that it gives different output in different default locales. For example:

en_SS: 12:00 AM
fr_BL: 00:00
ps_AF: 0:00
es_CO: 12:00 a.m.

The localized formats have been designed to conform with the expectations of different cultures. So they generally give the user a better experience and they save you of writing a format pattern string, which is always error-prone.

I furthermore suggest that you don’t use SimpleDateFormat. That class is notoriously troublesome and fortunately long outdated. Instead I use java.time, the modern Java date and time API. It is so much nicer to work with.

Four pattern letters for hour: H, h, k and K

Of course if you need to parse a string with a specified format, and also if you have a very specific formatting requirement, it’s good to use a format pattern string. There are actually four different pattern letters to choose from for hour (quoted from the documentation):

  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-day (1-24)    number            24
   H       hour-of-day (0-23)          number            0

In practice H and h are used. As far as I know k and K are not (they may just have been included for the sake of completeness). But let’s just see them all in action:

    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofPattern("hh:mm a  HH:mm  kk:mm  KK:mm a", Locale.ENGLISH);
    System.out.println(LocalTime.of(0, 0).format(timeFormatter));
    System.out.println(LocalTime.of(1, 15).format(timeFormatter));
    System.out.println(LocalTime.of(11, 25).format(timeFormatter));
    System.out.println(LocalTime.of(12, 35).format(timeFormatter));
    System.out.println(LocalTime.of(13, 40).format(timeFormatter));
12:00 AM  00:00  24:00  00:00 AM
01:15 AM  01:15  01:15  01:15 AM
11:25 AM  11:25  11:25  11:25 AM
12:35 PM  12:35  12:35  00:35 PM
01:40 PM  13:40  13:40  01:40 PM

If you don’t want the leading zero, just specify one pattern letter, that is h instead of hh or H instead of HH. It will still accept two digits when parsing, and if a number to be printed is greater than 9, two digits will still be printed.


How do DATETIME values work in SQLite?

One of the powerful features of SQLite is allowing you to choose the storage type. Advantages/disadvantages of each of the three different possibilites:

  • ISO8601 string

    • String comparison gives valid results
    • Stores fraction seconds, up to three decimal digits
    • Needs more storage space
    • You will directly see its value when using a database browser
    • Need for parsing for other uses
    • "default current_timestamp" column modifier will store using this format
  • Real number

    • High precision regarding fraction seconds
    • Longest time range
  • Integer number

    • Lowest storage space
    • Quick operations
    • Small time range
    • Possible year 2038 problem

If you need to compare different types or export to an external application, you're free to use SQLite's own datetime conversion functions as needed.

cURL not working (Error #77) for SSL connections on CentOS for non-root users

The error is due to corrupt or missing SSL chain certificate files in the PKI directory. You’ll need to make sure the files ca-bundle, following steps: In your console/terminal:

mkdir /usr/src/ca-certificates && cd /usr/src/ca-certificates

Enter this site: , get your ca-certificate, for yout SO, for example: << CentOS. Copy url of download and paste in url: wget your_url_donwload_ca-ceritificated.rpm now, install yout rpm:

rpm2cpio your_url_donwload_ca-ceritificated.rpm | cpio -idmv

now restart your service: my example this command:

sudo service2 httpd restart

very great good look

Regular expression to match standard 10 digit phone number

Perhaps the easiest one compare to several others.


It matches the following:

(555) 444-6789



555 444 6789

How to fix date format in ASP .NET BoundField (DataFormatString)?

Formatting depends on the server's culture setting. If you use en-US culture, you can use Short Date Pattern like {0:d}

For example, it formats 6/15/2009 1:45:30 to 6/15/2009

You can check more formats from BoundField.DataFormatString

Check if a string is a valid date using DateTime.TryParse

Use DateTime.TryParseExact() if you want to match against a specific date format

 string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
    DateTimeStyles.None, out dateTime))
    Console.WriteLine("Not a date");

Correct way to convert size in bytes to KB, MB, GB in JavaScript

function bytesToSize(bytes) {_x000D_
  var sizes = ['B', 'K', 'M', 'G', 'T', 'P'];_x000D_
  for (var i = 0; i < sizes.length; i++) {_x000D_
    if (bytes <= 1024) {_x000D_
      return bytes + ' ' + sizes[i];_x000D_
    } else {_x000D_
      bytes = parseFloat(bytes / 1024).toFixed(2)_x000D_
  return bytes + ' P';_x000D_

Writing an Excel file in EPPlus

It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

.. which will produce a beautiful excelsheet with a nice table!

Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..


Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);


How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

Remove "SSLv2ClientHello" from the enabled protocols on the client SSLSocket or HttpsURLConnection.

python dict to numpy structured array

Similarly to the approved answer. If you want to create an array from dictionary keys:

np.array( tuple(dict.keys()) )

If you want to create an array from dictionary values:

np.array( tuple(dict.values()) )

Extracting double-digit months and days from a Python date

Look at the types of those properties:

In [1]: import datetime

In [2]: d =

In [3]: type(d.month)
Out[3]: <type 'int'>

In [4]: type(
Out[4]: <type 'int'>

Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.

If you want leading zeroes, you'll have to format them one way or another. For that you have several options:

In [5]: '{:02d}'.format(d.month)
Out[5]: '03'

In [6]: '%02d' % d.month
Out[6]: '03'

In [7]: d.strftime('%m')
Out[7]: '03'

In [8]: f'{d.month:02d}'
Out[8]: '03'

How do I change select2 box height

I use the following to dynamically adjust height of the select2 dropdown element so it nicely fits the amount of options:

$('select').on('select2:open', function (e) {
  var OptionsSize = $(this).find("option").size(); // The amount of options 
  var HeightPerOption = 36; // the height in pixels every option should be
  var DropDownHeight = OptionsSize * HeightPerOption;

Make sure to unset the (default) max-height in css:

.select2-container--default .select2-results>.select2-results__options {
  max-height: inherit;

(only tested in version 4 of select2)


try this:

select convert(varchar, dob2, 101)
select convert(varchar, dob2, 102)
select convert(varchar, dob2, 103)
select convert(varchar, dob2, 104)
select convert(varchar, dob2, 105)
select convert(varchar, dob2, 106)
select convert(varchar, dob2, 107)
select convert(varchar, dob2, 108)
select convert(varchar, dob2, 109)
select convert(varchar, dob2, 110)
select convert(varchar, dob2, 111)
select convert(varchar, dob2, 112)
select convert(varchar, dob2, 113)


Saving to CSV in Excel loses regional date format

You can save your desired date format from Excel to .csv by following this procedure, hopefully an excel guru can refine further and reduce the number of steps:

  1. Create a new column DATE_TMP and set it equal to the =TEXT( oldcolumn, "date-format-arg" ) formula.

For example, in your example if your dates were in column A the value in row 1 for this new column would be:

=TEXT( A1, "dd/mm/yyyy" )

  1. Insert a blank column DATE_NEW next to your existing date column.

  2. Paste the contents of DATE_TMP into DATE_NEW using the "paste as value" option.

  3. Remove DATE_TMP and your existing date column, rename DATE_NEW to your old date column.

  4. Save as csv.

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This is documented behavior. From ?as.Date:

format: A character string. If not specified, it will try '"%Y-%m-%d"' then '"%Y/%m/%d"' on the first non-'NA' element, and give an error if neither works.

as.Date("01 Jan 2000") yields an error because the format isn't one of the two listed above. as.Date("01/01/2000") yields an incorrect answer because the date isn't in one of the two formats listed above.

I take "standard unambiguous" to mean "ISO-8601" (even though as.Date isn't that strict, as "%m/%d/%Y" isn't ISO-8601).

If you receive this error, the solution is to specify the format your date (or datetimes) are in, using the formats described in ?strptime. Be sure to use particular care if your data contain day/month names and/or abbreviations, as the conversion will depend on your locale (see the examples in ?strptime and read ?LC_TIME).

How to format a date using ng-model?

Angularjs ui bootstrap you can use angularjs ui bootstrap, it provides date validation also

<input type="text"  class="form-control" 
datepicker-popup="{{format}}" ng-model="dt" is-open="opened" 
min-date="minDate" max-date="'2015-06-22'"  datepickeroptions="dateOptions"
date-disabled="disabled(date, mode)" ng-required="true"> 

in controller can specify whatever format you want to display the date as datefilter

$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];

batch script - run command on each file in directory

I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.

set codedirectory=C:\Users\code
for /r  %codedirectory% %%i in (*.c) do 
( some GCC commands )

Writing MemoryStream to Response Object

First We Need To Write into our Memory Stream and then with the help of Memory Stream method "WriteTo" we can write to the Response of the Page as shown in the below code.

   MemoryStream filecontent = null;
   filecontent =//CommonUtility.ExportToPdf(inputXMLtoXSLT);(This will be your MemeoryStream Content)
   Response.ContentType = "image/pdf";
   string headerValue = string.Format("attachment; filename={0}", formName.ToUpper() + ".pdf");
   Response.AppendHeader("Content-Disposition", headerValue);



FormName is the fileName given,This code will make the generated PDF file downloadable by invoking a PopUp.

What Are The Best Width Ranges for Media Queries

best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920

java.util.NoSuchElementException - Scanner reading user input

This has really puzzled me for a while but this is what I found in the end.

When you call, sc.close() in first method, it not only closes your scanner but closes your input stream as well. You can verify it by printing its status at very top of the second method as :


So, now when you re-instantiate, Scanner in second method, it doesn't find any open stream and hence the exception.

I doubt if there is any way out to reopen because:

public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**

The only good solution for your problem is to initiate the Scanner in your main method, pass that as argument in your two methods, and close it again in your main method e.g.:

main method related code block:

Scanner scanner = new Scanner(;  

// Ask users for quantities 
PromptCustomerQty(customer, ProductList, scanner );

// Ask user for payment method
PromptCustomerPayment(customer, scanner );

//close the scanner 

Your Methods:

 public static void PromptCustomerQty(Customer customer, 
                             ArrayList<Product> ProductList, Scanner scanner) {

    // no more scanner instantiation
    // no more scanner close

 public static void PromptCustomerPayment (Customer customer, Scanner sc) {

    // no more scanner instantiation
    // no more scanner close

Hope this gives you some insight about the failure and possible resolution.

Get the system date and split day, month and year

Here is what you are looking for:

String sDate = DateTime.Now.ToString();
DateTime datevalue = (Convert.ToDateTime(sDate.ToString()));

String dy = datevalue.Day.ToString();
String mn = datevalue.Month.ToString();
String yy = datevalue.Year.ToString();


Alternatively, you can use split function to split string date into day, month and year here.

Hope, it will helps you... Cheers. !!

What are the date formats available in SimpleDateFormat class?

check the formats here


System.out.println("date  : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));


 public String getMyDate(String myDate, String returnFormat, String myFormat)
                DateFormat dateFormat = new SimpleDateFormat(returnFormat);
                Date date=null;
                String returnValue="";
                try {
                    date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
                    returnValue = dateFormat.format(date);
                } catch (ParseException e) {
                    returnValue= myDate;

            return returnValue;

RSA Public Key format

You can't just change the delimiters from ---- BEGIN SSH2 PUBLIC KEY ---- to -----BEGIN RSA PUBLIC KEY----- and expect that it will be sufficient to convert from one format to another (which is what you've done in your example).

This article has a good explanation about both formats.

What you get in an RSA PUBLIC KEY is closer to the content of a PUBLIC KEY, but you need to offset the start of your ASN.1 structure to reflect the fact that PUBLIC KEY also has an indicator saying which type of key it is (see RFC 3447). You can see this using openssl asn1parse and -strparse 19, as described in this answer.

EDIT: Following your edit, your can get the details of your RSA PUBLIC KEY structure using grep -v -- ----- | tr -d '\n' | base64 -d | openssl asn1parse -inform DER:

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim: INTEGER           :FB1199FF0733F6E805A4FD3B36CA68E94D7B974621162169C71538A539372E27F3F51DF3B08B2E111C2D6BBF9F5887F13A8DB4F1EB6DFE386C92256875212DDD00468785C18A9C96A292B067DDC71DA0D564000B8BFD80FB14C1B56744A3B5C652E8CA0EF0B6FDA64ABA47E3A4E89423C0212C07E39A5703FD467540F874987B209513429A90B09B049703D54D9A1CFE3E207E0E69785969CA5BF547A36BA34D7C6AEFE79F314E07D9F9F2DD27B72983AC14F1466754CD41262516E4A15AB1CFB622E651D3E83FA095DA630BD6D93E97B0C822A5EB4212D428300278CE6BA0CC7490B854581F0FFB4BA3D4236534DE09459942EF115FAA231B15153D67837A63
  265:d=1  hl=2 l=   3 prim: INTEGER           :010001

To decode the SSH key format, you need to use the data format specification in RFC 4251 too, in conjunction with RFC 4253:

   The "ssh-rsa" key format has the following specific encoding:

      string    "ssh-rsa"
      mpint     e
      mpint     n

For example, at the beginning, you get 00 00 00 07 73 73 68 2d 72 73 61. The first four bytes (00 00 00 07) give you the length. The rest is the string itself: 73=s, 68=h, ... -> 73 73 68 2d 72 73 61=ssh-rsa, followed by the exponent of length 1 (00 00 00 01 25) and the modulus of length 256 (00 00 01 00 7f ...).

Exception: "URI formats are not supported"

I solved the same error with the Path.Combine(MapPath()) to get the physical file path instead of the http:/// www one.

what's the correct way to send a file from REST web service to client?

Since youre using JSON, I would Base64 Encode it before sending it across the wire.

If the files are large, try to look at BSON, or some other format that is better with binary transfers.

You could also zip the files, if they compress well, before base64 encoding them.

How to save a figure in MATLAB from the command line?

try plot(var); saveFigure('title'); it will save as a jpeg automatically

How to make Sonar ignore some classes for codeCoverage metric?

Sometimes, Clover is configured to provide code coverage reports for all non-test code. If you wish to override these preferences, you may use configuration elements to exclude and include source files from being instrumented:


Also, you can include the following Sonar configuration:


How do I get the current date and current time only respectively in Django?

import datetime ("%Y%m%d")

For the time

from time import gmtime, strftime
showtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print showtime
2015-10-15 07:49:18

Datatable date sorting dd/mm/yyyy issue

Update 2020: HTML Solution

Since HTML 5 is so much developed and almost all major browser supporting it. So now a much cleaner approach is to use HTML5 data attributes (maxx777 provided a PHP solution I am using the simple HTML). For non-numeric data as in our scenario, we can use data-sort or data-order attribute and assign a sortable value to it.


<td data-sort='YYYYMMDD'>DD/MM/YYYY</td>

Here is working HTML solution

jQuery Solution

Here is working jQuery solution.

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"date-uk-pre": function ( a ) {
    var ukDatea = a.split('/');
    return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;

"date-uk-asc": function ( a, b ) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));

"date-uk-desc": function ( a, b ) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
} );

Add the above code to script and set the specific column with Date values with { "sType": "date-uk" } and others as null, see below:

$(document).ready(function() {
    $('#example').dataTable( {
        "aoColumns": [
            { "sType": "date-uk" },

DateTime.TryParseExact() rejecting valid formats

Try C# 7.0

var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
 ? dt : DateTime.Parse("1800-01-01");

HTML Input="file" Accept Attribute File Type (CSV)

These days you can just use the file extension

<input type="file" ID="fileSelect" accept=".xlsx, .xls, .csv"/>

Display calendar to pick a date in java

I wrote a DateTextField component.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class DateTextField extends JTextField {

    private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
    private static final int DIALOG_WIDTH = 200;
    private static final int DIALOG_HEIGHT = 200;

    private SimpleDateFormat dateFormat;
    private DatePanel datePanel = null;
    private JDialog dateDialog = null;

    public DateTextField() {
        this(new Date());

    public DateTextField(String dateFormatPattern, Date date) {
        DEFAULT_DATE_FORMAT = dateFormatPattern;

    public DateTextField(Date date) {
        setCursor(new Cursor(Cursor.HAND_CURSOR));

    private void addListeners() {
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent paramMouseEvent) {
                if (datePanel == null) {
                    datePanel = new DatePanel();
                Point point = getLocationOnScreen();
                point.y = point.y + 30;
                showDateDialog(datePanel, point);

    private void showDateDialog(DatePanel dateChooser, Point position) {
        Frame owner = (Frame) SwingUtilities
        if (dateDialog == null || dateDialog.getOwner() != owner) {
            dateDialog = createDateDialog(owner, dateChooser);
        dateDialog.setLocation(getAppropriateLocation(owner, position));

    private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
        JDialog dialog = new JDialog(owner, "Date Selected", true);
        dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
        dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
        return dialog;

    private Point getAppropriateLocation(Frame owner, Point position) {
        Point result = new Point(position);
        Point p = owner.getLocation();
        int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
        int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());

        if (offsetX > 0) {
            result.x -= offsetX;

        if (offsetY > 0) {
            result.y -= offsetY;

        return result;

    private SimpleDateFormat getDefaultDateFormat() {
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
        return dateFormat;

    public void setText(Date date) {

    public void setDate(Date date) {

    public Date getDate() {
        try {
            return getDefaultDateFormat().parse(getText());
        } catch (ParseException e) {
            return new Date();

    private class DatePanel extends JPanel implements ChangeListener {
        int startYear = 1980;
        int lastYear = 2050;

        Color backGroundColor = Color.gray;
        Color palletTableColor = Color.white;
        Color todayBackColor =;
        Color weekFontColor =;
        Color dateFontColor =;
        Color weekendFontColor =;

        Color controlLineColor =;
        Color controlTextColor = Color.white;

        JSpinner yearSpin;
        JSpinner monthSpin;
        JButton[][] daysButton = new JButton[6][7];

        DatePanel() {
            setLayout(new BorderLayout());
            setBorder(new LineBorder(backGroundColor, 2));

            JPanel topYearAndMonth = createYearAndMonthPanal();
            add(topYearAndMonth, BorderLayout.NORTH);
            JPanel centerWeekAndDay = createWeekAndDayPanal();
            add(centerWeekAndDay, BorderLayout.CENTER);


        private JPanel createYearAndMonthPanal() {
            Calendar cal = getCalendar();
            int currentYear = cal.get(Calendar.YEAR);
            int currentMonth = cal.get(Calendar.MONTH) + 1;

            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());

            yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
                    startYear, lastYear, 1));
            yearSpin.setPreferredSize(new Dimension(56, 20));
            yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));

            JLabel yearLabel = new JLabel("Year");

            monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
                    12, 1));
            monthSpin.setPreferredSize(new Dimension(35, 20));

            JLabel monthLabel = new JLabel("Month");

            return panel;

        private JPanel createWeekAndDayPanal() {
            String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
            JPanel panel = new JPanel();
            panel.setFont(new Font("Arial", Font.PLAIN, 10));
            panel.setLayout(new GridLayout(7, 7));

            for (int i = 0; i < 7; i++) {
                JLabel cell = new JLabel(colname[i]);
                if (i == 0 || i == 6) {
                } else {

            int actionCommandId = 0;
            for (int i = 0; i < 6; i++)
                for (int j = 0; j < 7; j++) {
                    JButton numBtn = new JButton();
                    numBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                            JButton source = (JButton) event.getSource();
                            if (source.getText().length() == 0) {
                            int newDay = Integer.parseInt(source.getText());
                            Calendar cal = getCalendar();
                            cal.set(Calendar.DAY_OF_MONTH, newDay);


                    if (j == 0 || j == 6)
                    daysButton[i][j] = numBtn;

            return panel;

        private Calendar getCalendar() {
            Calendar calendar = Calendar.getInstance();
            return calendar;

        private int getSelectedYear() {
            return ((Integer) yearSpin.getValue()).intValue();

        private int getSelectedMonth() {
            return ((Integer) monthSpin.getValue()).intValue();

        private void dayColorUpdate(boolean isOldDay) {
            Calendar cal = getCalendar();
            int day = cal.get(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
            int i = actionCommandId / 7;
            int j = actionCommandId % 7;
            if (isOldDay) {
            } else {

        private void reflushWeekAndDay() {
            Calendar cal = getCalendar();
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 7; j++) {
                    String s = "";
                    if (dayNo >= 1 && dayNo <= maxDayNo) {
                        s = String.valueOf(dayNo);

        public void stateChanged(ChangeEvent e) {

            JSpinner source = (JSpinner) e.getSource();
            Calendar cal = getCalendar();
            if (source.getName().equals("Year")) {
                cal.set(Calendar.YEAR, getSelectedYear());
            } else {
                cal.set(Calendar.MONTH, getSelectedMonth() - 1);

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

This can be achieved through LINQ with grouping, here a list of items pointed as a data source to the actual grid view. Sample pseudo code which could help coding the actual.

var tabelDetails =(from li in dc.My_table
    join m in dc.Table_One on li.ID equals m.ID
    join c in dc.Table_two on li.OtherID equals c.ID
    where //Condition
group new { m, li, c } by new
} into g
select new
    Name = g.Key.FullName,
    sponsorBonus= g.Where(s => s.c.Name == "sponsorBonus").Count(),
    pairingBonus = g.Where(s => s.c.Name == "pairingBonus").Count(),
    staticBonus = g.Where(s => s.c.Name == "staticBonus").Count(),   
    leftBonus = g.Where(s => s.c.Name == "leftBonus").Count(),  
    rightBonus = g.Where(s => s.c.Name == "rightBonus").Count(),  
    Total = g.Count()  //Row wise Total
}).OrderBy(t => t.Name).ToList();

tabelDetails.Insert(tabelDetails.Count(), new  //This data will be the last row of the grid
    Name = "Total",  //Column wise total
    sponsorBonus = tabelDetails.Sum(s => s.sponsorBonus),
    pairingBonus = tabelDetails.Sum(s => s.pairingBonus),
    staticBonus = tabelDetails.Sum(s => s.staticBonus),
    leftBonus = tabelDetails.Sum(s => s.leftBonus),
    rightBonus = tabelDetails.Sum(s => s.rightBonus ),
    Total = tabelDetails.Sum(s => s.Total)

Phone mask with jQuery and Masked Input Plugin

With jquery.mask.js


<input type="text" class="phone" maxlength="15" value="85999998888">
<input type="text" class="phone" maxlength="15" value="8533334444">


// Function
function phoneMask(e){
    var s=e.val();
    var s=s.replace(/[_\W]+/g,'');
    var n=s.length;
    if(n<11){var m='(00) 0000-00000';}else{var m='(00) 00000-00000';}

// Type

// On load

Only jQuery


<p class="phone">85999998888</p>
<p class="phone">8599998888</p>


$('.phone').text(function(i, text) {
    var n = (text.length)-6;
    if(n==4){var p=n;}else{var p=5;}
    var regex = new RegExp('(\\d{2})(\\d{'+p+'})(\\d{4})');
    var text = text.replace(regex, "($1) $2-$3");
    return text;

Format datetime in mvc 4

Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

    if (!string.IsNullOrEmpty(displayFormat) && value != null)
        DateTime date;
        displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
        // use the format specified in the DisplayFormat attribute to parse the date
         if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
            return date;
                string.Format("{0} is an invalid date format", value.AttemptedValue)

    return base.BindModel(controllerContext, bindingContext);

Hope this could help someone else...

Google Play app description formatting

Another alternative to cut, copy and paste emojis is:

The Completest Cocos2d-x Tutorial & Guide List

Here you got complementaries discussions about the topic, it can be interesting.



MySQL date format DD/MM/YYYY select query?

ORDER BY a date type does not depend on the date format, the date format is only for showing, in the database, they are same data.

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

var d = new Date();

// calling the function

function formatDate(dateObj,format)
    var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
    var curr_date = dateObj.getDate();
    var curr_month = dateObj.getMonth();
    curr_month = curr_month + 1;
    var curr_year = dateObj.getFullYear();
    var curr_min = dateObj.getMinutes();
    var curr_hr= dateObj.getHours();
    var curr_sc= dateObj.getSeconds();
    if(curr_month.toString().length == 1)
    curr_month = '0' + curr_month;      
    if(curr_date.toString().length == 1)
    curr_date = '0' + curr_date;
    if(curr_hr.toString().length == 1)
    curr_hr = '0' + curr_hr;
    if(curr_min.toString().length == 1)
    curr_min = '0' + curr_min;

    if(format ==1)//dd-mm-yyyy
        return curr_date + "-"+curr_month+ "-"+curr_year;       
    else if(format ==2)//yyyy-mm-dd
        return curr_year + "-"+curr_month+ "-"+curr_date;       
    else if(format ==3)//dd/mm/yyyy
        return curr_date + "/"+curr_month+ "/"+curr_year;       
    else if(format ==4)// MM/dd/yyyy HH:mm:ss
        return curr_month+"/"+curr_date +"/"+curr_year+ " "+curr_hr+":"+curr_min+":"+curr_sc;       

How to reduce the image file size using PIL

If you hava a fact png (1MB for 400x400 etc.):


extract digits in a simple way from a python string

The simplest way to extract a number from a string is to use regular expressions and findall.

>>> import re
>>> s = '300 gm'
>>> re.findall('\d+', s)
>>> s = '300 gm 200 kgm some more stuff a number: 439843'
>>> re.findall('\d+', s)
['300', '200', '439843']

It might be that you need something more complex, but this is a good first step.

Note that you'll still have to call int on the result to get a proper numeric type (rather than another string):

>>> map(int, re.findall('\d+', s))
[300, 200, 439843]

DB2 Date format

One more solution REPLACE (CHAR(current date, ISO),'-','')

Example using Hyperlink in WPF

One of the most beautiful ways in my opinion (since it is now commonly available) is using behaviours.

It requires:

  • nuget dependency: Microsoft.Xaml.Behaviors.Wpf
  • if you already have behaviours built in you might have to follow this guide on Microsofts blog.

xaml code:



<Hyperlink NavigateUri="{Binding Path=Link}">
        <behaviours:HyperlinkOpenBehaviour ConfirmNavigation="True"/>
        <Run Text="{Binding Path=Link}"/>

behaviour code:

using System.Windows;
using System.Windows.Documents;
using System.Windows.Navigation;
using Microsoft.Xaml.Behaviors;

namespace YourNameSpace
    public class HyperlinkOpenBehaviour : Behavior<Hyperlink>
        public static readonly DependencyProperty ConfirmNavigationProperty = DependencyProperty.Register(
            nameof(ConfirmNavigation), typeof(bool), typeof(HyperlinkOpenBehaviour), new PropertyMetadata(default(bool)));

        public bool ConfirmNavigation
            get { return (bool) GetValue(ConfirmNavigationProperty); }
            set { SetValue(ConfirmNavigationProperty, value); }

        /// <inheritdoc />
        protected override void OnAttached()
            this.AssociatedObject.RequestNavigate += NavigationRequested;
            this.AssociatedObject.Unloaded += AssociatedObjectOnUnloaded;

        private void AssociatedObjectOnUnloaded(object sender, RoutedEventArgs e)
            this.AssociatedObject.Unloaded -= AssociatedObjectOnUnloaded;
            this.AssociatedObject.RequestNavigate -= NavigationRequested;

        private void NavigationRequested(object sender, RequestNavigateEventArgs e)
            if (!ConfirmNavigation || MessageBox.Show("Are you sure?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)

            e.Handled = true;

        private void OpenUrl()
//          Process.Start(new ProcessStartInfo(AssociatedObject.NavigateUri.AbsoluteUri));
            MessageBox.Show($"Opening {AssociatedObject.NavigateUri}");

        /// <inheritdoc />
        protected override void OnDetaching()
            this.AssociatedObject.RequestNavigate -= NavigationRequested;

python-pandas and databases like mysql

And this is how you connect to PostgreSQL using psycopg2 driver (install with "apt-get install python-psycopg2" if you're on Debian Linux derivative OS).

import as psql
import psycopg2

conn = psycopg2.connect("dbname='datawarehouse' user='user1' host='localhost' password='uberdba'")

q = """select month_idx, sum(payment) from bi_some_table"""

df3 = psql.frame_query(q, conn)

Sublime Text 2 Code Formatting

A similar option in Sublime Text is the built in Edit->Line->Reindent. You can put this code in Preferences -> Key Bindings User:

{ "keys": ["alt+shift+f"], "command": "reindent"} 

I use alt+shift+f because I'm a Netbeans user.

To format your code, select all by pressing ctrl+a and "your key combination". Excuse me for my bad english.

Or if you don't want to select all before formatting, add an argument to the command instead:

{ "keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false} }

(as per comment by @Supr below)

MySQL date formats - difficulty Inserting a date

The date format for mysql insert query is YYYY-MM-DD


INSERT INTO table_name (date_column) VALUE ('YYYY-MM-DD');

milliseconds to time in javascript

Editing RobG's solution and using JavaScript's Date().

function msToTime(ms) {

    function addZ(n) {
        return (n<10? '0':'') + n;
    var dt = new Date(ms);
    var hrs = dt.getHours();
    var mins = dt.getMinutes();
    var secs = dt.getSeconds();
    var millis = dt.getMilliseconds();

    var tm = addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs) + "." + millis;
    return tm;

Convert HH:MM:SS string to seconds only in javascript

This can be done quite resiliently with the following:

'01:02:03'.split(':').reduce((acc,time) => (60 * acc) + +time);

This is because each unit of time within the hours, minutes and seconds is a multiple of 60 greater than the smaller unit. Time is split into hour minutes and seconds components, then reduced to seconds by using the accumulated value of the higher units multiplied by 60 as it goes through each unit.

The +time is used to cast the time to a number.

It basically ends up doing: (60 * ((60 * HHHH) + MM)) + SS

If only seconds is passed then the result would be a string, so to fix that we could cast the entire result to an int:

+('03'.split(':').reduce((acc,time) => (60 * acc) + +time));

matplotlib savefig in jpeg format

Just install pillow with pip install pillow and it will work.

fast way to copy formatting in excel

Just use the NumberFormat property after the Value property: In this example the Ranges are defined using variables called ColLetter and SheetRow and this comes from a for-next loop using the integer i, but they might be ordinary defined ranges of course.

TransferSheet.Range(ColLetter & SheetRow).Value = Range(ColLetter & i).Value TransferSheet.Range(ColLetter & SheetRow).NumberFormat = Range(ColLetter & i).NumberFormat

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

How to obtain image size using standard Python class (without using external library)?

It depends on the output of file which I am not sure is standardized on all systems. Some JPEGs don't report the image size

import subprocess, re
image_size = list(map(int, re.findall('(\d+)x(\d+)', subprocess.getoutput("file" + filename))[-1]))

How to change Git log date formats

Git 2.7 (Q4 2015) will introduce -local as an instruction.
It means that, in addition to:


you will also have:


The -local suffix cannot be used with raw or relative. Reference.

You now can ask for any date format using the local timezone. See

See commit add00ba, commit 547ed71 (03 Sep 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 7b09c45, 05 Oct 2015)

In particular, the last from above (commit add00ba) mentions:

date: make "local" orthogonal to date format:

Most of our "--date" modes are about the format of the date: which items we show and in what order.
But "--date=local" is a bit of an oddball. It means "show the date in the normal format, but using the local timezone".
The timezone we use is orthogonal to the actual format, and there is no reason we could not have "localized iso8601", etc.

This patch adds a "local" boolean field to "struct date_mode", and drops the DATE_LOCAL element from the date_mode_type enum (it's now just DATE_NORMAL plus local=1).
The new feature is accessible to users by adding "-local" to any date mode (e.g., "iso-local"), and we retain "local" as an alias for "default-local" for backwards compatibility.

When should the xlsm or xlsb formats be used?

The XLSB format is also dedicated to the macros embeded in an hidden workbook file located in excel startup folder (XLSTART).

A quick & dirty test with a xlsm or xlsb in XLSTART folder:

Measure-Command { $x = New-Object -com Excel.Application ;$x.Visible = $True ; $x.Quit() }

0,89s with a xlsb (binary) versus 1,3s with the same content in xlsm format (xml in a zip file) ... :)

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

To be honest I don't know how to check the content of the validation errors. Visual Studio shows me that it's an array with 8 objects, so 8 validation errors.

Actually you should see the errors if you drill into that array in Visual studio during debug. But you can also catch the exception and then write out the errors to some logging store or the console:

    // Your code...
    // Could also be before try if you know the exception occurs in SaveChanges

catch (DbEntityValidationException e)
    foreach (var eve in e.EntityValidationErrors)
        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);

EntityValidationErrors is a collection which represents the entities which couldn't be validated successfully, and the inner collection ValidationErrors per entity is a list of errors on property level.

These validation messages are usually helpful enough to find the source of the problem.


A few slight improvements:

The value of the offending property can be included in the inner loop like so:

        foreach (var ve in eve.ValidationErrors)
            Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",

While debugging Debug.Write might be preferable over Console.WriteLine as it works in all kind of applications, not only console applications (thanks to @Bart for his note in the comments below).

For web applications that are in production and that use Elmah for exception logging it turned out to be very useful for me to create a custom exception and overwrite SaveChanges in order to throw this new exception.

The custom exception type looks like this:

public class FormattedDbEntityValidationException : Exception
    public FormattedDbEntityValidationException(DbEntityValidationException innerException) :
        base(null, innerException)

    public override string Message
            var innerException = InnerException as DbEntityValidationException;
            if (innerException != null)
                StringBuilder sb = new StringBuilder();

                foreach (var eve in innerException.EntityValidationErrors)
                    sb.AppendLine(string.Format("- Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().FullName, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                        sb.AppendLine(string.Format("-- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",

                return sb.ToString();

            return base.Message;

And SaveChanges can be overwritten the following way:

public class MyContext : DbContext
    // ...

    public override int SaveChanges()
            return base.SaveChanges();
        catch (DbEntityValidationException e)
            var newException = new FormattedDbEntityValidationException(e);
            throw newException;

A few remarks:

  • The yellow error screen that Elmah shows in the web interface or in the sent emails (if you have configured that) now displays the validation details directly at the top of the message.

  • Overwriting the Message property in the custom exception instead of overwriting ToString() has the benefit that the standard ASP.NET "Yellow screen of death (YSOD)" displays this message as well. In contrast to Elmah the YSOD apparently doesn't use ToString(), but both display the Message property.

  • Wrapping the original DbEntityValidationException as inner exception ensures that the original stack trace will still be available and is displayed in Elmah and the YSOD.

  • By setting a breakpoint on the line throw newException; you can simply inspect the newException.Message property as a text instead of drilling into the validation collections which is a bit awkward and doesn't seem to work easily for everyone (see comments below).

How can I convert a Timestamp into either Date or DateTime object?

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {

    public static void main(String[] args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Date date = new Date(timestamp.getTime());

        // S is the millisecond
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");


Javascript - Regex to validate date format

If you want to validate your date(YYYY-MM-DD) along with the comparison it will be use full for you...

    function validateDate()
     var newDate = new Date();
     var presentDate = newDate.getDate();
     var presentMonth = newDate.getMonth();
     var presentYear = newDate.getFullYear();
     var dateOfBirthVal = document.forms[0].dateOfBirth.value;
    if (dateOfBirthVal == null) 
    return false;
    var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
    dateValues = dateOfBirthVal.match(validatePattern);
    if (dateValues == null) 
        alert("Date of birth should be null and it should in the format of yyyy-mm-dd")
    return false;
    var birthYear = dateValues[1];        
    birthMonth = dateValues[3];
    birthDate=  dateValues[5];
    if ((birthMonth < 1) || (birthMonth > 12)) 
        alert("Invalid date")
    return false;
    else if ((birthDate < 1) || (birthDate> 31)) 
        alert("Invalid date")
    return false;
    else if ((birthMonth==4 || birthMonth==6 || birthMonth==9 || birthMonth==11) && birthDate ==31) 
        alert("Invalid date")
    return false;
    else if (birthMonth == 2){ 
    var isleap = (birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0));
    if (birthDate> 29 || (birthDate ==29 && !isleap)) 
        alert("Invalid date")
    return false;
    else if((birthYear>presentYear)||(birthYear+70<presentYear))
        alert("Invalid date")
        return false;
    else if(birthYear==presentYear)
            alert("Invalid date")
            return false;
        else if(birthMonth==presentMonth+1)
                alert("Invalid date")
                return false;
return true;

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

Convert date formats in bash

Just with bash:

convert_date () {
    local i
    for (( i=0; i<11; i++ )); do
        [[ $2 = ${months[$i]} ]] && break
    printf "%4d%02d%02d\n" $3 $(( i+1 )) $1

And invoke it like this

d=$( convert_date 27 JUN 2011 )

Or if the "old" date string is stored in a variable

d_old="27 JUN 2011"
d=$( convert_date $d_old )  # not quoted

Check whether a path is valid

Just Simply Use

if (System.IO.Directory.Exists(path))

How to do URL decoding in Java?

I use apache commons

String decodedUrl = new URLCodec().decode(url);

The default charset is UTF-8

How to render a DateTime in a specific format in ASP.NET MVC 3?

My preference is to keep the formatting details with the view and not the viewmodel. So in MVC4/Razor:

@Html.TextBoxFor(model => model.DateTime, "{0:d}");

datetime format reference:

Then I have a JQuery datepicker bound to it, and that put's the date in as a different format...doh!

Looks like I need to set the datepicker's format to the same formatting.

So I'm storing the System.Globalization formatting in a data-* attribute and collecting it when setting up the

    model => model.DateTime.Date, 
        @class = "datePicker", 

And here's the sucky part: the formats of .net and datepicker do not match, so hackery is needed:


that's kind of weak, but should cover a lot of cases.

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like and

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

ffmpeg usage to encode a video to H264 codec format

I believe that by now the above answers are outdated (or at least unclear) so here's my little go at it. I tried compiling ffmpeg with the option --enable-encoders=libx264 and it will give no error but it won't enable anything (I can't seem to find where I found that suggestion).

Anyways step-by-step, first you must compile libx264 yourself because repository version is outdated:

  tar --bzip2 -xvf last_x264.tar.bz2
  cd x264-snapshot-XXXXXXXX-XXXX/
  sudo make install

And then get and compile ffmpeg with libx264 enabled. I'm using the latest release which is "Happiness":

tar --bzip2 -xvf ffmpeg-0.11.2.tar.bz2
cd ffmpeg-0.11.2/
./configure --enable-libx264 --enable-gpl
sudo install

Now finally you have the libx264 codec to encode, to check it you may run

ffmpeg -codecs | grep h264

and you'll see the options you have were the first D means decoding and the first E means encoding

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

For a PHP-specific you could try PHPWord - this library is written in pure PHP and provides a set of classes to write to and read from different document file formats (including .doc and .docx). The main drawback is that the quality of converted files can be quite variable.

Alternatively if you want a higher quality option you could use a file conversion API like Zamzar. You can use it to convert a wide range of office formats (and others) into PDF, and you can call from any platform (Windows, Linux, OS X etc).

PHP code to convert a file would look like this:

$endpoint = "";
$apiKey = "API_KEY";
$sourceFilePath = "/my.doc"; // Or docx/xls/xlsx etc
$targetFormat = "pdf";

$postData = array(
  "source_file" => $sourceFile,
  "target_format" => $targetFormat

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);

$response = json_decode($body, true);

Full disclosure: I'm the lead developer for the Zamzar API.

Is there a date format to display the day of the week in java?

Yep - 'E' does the trick

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-E");

Reset Excel to default borders

I understand this is an old post. But it is programmable. Otherwise make sure your fill is set to "No Fill" and your boarders are set to "No Boarder" via the user interface shown in the previous posts.

Sub clear()
Range("A4:G1000").Borders.LineStyle = xlNone 
Range("A4:G1000").Interior.ColorIndex = xlNone 
End Sub()

Float to String format specifier

You can pass a format string to the ToString method, like so:

ToString("N4"); // 4 decimal points Number

If you want to see more modifiers, take a look at MSDN - Standard Numeric Format Strings

Double value to round up in Java

double TotalPrice=90.98989898898;

  DecimalFormat format_2Places = new DecimalFormat("0.00");

    TotalPrice = Double.valueOf(format_2Places.format(TotalPrice));

How can I get date and time formats based on Culture Info?

Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture:

Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);

customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;

DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));

Validate phone number with JavaScript

Just ignore everything but digits.

Here is what I use:

// USA phones should contain at least 10 digits. For Ukrainian phones it's OK to have only 9 digits, without leading 0 and country code prefix: [+380] 88 888-88-88.
String.prototype.isValidPhone = function(digitsCount) {
  var str = this.trim().match(/\d/g);
  return str && str.length >= (digitsCount || 10); // default is at least 10 digits

Can I have a video with transparent background using HTML5 video tag?

webm format is the best solution for Chrome > 29, but it is not supported in Firefox IE and Safari, the best solution is using Flash (wmode="transparent"). but you have to forget "ios".

How to parse dates in multiple formats using SimpleDateFormat

This solution checks all the possible formats before throwing an exception. This solution is more convenient if you are trying to test for multiple date formats.

Date extractTimestampInput(String strDate){
    final List<String> dateFormats = Arrays.asList("yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd");    

    for(String format: dateFormats){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.parse(strDate);
        } catch (ParseException e) {
             //intentionally empty
        throw new IllegalArgumentException("Invalid input for date. Given '"+strDate+"', expecting format yyyy-MM-dd HH:mm:ss.SSS or yyyy-MM-dd.");


Rotating videos with FFmpeg

Smartphone: Recored a video in vertical format

Want to send it to a webside it was 90° to the left (anti clockwise, landscape format) hmm.

ffmpeg -i input.mp4 -vf "rotate=0" output.mp4

does it. I got vertical format back again

debian buster: ffmpeg --version ffmpeg version 4.1.4-1~deb10u1 Copyright (c) 2000-2019 the FFmpeg developers

Select method of Range class failed via VBA

This is how you get around that in an easy non-complicated way.
Instead of using sheet(x).range use Activesheet.range("range").select

Using ffmpeg to encode a high quality video

A couple of things:

  • You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k to the command line to get more or less DVD video bitrate.

  • You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264 as part of the command line. Otherwise -vcodec mpeg4 will also do a better job than MPEG-1, but not as well as x264.

  • There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.

How do I get the YouTube video ID from a URL?

I have summed up all the suggestions and here is the universal and short answer to this question:


What are all codecs and formats supported by FFmpeg?

You can see the list of supported codecs in the official documentation:

Supported video codecs

Supported audio codecs

Convert audio files to mp3 using ffmpeg

I had to purge my ffmpeg and then install another one from a ppa:

sudo apt-get purge ffmpeg
sudo apt-add-repository -y ppa:jon-severinsson/ffmpeg 
sudo apt-get update 
sudo apt-get install ffmpeg

Then convert:

 ffmpeg -i audio.ogg -f mp3 newfile.mp3

Converting video to HTML5 ogg / ogv and mpg4

MS Expression Encoder can do mp4/h.264. not sure about ogg though.

Strtotime() doesn't work with dd/mm/YYYY format

{{ date('d F Y',strtotime($a->dates)) }}

alternative use laravel

\Carbon\Carbon::parse($a->dates)->format('d F Y') }}

jquery data selector

At the moment I'm selecting like this:


Which seems to work just fine, but it would be nice if jQuery was able to select by that attribute without the 'data-' prefix.

I haven't tested this with data added to elements via jQuery dynamically, so that could be the downfall of this method.

PHP json_decode() returns NULL with valid JSON?

$json_url = "";
$json = file_get_contents($json_url);


$data = json_decode($json);

echo "<pre>";
echo "</pre>";

Java SimpleDateFormat for time zone with a colon separator?

Try setLenient(false).

Addendum: It looks like you're recognizing variously formatted Date strings. If you have to do entry, you might like looking at this example that extends InputVerifier.

How can I mix LaTeX in with Markdown?

I was looking for exactly the same thing when I found teqhtml. It does the conversion of $ and $$ equations to images with the nice bonus of aligning the resulting image vertically with the surrounding text. Not a lot of doc but it's quite straightforward.

Hope it helps some future readers.

jQuery and TinyMCE: textarea value doesn't submit

var text = tinyMCE.activeEditor.getContent();
$('<textarea id="textareaid" name="textareaid">'+text+'</textarea>').insertAfter($('[name=someinput]'));

Setting the filter to an OpenFileDialog to allow the typical image formats?

To filter images files, use this code sample.

//Create a new instance of openFileDialog
OpenFileDialog res = new OpenFileDialog();

res.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.gif;*.tif;...";

//When the user select the file
if (res.ShowDialog() == DialogResult.OK)
   //Get the file's path
   var filePath = res.FileName;
   //Do something

Best way to check if a URL is valid

You can use a native Filter Validator

filter_var($url, FILTER_VALIDATE_URL);

Validates value as URL (according to », optionally with required components. Beware a valid URL may not specify the HTTP protocol http:// so further validation may be required to determine the URL uses an expected protocol, e.g. ssh:// or mailto:. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.


if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
    die('Not a valid URL');

Date only from TextBoxFor()

You can also use the HTML 5 attributes by applying this data annotation:


But the problem is this enables a browser specific date picker for HTML 5 browsers. You still need your own date picker for browsers without support, and then you have to make sure your date picker doesn't appear in addition to a browser's (Modernizr can do this easily), or hide the browser's if it does(complicated and I don't know how reliable methods I saw were).

In the end I went with Alex's because my current environment doesn't have Modernizr, but if it did, I would have used that to conditionally only show my data picker if the browser didn't support one already.

Video file formats supported in iPhone

Quoting the iPhone OS Technology Overview:

iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:

  • H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • Numerous audio formats, including the ones listed in “Audio Technologies”

For information about the classes of the Media Player framework, see Media Player Framework Reference.

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Somewhere in that mess, the non-breaking spaces from the HTML template (the  s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character

That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as " ". That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.

What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your &nbsp; strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.

Well anyway, for now you can add one of the following to your document's <head> and see if that makes it look right in the browser:

  • for HTML4: <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  • for HTML5: <meta charset="utf-8">

If you've done that, then any remaining problem is ActivePDF's fault.

Convert seconds to hh:mm:ss in Python

Just be careful when dividing by 60: division between integers returns an integer -> 12/60 = 0 unless you import division from future. The following is copy and pasted from Python 2.6.2:

IDLE 2.6.2      
>>> 12/60
>>> from __future__ import division
>>> 12/60

How to get number of rows using SqlDataReader in C#

I also face a situation when I needed to return a top result but also wanted to get the total rows that where matching the query. i finaly get to this solution:

   public string Format(SelectQuery selectQuery)
      string result;

      if (string.IsNullOrWhiteSpace(selectQuery.WherePart))
        result = string.Format(
declare @maxResult  int;
set @maxResult = {0};

SELECT count(*) as [Count] FROM {2}
SELECT top (@maxResult) Total.[Count], {1} FROM Total, {2}", m_limit.To, selectQuery.SelectPart, selectQuery.FromPart);
        result = string.Format(
declare @maxResult  int;
set @maxResult = {0};

SELECT count(*) as [Count] FROM {2} WHERE {3}
SELECT top (@maxResult) Total.[Count], {1} FROM Total, {2} WHERE {3}", m_limit.To, selectQuery.SelectPart, selectQuery.FromPart, selectQuery.WherePart);

      if (!string.IsNullOrWhiteSpace(selectQuery.OrderPart))
        result = string.Format("{0} ORDER BY {1}", result, selectQuery.OrderPart);

      return result;

How to mark-up phone numbers?

As one would expect, WebKit's support of tel: extends to the Android mobile browser as well - FYI

Format XML string to print friendly XML string

if you load up the XMLDoc I'm pretty sure the .ToString() function posses an overload for this.

But is this for debugging? The reason that it is sent like that is to take up less space (i.e stripping unneccessary whitespace from the XML).

Where can I find documentation on formatting a date in JavaScript?

If you want to show only time with two digits, this may helps you:

var now = new Date();
var cHour = now.getHours();
var cMinuts = now.getMinutes();
var cSeconds = now.getSeconds();

var outStr = (cHour <= 0 ? ('0' + cHour) : cHour) + ':' + (cMinuts <= 9 ? ('0' + cMinuts) : cMinuts) + ':' + (cSeconds <= 9 ? '0' + cSeconds : cSeconds);

Set mouse focus and move cursor to end of input using jQuery

Ref: @will824 Comment, This solution worked for me with no compatibility issues. Rest of solutions failed in IE9.

var input = $("#inputID");
var tmp = input.val();

Tested and found working in:

Firefox 33
Chrome 34
Safari 5.1.7
IE 9

Setting mime type for excel document

For .xls use the following content-type


For Excel 2007 version and above .xlsx files format


What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

As mentioned, you can use:

=Format(Fields!Price.Value, "C")

A digit after the "C" will specify precision:

=Format(Fields!Price.Value, "C0")
=Format(Fields!Price.Value, "C1")

You can also use Excel-style masks like this:

=Format(Fields!Price.Value, "#,##0.00")

Haven't tested the last one, but there's the idea. Also works with dates:

=Format(Fields!Date.Value, "yyyy-MM-dd")

Parse String to Date with Different Format in Java

Use the SimpleDateFormat class:

private Date parseDate(String date, String format) throws ParseException
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    return formatter.parse(date);


Date date = parseDate("19/05/2009", "dd/MM/yyyy");

For efficiency, you would want to store your formatters in a hashmap. The hashmap is a static member of your util class.

private static Map<String, SimpleDateFormat> hashFormatters = new HashMap<String, SimpleDateFormat>();

public static Date parseDate(String date, String format) throws ParseException
    SimpleDateFormat formatter = hashFormatters.get(format);

    if (formatter == null)
        formatter = new SimpleDateFormat(format);
        hashFormatters.put(format, formatter);

    return formatter.parse(date);

CSV parsing in Java - working example..?

I agree with @Brian Clapper. I have used SuperCSV as a parser though I've had mixed results. I enjoy the versatility of it, but there are some situations within my own csv files for which I have not been able to reconcile "yet". I have faith in this product and would recommend it overall--I'm just missing something simple, no doubt, that I'm doing in my own implementation.

SuperCSV can parse the columns into various formats, do edits on the columns, etc. It's worth taking a look-see. It has examples as well, and easy to follow.

The one/only limitation I'm having is catching an 'empty' column and parsing it into an Integer or maybe a blank, etc. I'm getting null-pointer errors, but javadocs suggest each cellProcessor checks for nulls first. So, I'm blaming myself first, for now. :-)

Anyway, take a look at SuperCSV.

Where's the DateTime 'Z' format specifier?

Maybe the "K" format specifier would be of some use. This is the only one that seems to mention the use of capital "Z".

"Z" is kind of a unique case for DateTimes. The literal "Z" is actually part of the ISO 8601 datetime standard for UTC times. When "Z" (Zulu) is tacked on the end of a time, it indicates that that time is UTC, so really the literal Z is part of the time. This probably creates a few problems for the date format library in .NET, since it's actually a literal, rather than a format specifier.

Converting a Java Keystore into PEM Format

I found a very interesting solution:

Then, I divided the pair public/private key into two files private.key publi.pem and it works!

Plotting with C#

gnuplot is an actively maintained program widely used in the scientific community. Normally plots are generated from data files which you can write out in your C# program, but it is also possible to call the gnuplot executable from C# and display the generated image in a C# picture box.

What's the difference between ISO 8601 and RFC 3339 Date Formats?

RFC 3339 is mostly a profile of ISO 8601, but is actually inconsistent with it in borrowing the "-00:00" timezone specification from RFC 2822. This is described in the Wikipedia article.

How to use unicode characters in Windows command line?

This problem is quite annoying. I usually have Chinese character in my filename and file content. Please note that I am using Windows 10, here is my solution:

To display the file name, such as dir or ls if you installed Ubuntu bash on Windows 10

  1. Set the region to support non-utf 8 character.

  2. After that, console's font will be changed to the font of that locale, and it also changes the encoding of the console.

After you have done previous steps, in order to display the file content of a UTF-8 file using command line tool

  1. Change the page to utf-8 by chcp 65001
  2. Change to the font that supports utf-8, such as Lucida Console
  3. Use type command to peek the file content, or cat if you installed Ubuntu bash on Windows 10
  4. Please note that, after setting the encoding of the console to utf-8, I can't type Chinese character in the cmd using Chinese input method.

The laziest solution: Just use a console emulator such as

How do you display code snippets in MS Word preserving format and syntax highlighting?

Download and install Notepad++ and do the following:

  1. Paste your code in the window;

  2. Select the programming language from the language menu;

  3. Select the text to copy;

  4. Right click and select Plugin commands -> Copy Text with Syntax Highlighting;

  5. Paste it into MS Word and you are good to go!

Update 29/06/2013:

Notepad++ has a plugin called "NppExport" (comes pre-installed) that allows you to copy to RTF, HTML and ALL. It permits dozens of languages, whereas the aforementioned IDEs are limited to a handful each (without other plug-ins).

I use Copy all formats to clipboard and "paste as HTML" in MS word.

screenshot from notepad++

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

This is how I've always done it:

  <%# Boolean.Parse(Eval("Active").ToString()) ? "Yes" : "No" %>

Hope that helps.

Sql Server string to date conversion

SQL Server (2005, 2000, 7.0) does not have any flexible, or even non-flexible, way of taking an arbitrarily structured datetime in string format and converting it to the datetime data type.

By "arbitrarily", I mean "a form that the person who wrote it, though perhaps not you or I or someone on the other side of the planet, would consider to be intuitive and completely obvious." Frankly, I'm not sure there is any such algorithm.

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

By default, oracle date subtraction returns a result in # of days.

So just multiply by 24 to get # of hours, and again by 60 for # of minutes.


  round((second_date - first_date) * (60 * 24),2) as time_in_minutes
    to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
   ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
  ) test_data

Custom Date/Time formatting in SQL Server

You can use the following command in SQL server to make it:

select FORMAT(getdate(), N'yyyy-MM-ddThh:mm:ss')

Excel CSV - Number cell format

Well, excel never pops up the wizard for CSV files. If you rename it to .txt, you'll see the wizard when you do a File>Open in Excel the next time.

How do you perform address validation?

Yahoo has also a Placemaker API. It is good only for locations but it has an universal id for all world locations.

It look that there is no standard in ISO list.

How to validate phone numbers using regex

If at all possible, I would recommend to have four separate fields—Area Code, 3-digit prefix, 4 digit part, extension—so that the user can input each part of the address separately, and you can verify each piece individually. That way you can not only make verification much easier, you can store your phone numbers in a more consistent format in the database.

Given a DateTime object, how do I get an ISO 8601 date in string format?

If you're developing under SharePoint 2010 or higher you can use

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
string strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)

What datatype should be used for storing phone numbers in SQL Server 2005?

Use CHAR(10) if you are storing US Phone numbers only. Remove everything but the digits.

What is the argument for printf that formats a long?

I think to answer this question definitively would require knowing the compiler name and version that you are using and the platform (CPU type, OS etc.) that it is compiling for.

Inserting values into tables Oracle SQL

You can insert into a table from a SELECT.

  Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
  'John Doe',
  '1 River Walk, Green Street',
  (SELECT id FROM state WHERE name = 'New York'),
  (SELECT id FROM positions WHERE name = 'Sales Executive'),
  (SELECT id FROM manager WHERE name = 'Barry Green')

Or, similarly...

  Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
  'John Doe',
  '1 River Walk, Green Street',,,
WHERE     = 'New York'
  AND = 'Sales Executive'
  AND   = 'Barry Green'

Though this one does assume that all the look-ups exist. If, for example, there is no position name 'Sales Executive', nothing would get inserted with this version.

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

Node.js - get raw request body using Express

Use body-parser Parse the body with what it will be:





ie. If you are supposed to get raw text file, run .text().

Thats what body-parser currently supports

Convert Pandas Series to DateTime in a DataFrame

Some handy script:

hour = df['assess_time'].dt.hour.values[0]

Which is faster: multiple single INSERTs or one multiple-row INSERT?

multiple inserts are faster but it has thredshould. another thrik is disabling constrains checks temprorary make inserts much much faster. It dosn't matter your table has it or not. For example test disabling foreign keys and enjoy the speed:


offcourse you should turn it back on after inserts by:


this is common way to inserting huge data. the data integridity may break so you shoud care of that before disabling foreign key checks.

NullPointerException in Java with no StackTrace

You are probably using the HotSpot JVM (originally by Sun Microsystems, later bought by Oracle, part of the OpenJDK), which performs a lot of optimization. To get the stack traces back, you need to pass the option -XX:-OmitStackTraceInFastThrow to the JVM.

The optimization is that when an exception (typically a NullPointerException) occurs for the first time, the full stack trace is printed and the JVM remembers the stack trace (or maybe just the location of the code). When that exception occurs often enough, the stack trace is not printed anymore, both to achieve better performance and not to flood the log with identical stack traces.

To see how this is implemented in the HotSpot JVM, grab a copy of it and search for the global variable OmitStackTraceInFastThrow. Last time I looked at the code (in 2019), it was in the file graphKit.cpp.

Find a row in dataGridView based on column and value

Try this:

        string searchValue = textBox3.Text;
        int rowIndex = -1;

        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            foreach (DataGridViewRow row in dataGridView1.Rows)
                if (row.Cells["peseneli"].Value.ToString().Equals(searchValue))
                    rowIndex = row.Index;
                    dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex].Cells[0];
                    dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Selected = true;

        catch (Exception exc)

Git: Recover deleted (remote) branch

just two commands save my life

1. This will list down all previous HEADs

git reflog

2. This will revert the HEAD to commit that you deleted.

git reset --hard <your deleted commit>
ex. git reset --hard b4b2c02

What is JavaScript's highest integer value that a number can go to without losing precision?

At the moment of writing, JavaScript is receiving a new data type: BigInt. It is a TC39 proposal at stage 4 to be included in EcmaScript 2020. BigInt is available in Chrome 67+, FireFox 68+, Opera 54 and Node 10.4.0. It is underway in Safari, et al... It introduces numerical literals having an "n" suffix and allows for arbitrary precision:

var a = 123456789012345678901012345678901n;

Precision will still be lost, of course, when such a number is (maybe unintentionally) coerced to a number data type.

And, obviously, there will always be precision limitations due to finite memory, and a cost in terms of time in order to allocate the necessary memory and to perform arithmetic on such large numbers.

For instance, the generation of a number with a hundred thousand decimal digits, will take a noticeable delay before completion:

console.log(BigInt("1".padEnd(100000,"0")) + 1n)

...but it works.

C++ display stack trace on exception

I recommend project. It support Windows, Mac OS and also Linux

ls command: how can I get a recursive full-path listing, one line per file?

The realpath command prints the resolved path:

realpath *

To include dot files, pipe the output of ls -a to realpath:

ls -a | xargs realpath

To list subdirectories recursively:

ls -aR | xargs realpath

In case you have spaces in file names, man xargs recommends using the -o option to prevent file names from being processed incorrectly, this works best with the output of find -print0 and it starts to look a lot more complex than other answers:

find -print0 |xargs -0 realpath

See also Unix and Linux stackexchange question on how to list all files in a directory with absolute path.

How to get the last element of an array in Ruby?

Use -1 index (negative indices count backward from the end of the array):

a[-1] # => 5
b[-1] # => 6

or Array#last method:

a.last # => 5
b.last # => 6

How to pass the -D System properties while testing on Eclipse?

run configuration -> arguments -> vm arguments

(can also be placed in the debug configuration under Debug Configuration->Arguments->VM Arguments)

How to use SortedMap interface in Java?

You can use TreeMap which internally implements the SortedMap below is the example

Sorting by ascending ordering :

  Map<Float, String> ascsortedMAP = new TreeMap<Float, String>();

  ascsortedMAP.put(8f, "name8");
  ascsortedMAP.put(5f, "name5");
  ascsortedMAP.put(15f, "name15");
  ascsortedMAP.put(35f, "name35");
  ascsortedMAP.put(44f, "name44");
  ascsortedMAP.put(7f, "name7");
  ascsortedMAP.put(6f, "name6");

  for (Entry<Float, String> mapData : ascsortedMAP.entrySet()) {
    System.out.println("Key : " + mapData.getKey() + "Value : " + mapData.getValue());

Sorting by descending ordering :

If you always want this create the map to use descending order in general, if you only need it once create a TreeMap with descending order and put all the data from the original map in.

  // Create the map and provide the comparator as a argument
  Map<Float, String> dscsortedMAP = new TreeMap<Float, String>(new Comparator<Float>() {
    public int compare(Float o1, Float o2) {
      return o2.compareTo(o1);

for further information about SortedMAP read

Include another JSP file

What you're doing is a static include. A static include is resolved at compile time, and may thus not use a parameter value, which is only known at execution time.

What you need is a dynamic include:

<jsp:include page="..." />

Note that you should use the JSP EL rather than scriptlets. It also seems that you're implementing a central controller with index.jsp. You should use a servlet to do that instead, and dispatch to the appropriate JSP from this servlet. Or better, use an existing MVC framework like Stripes or Spring MVC.


Use a seperate column to indicate the join condition

SELECT  t.importid, 
            when t.importid = g.home 
            then 'home' 
            else 'away' 
        end as join_condition,, 
FROM    game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC 

How to create directory automatically on SD card

Make sure external storage is present:

private boolean isExternalStoragePresent() {

        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Something else is wrong. It may be one of many other states, but
            // all we need
            // to know is we can neither read nor write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) {
            Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG)

        return (mExternalStorageAvailable) && (mExternalStorageWriteable);

Changing width property of a :before css selector using JQuery

Pseudo-elements are not part of the DOM, so they can't be manipulated using jQuery or Javascript.

But as pointed out in the accepted answer, you can use the JS to append a style block which ends of styling the pseudo-elements.

Can overridden methods differ in return type?

Yes. It is possible for overridden methods to have different return type .

But the limitations are that the overridden method must have a return type that is more specific type of the return type of the actual method.

All the answers have given examples of the overridden method to have a return type which is a subclass of the return type of the actual method.

For example :

public class Foo{

   //method which returns Foo
  Foo getFoo(){
      //your code         


 public class subFoo extends Foo{

  //Overridden method which returns subclass of Foo
  subFoo getFoo(){
      //your code         


But this is not only limited to subclass.Even classes that implement an interface are a specific type of the interface and thus can be a return type where the interface is expected.

For example :

public interface Foo{

   //method which returns Foo
  Foo getFoo();


 public class Fizz implements Foo{

  //Overridden method which returns Fizz(as it implements Foo)
  Fizz getFoo(){
      //your code         


CSS customized scroll bar in div

This is what Google has used in some of its applications for a long time now. See in the code that, if you apply next classes, they somehow hide the scrollbar in Chrome, but it still works.

The classes are jfk-scrollbar, jfk-scrollbar-borderless, and jfk-scrollbar-dark

.testg{ border:1px solid black;  max-height:150px;  overflow-y: scroll; overflow-x: hidden; width: 250px;}_x000D_
.content{ height: 700px}_x000D_
/* The google css code for scrollbars */_x000D_
::-webkit-scrollbar {_x000D_
    height: 16px;_x000D_
    overflow: visible;_x000D_
    width: 16px_x000D_
::-webkit-scrollbar-button {_x000D_
    height: 0;_x000D_
    width: 0_x000D_
::-webkit-scrollbar-track {_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px_x000D_
::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 7px 0 0_x000D_
::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .1)_x000D_
::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .1)_x000D_
::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .2)_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .2)_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .25), inset -1px 0 0 rgba(255, 255, 255, .15)_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), inset 0 -1px 0 rgba(255, 255, 255, .15)_x000D_
::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(0, 0, 0, .2);_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px;_x000D_
    min-height: 28px;_x000D_
    padding: 100px 0 0;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 7px 0 0;_x000D_
    padding: 0 0 0 100px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(0, 0, 0, .4);_x000D_
    box-shadow: inset 1px 1px 1px rgba(0, 0, 0, .25)_x000D_
::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    box-shadow: inset 1px 1px 3px rgba(0, 0, 0, 0.35)_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(255, 255, 255, .3);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset 0 -1px 0 rgba(255, 255, 255, .1)_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb:horizontal {_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset -1px 0 0 rgba(255, 255, 255, .1)_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(255, 255, 255, .6);_x000D_
    box-shadow: inset 1px 1px 1px rgba(255, 255, 255, .37)_x000D_
.jfk-scrollbar-dark::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(255, 255, 255, .75);_x000D_
    box-shadow: inset 1px 1px 3px rgba(255, 255, 255, .5)_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-track {_x000D_
    border-width: 0 1px 0 6px_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .035);_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14), inset -1px -1px 0 rgba(0, 0, 0, .07)_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar-dark::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .07);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .25), inset -1px -1px 0 rgba(255, 255, 255, .15)_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-thumb {_x000D_
    border-width: 0 1px 0 6px_x000D_
.jfk-scrollbar-borderless::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
::-webkit-scrollbar-corner {_x000D_
    background: transparent_x000D_
body::-webkit-scrollbar-track-piece {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 0 0 0 3px;_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
body::-webkit-scrollbar-track-piece:horizontal {_x000D_
    border-width: 3px 0 0;_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
body::-webkit-scrollbar-thumb {_x000D_
    border-width: 1px 1px 1px 5px_x000D_
body::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 5px 1px 1px_x000D_
body::-webkit-scrollbar-corner {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 3px 0 0 3px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14)_x000D_
.jfk-scrollbar::-webkit-scrollbar {_x000D_
    height: 16px;_x000D_
    overflow: visible;_x000D_
    width: 16px_x000D_
.jfk-scrollbar::-webkit-scrollbar-button {_x000D_
    height: 0;_x000D_
    width: 0_x000D_
.jfk-scrollbar::-webkit-scrollbar-track {_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 7px 0 0_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .1)_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .1)_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(0, 0, 0, .05);_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
.jfk-scrollbar::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .2)_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:horizontal:hover {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .2)_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:active {_x000D_
    background-color: rgba(255, 255, 255, .1);_x000D_
    box-shadow: inset 1px 0 0 rgba(255, 255, 255, .25), inset -1px 0 0 rgba(255, 255, 255, .15)_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:horizontal:active {_x000D_
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), inset 0 -1px 0 rgba(255, 255, 255, .15)_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(0, 0, 0, .2);_x000D_
    background-clip: padding-box;_x000D_
    border: solid transparent;_x000D_
    border-width: 0 0 0 7px;_x000D_
    min-height: 28px;_x000D_
    padding: 100px 0 0;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 7px 0 0;_x000D_
    padding: 0 0 0 100px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(0, 0, 0, .4);_x000D_
    box-shadow: inset 1px 1px 1px rgba(0, 0, 0, .25)_x000D_
.jfk-scrollbar::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    box-shadow: inset 1px 1px 3px rgba(0, 0, 0, 0.35)_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    background-color: rgba(255, 255, 255, .3);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset 0 -1px 0 rgba(255, 255, 255, .1)_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .15), inset -1px 0 0 rgba(255, 255, 255, .1)_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb:hover {_x000D_
    background-color: rgba(255, 255, 255, .6);_x000D_
    box-shadow: inset 1px 1px 1px rgba(255, 255, 255, .37)_x000D_
.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-thumb:active {_x000D_
    background-color: rgba(255, 255, 255, .75);_x000D_
    box-shadow: inset 1px 1px 3px rgba(255, 255, 255, .5)_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-track {_x000D_
    border-width: 0 1px 0 6px_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-track:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(0, 0, 0, .035);_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14), inset -1px -1px 0 rgba(0, 0, 0, .07)_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar-dark.jfk-scrollbar::-webkit-scrollbar-track:hover {_x000D_
    background-color: rgba(255, 255, 255, .07);_x000D_
    box-shadow: inset 1px 1px 0 rgba(255, 255, 255, .25), inset -1px -1px 0 rgba(255, 255, 255, .15)_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    border-width: 0 1px 0 6px_x000D_
.jfk-scrollbar-borderless.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 6px 0 1px_x000D_
.jfk-scrollbar::-webkit-scrollbar-corner {_x000D_
    background: transparent_x000D_
body.jfk-scrollbar::-webkit-scrollbar-track-piece {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 0 0 0 3px;_x000D_
    box-shadow: inset 1px 0 0 rgba(0, 0, 0, .14), inset -1px 0 0 rgba(0, 0, 0, .07)_x000D_
body.jfk-scrollbar::-webkit-scrollbar-track-piece:horizontal {_x000D_
    border-width: 3px 0 0;_x000D_
    box-shadow: inset 0 1px 0 rgba(0, 0, 0, .14), inset 0 -1px 0 rgba(0, 0, 0, .07)_x000D_
body.jfk-scrollbar::-webkit-scrollbar-thumb {_x000D_
    border-width: 1px 1px 1px 5px_x000D_
body.jfk-scrollbar::-webkit-scrollbar-thumb:horizontal {_x000D_
    border-width: 5px 1px 1px_x000D_
body.jfk-scrollbar::-webkit-scrollbar-corner {_x000D_
    background-clip: padding-box;_x000D_
    background-color: #f5f5f5;_x000D_
    border: solid #fff;_x000D_
    border-width: 3px 0 0 3px;_x000D_
    box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .14)_x000D_
<div class="testg">_x000D_
    <div class="content">_x000D_
        Look Ma'  my scrollbars doesn't have arrows <br /><br />_x000D_
        content, content, content <br /> content, content, content <br /> content, content, content s<br />  content, content, content <br/> content, content, content <br/> content, content, content d<br/>  content, content, content <br/> _x000D_
<div class="testg jfk-scrollbar jfk-scrollbar-borderless jfk-scrollbar-dark">_x000D_
    <div class="content">_x000D_
        Look Ma'  my scrollbars dissapear in chrome<br /><br />_x000D_
        content, content, content <br /> content, content, content <br /> content, content, content s<br />  content, content, content <br/> content, content, content <br/> content, content, content d<br/>  content, content, content <br/> _x000D_

I just found it useful to remove the arrows from the scrollbars. As of 2015 it's been used in Google Maps when searching for places in the list of results in its material design UI.

npm throws error without sudo

All the above is not necessary.

The issue I was having was I was using the -g when I was running NPM. I couldn't work out how I wasn't getting a 'npm_module' folder created in my project.

The solution is to run 'NPM init' This creates a 'package.json' and the 'npm_module' folder where all subsequent modules will be loaded into. When running npm DO NOT use -g use -s to update your 'package.json' file.

Here is a good video explaining

How do you loop in a Windows batch file?

FOR will give you any information you'll ever need to know about FOR loops, including examples on proper usage.

Singletons vs. Application Context in Android?

From: Developer > reference - Application

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

How to use Bootstrap 4 in ASP.NET Core

Looking into this, it seems like the LibMan approach works best for my needs with adding Bootstrap. I like it because it is now built into Visual Studio 2017(15.8 or later) and has its own dialog boxes.

Update 6/11/2020: bootstrap 4.1.3 is now added by default with VS-2019.5 (Thanks to Harald S. Hanssen for noticing.)

The default method VS adds to projects uses Bower but it looks like it is on the way out. In the header of Microsofts bower page they write: Bower is maintained only.Recommend using LibManager

Following a couple links lead to Use LibMan with ASP.NET Core in Visual Studio where it shows how libs can be added using a built-in Dialog:

In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears: [source: Scott Addie 2018]

enter image description here

Then for bootstrap just (1) select the unpkg, (2) type in "bootstrap@.." (3) Install. After this, you would just want to verify all the includes in the _Layout.cshtml or other places are correct. They should be something like href="~/lib/bootstrap/dist/js/bootstrap...")

How to deploy a Java Web Application (.war) on tomcat?

Note that you can deploy remotely using HTTP.


Upload the web application archive (WAR) file that is specified as the request data in this HTTP PUT request, install it into the appBase directory of our corresponding virtual host, and start it using the war file name without the .war extension as the path. The application can later be undeployed (and the corresponding application directory removed) by use of the /undeploy. To deploy the ROOT web application (the application with a context path of "/"), name the war ROOT.war.

and if you're using Ant you can do this using Tomcat Ant tasks (perhaps following a successful build).

To determine which path you then hit on your browser, you need to know the port Tomcat is running on, the context and your servlet path. See here for more details.

SQL Server Pivot Table with multiple column aggregates

The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.

    select * from  mytransactions
    pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
    SUM(totalamount) AS totalamount,
    SUM(ISNULL(Australia, 0)) AS Australia,
    SUM(ISNULL(Austria, 0)) Austria
GROUP BY numericmonth, chardate

The ISNULL is to stop a NULL value from nullifying the sum (because NULL + any value = NULL)

This action could not be completed. Try Again (-22421)

Tested in Xcode 7.3, 04142016

Instead of clicking the blue Upload to App Store… button from the Organizer or while Archiving, Xcode offers a better tool to do this, but it is a little hidden and the process is not clear how to use it.

Here is what I documented while submitting our latest iOS application to the App Store:

First, do NOT use the blue Upload to App Store… button.

From Xcode's Xcode: Developer Tools: menu, select Application Loader.

Sign in with appropriate credentials that allow you to upload to the App Store.

When Application Loader shows you its main screen, select the Choose button on the lower right of the main window and open your IPA that you exported for the App Store.

Proceed with the submission.

Why you want to do this:

  1. Detailed app submission error reporting. Exact explanations of submission errors. It tells you what's incorrect in your app that you are trying to submit.
  2. You don't have to deal with the insipid error that prompted this question in the first place.
  3. It works consistently in my tests where Xcode's Submit App to Store… from the Archive menu does not.


It is not what is asked directly. But looking for how to do drop tables properly, I stumbled over this question, as I guess many others do too.

From SQL Server 2016+ you can use


For SQL Server <2016 what I do is the following for a permanent table

IF OBJECT_ID('dbo.Table', 'U') IS NOT NULL 
  DROP TABLE dbo.Table; 

Or this, for a temporary table

IF OBJECT_ID('tempdb.dbo.#T', 'U') IS NOT NULL

Difference between frontend, backend, and middleware in web development

There are in fact 3 questions in your question :

  • Define frontend, middle and back end
  • How and when do they overlap ?
  • Their associated usual bottlenecks.

What JB King has described is correct, but it is a particular, simple version, where in fact he mapped front, middle and bacn to an MVC layer. He mapped M to the back, V to the front, and C to the middle.

For many people, it is just fine, since they come from the ugly world where even MVC was not applied, and you could have direct DB calls in a view.

However in real, complex web applications, you indeed have two or three different layers, called front, middle and back. Each of them may have an associated database and a controller.

The front-end will be visible by the end-user. It should not be confused with the front-office, which is the UI for parameters and administration of the front. The front-end will usually be some kind of CMS or e-commerce Platform (Magento, etc.)

The middle-end is not compulsory and is where the business logics is. It will be based on a PIM, a MDM tool, or some kind of custom database where you enrich your produts or your articles (for CMS). It'll also be the place where you code business functions that need to be shared between differents frontends (for instance between the PC frontend and the API-based mobile application). Sometimes, an ESB or tool like ActiveMQ will be your middle-end

The back-end will be a 3rd layer, surrouding your source database or your ERP. It may be jsut the API wrting to and reading from your ERP. It may be your supplier DB, if you are doing e-commerce. In fact, it really depends on web projects, but it is always a central repository. It'll be accessed either through a DB call, through an API, or an Hibernate layer, or a full-featured back-end application

This description means that answering the other 2 questions is not possible in this thread, as bottlenecks really depend on what your 3 ends contain : what JB King wrote remains true for simple MVC architectures

at the time the question was asked (5 years ago), maybe the MVC pattern was not yet so widely adopted. Now, there is absolutely no reason why the MVC pattern would not be followed and a view would be tied to DB calls. If you read the question "Are there cases where they MUST overlap, and frontend/backend cannot be separated?" in a broader sense, with 3 different components, then there times when the 3 layers architecture is useless of course. Think of a simple personal blog, you'll not need to pull external data or poll RabbitMQ queues.

batch script - run command on each file in directory

I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.

set codedirectory=C:\Users\code
for /r  %codedirectory% %%i in (*.c) do 
( some GCC commands )

Why can't I inherit static classes?

What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces

How to specify multiple return types using type-hints

The statement def foo(client_id: str) -> list or bool: when evaluated is equivalent to def foo(client_id: str) -> list: and will therefore not do what you want.

The native way to describe a "either A or B" type hint is Union (thanks to Bhargav Rao):

def foo(client_id: str) -> Union[list, bool]:

I do not want to be the "Why do you want to do this anyway" guy, but maybe having 2 return types isn't what you want:

If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation. You can also indicate that None could be returned with Optional[list]

Smooth scrolling when clicking an anchor link

$("a").on("click", function(event){
    //check the value of this.hash
    if(this.hash !== ""){

        $("html, body").animate({scrollTop:$(this.hash).offset().top}, 500);

        //add hash to the current scroll position
        window.location.hash = this.hash;



How to convert List to Json in Java

download java-json.jar from Java2s then use the JSONArray constructor

List myList = new ArrayList<>();    
JSONArray jsonArray = new JSONArray(myList);

Removing elements from array Ruby

a = [1,1,1,2,2,3]
a.slice!(0) # remove first index
a.slice!(-1) # remove last index
# a = [1,1,2,2] as desired

Get file size, image width and height before upload


Not sure if it is what you want, but just simple example:

var input = document.getElementById('input');

input.addEventListener("change", function() {
    var file  = this.files[0];
    var img = new Image();

    img.onload = function() {
        var sizes = {
            height: this.height

        console.log('onload: sizes', sizes);
        console.log('onload: this', this);

    var objectURL = URL.createObjectURL(file);

    console.log('change: file', file);
    console.log('change: objectURL', objectURL);
    img.src = objectURL;

Form inline inside a form horizontal in twitter bootstrap?

I know this is an old answer but here is what I usually do:


.form-control-inline {
   width: auto;
   margin-right: 5px;

Then wrap the fields you want to be inlined in a div and add .form-control-inline to the input, example:


<label class="control-label">Date of birth:</label>
<select class="form-control form-control-inline" name="year"> ... </select>
<select class="form-control form-control-inline" name="month"> ... </select>
<select class="form-control form-control-inline" name="day"> ... </select>

Why is it that "No HTTP resource was found that matches the request URI" here?

WebApiConfig.Register(GlobalConfiguration.Configuration); should be on top.

Cannot find vcvarsall.bat when running a Python script


As pointed out by other, the problem is that python/cython etc. tries to find the same compiler they were built from, but this compiler does not exist on the computer. Most of the time, this compiler is a version of visual studio (2008, 2010 or 2013), but either such a compiler is not installed, or a newer version is installed and the system prevents from installing an older one. So, the solution is simple:

1) look at C:\Program Files (x86) and see if there is an installed version of Microsoft visual studio, and if it is newer than the version from which Python has been built. If not, install(/update to) the version from which Python has been built (see previous answers), or even a newest version and follow the next step.

2)If a newest version of Microsoft visual studio is already installed, we have to make Python/cython etc. believe that it is the version from which it has been built. And this is very simple: go to the the system environment variables and create the following variables, if they do not exist:





And set the field of these variables to

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools" (if visual studio 2008 is installed), or "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools" (if visual studio 2010 is installed) or "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools" (if visual studio 2013 is installed) or "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools" (if visual studio 2015 is installed).

This solution works for 32 bit versions of python. It may also work for 64 bit version but I've not tested; most probably, for 64 bit versions, the following additional steps must be performed:

3)add the path "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC" to the %PATH% environment variable (change the number of the version of visual studio according to you version).

4) from the command line, run "vcvarsall.bat x86_amd64"

That's all.

Warning: A non-numeric value encountered

in PHP if you use + for concatenation you will end up with this error. In php + is a arithmetic operator.

wrong use of + operator:

            "<label for='content'>Content:</label>"+
            "<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>"+$initcontent+"</textarea>'"+                 

use . for concatenation

$output = "<div class='from-group'>".
            "<label for='content'>Content:</label>".
            "<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>".$initcontent."</textarea>'".                 

How to determine the last Row used in VBA including blank spaces in between


if cells(i,1)="" then 
exit for

How to know a Pod's own IP address from inside a container in the Pod?

kubectl get pods -o wide

Give you a list of pods with name, status, ip, node...

How to add key,value pair to dictionary?

If you want to add a new record in the form

newRecord = [4L, 1L, u'DDD', 1689544L, datetime.datetime(2010, 9, 21, 21, 45), u'jhhjjh']

to messageName where messageName in the form X_somemessage can, but does not have to be in your dictionary, then do it this way:

myDict.setdefault(messageName, []).append(newRecord)

This way it will be appended to an existing messageName or a new list will be created for a new messageName.

maven "cannot find symbol" message unhelpful

if you are having dependency on some other project in work space and these projects are not build properly, such error might come. try building such dependent projects first, it may help

Adding an image to a project in Visual Studio

You need to turn on Show All Files option on solution pane toolbar and include this file manually.

iOS detect if user is on an iPad

UI_USER_INTERFACE_IDIOM() only returns iPad if the app is for iPad or Universal. If its an iPhone app running on an iPad then it won't. So you should instead check the model.

How to get the real path of Java application at runtime?

And what about using this.getClass().getProtectionDomain().getCodeSource().getLocation()?

How can I get the current user directory?

$env:USERPROFILE = "C:\\Documents and Settings\\[USER]\\"

How to run a PowerShell script without displaying a window?

When you scheduled task, just select "Run whether user is logged on or not" under the "General" tab.

Alternate way is to let the task run as another user.

SQL Case Sensitive String Compare

Just as another alternative you could use HASHBYTES, something like this:

FROM a_table 
WHERE HASHBYTES('sha1', attribute) = HASHBYTES('sha1', 'k')

How to update Git clone

If you want to fetch + merge, run

git pull

if you want simply to fetch :

git fetch

SQL Delete Records within a specific Range

My worry is if I say delete evertything with an ID (>79 AND < 296) then it may literally wipe the whole table...

That wont happen because you will have a where clause. What happens is that, if you have a statement like delete * from Table1 where id between 70 and 1296 , the first thing that sql query processor will do is to scan the table and look for those records in that range and then apply a delete.

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

Using = causes the variable to be assigned a value. If the variable already had a value, it is replaced. This value will be expanded when it is used. For example:

HELLO = world

# This echoes "world world!"

HELLO = hello

# This echoes "hello world!"

Using := is similar to using =. However, instead of the value being expanded when it is used, it is expanded during the assignment. For example:

HELLO = world
HELLO_WORLD := $(HELLO) world!

# This echoes "world world!"

HELLO = hello

# Still echoes "world world!"

HELLO_WORLD := $(HELLO) world!

# This echoes "hello world!"

Using ?= assigns the variable a value iff the variable was not previously assigned. If the variable was previously assigned a blank value (VAR=), it is still considered set I think. Otherwise, functions exactly like =.

Using += is like using =, but instead of replacing the value, the value is appended to the current one, with a space in between. If the variable was previously set with :=, it is expanded I think. The resulting value is expanded when it is used I think. For example:

HELLO_WORLD += world!

# This echoes "hello world!"

If something like HELLO_WORLD = $(HELLO_WORLD) world! were used, recursion would result, which would most likely end the execution of your Makefile. If A := $(A) $(B) were used, the result would not be the exact same as using += because B is expanded with := whereas += would not cause B to be expanded.

Why is MySQL InnoDB insert so slow?

I've needed to do testing of an insert-heavy application in both MyISAM and InnoDB simultaneously. There was a single setting that resolved the speed issues I was having. Try setting the following:

innodb_flush_log_at_trx_commit = 2

Make sure you understand the risks by reading about the setting here.

Also see and

Merge two array of objects based on a key

This solution is applicable even when you have different size of array being merged. Also, even if the keys on which match is happening has a different name.

const arr1 = [
  { id: "abdc4051", date: "2017-01-24" }, 
  { id: "abdc4052", date: "2017-01-22" },
  { id: "abdc4053", date: "2017-01-22" }
const arr2 = [
  { nameId: "abdc4051", name: "ab" },
  { nameId: "abdc4052", name: "abc" }

Now to merge these use a Map as follows:

const map = new Map();
arr1.forEach(item => map.set(, item));
arr2.forEach(item => map.set(item.nameId, {, ...item}));
const mergedArr = Array.from(map.values());

This should result in:

    "id": "abdc4051",
    "date": "2017-01-24",
    "nameId": "abdc4051",
    "name": "ab"
    "id": "abdc4052",
    "date": "2017-01-22",
    "nameId": "abdc4052",
    "name": "abc"
    "id": "abdc4053",
    "date": "2017-01-22"

ExecuteNonQuery: Connection property has not been initialized.

Opening and closing the connection takes a lot of time. And use the "using" as another member suggested. I changed your code slightly, but put the SQL creation and opening and closing OUTSIDE your loop. Which should speed up the execution a bit.

  static void Main()
            EventLog alog = new EventLog();
            alog.Log = "Application";
            alog.MachineName = ".";
            /*  ALSO: USE the USING Statement as another member suggested
            using (SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True")

                using (SqlCommand comm = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection1))
                    // add the code in here
                    // AND REMEMBER: connection1.Open();

            SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True");
            SqlDataAdapter cmd = new SqlDataAdapter();
            // Do it one line
            cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection1);
            // cmd.InsertCommand.Connection = connection1;

            foreach (EventLogEntry entry in alog.Entries)
                cmd.InsertCommand.Parameters.Add("@EventLog", SqlDbType.VarChar).Value = alog.Log;
                cmd.InsertCommand.Parameters.Add("@TimeGenerated", SqlDbType.DateTime).Value = entry.TimeGenerated;
                cmd.InsertCommand.Parameters.Add("@EventType", SqlDbType.VarChar).Value = entry.EntryType;
                cmd.InsertCommand.Parameters.Add("@SourceName", SqlDbType.VarChar).Value = entry.Source;
                cmd.InsertCommand.Parameters.Add("@ComputerName", SqlDbType.VarChar).Value = entry.MachineName;
                cmd.InsertCommand.Parameters.Add("@InstanceId", SqlDbType.VarChar).Value = entry.InstanceId;
                cmd.InsertCommand.Parameters.Add("@Message", SqlDbType.VarChar).Value = entry.Message;
                int rowsAffected = cmd.InsertCommand.ExecuteNonQuery();
            connection1.Close(); // AND CLOSE IT ONCE, AFTER THE LOOP

scp (secure copy) to ec2 instance without password

copy a file from a local server to a remote server

sudo scp -i my-pem-file.pem ./source/test.txt [email protected]:~/destination/

copy a file from a remote server to a local machine

sudo scp -i my-pem-file.pem [email protected]:~/source/of/remote/test.txt ./where/to/put

So the basically syntax is:-

scp -i my-pem-file.pem username@source:/location/to/file username@destination:/where/to/put

-i is for the identity_file

Convert a positive number to negative in C#

Converting a number from positive to negative, or negative to positive:

public static decimal Reverse(this decimal source)
     return source * decimal.MinusOne;

What does 'IISReset' do?

When you change an ASP.NET website's configuration file, it restarts the application to reflect the changes...

When you do an IIS reset, that restarts all applications running on that IIS instance.

How do I disable log messages from the Requests library?

Setting the logger name as requests or requests.urllib3 did not work for me. I had to specify the exact logger name to change the logging level.

First See which loggers you have defined, to see which ones you want to remove


And you will see something like this:

{...'urllib3.poolmanager': <logging.Logger object at 0x1070a6e10>, 'django.request': <logging.Logger object at 0x106d61290>, 'django.template': <logging.Logger object at 0x10630dcd0>, 'django.server': <logging.Logger object at 0x106dd6a50>, 'urllib3.connection': <logging.Logger object at 0x10710a350>,'urllib3.connectionpool': <logging.Logger object at 0x106e09690> ...}

Then configure the level for the exact logger:

   'loggers': {
    '': {
        'handlers': ['default'],
        'level': 'DEBUG',
        'propagate': True
    'urllib3.connectionpool': {
        'handlers': ['default'],
        'level': 'WARNING',
        'propagate' : False

How to read response headers in angularjs?

Additionally to Eugene Retunsky's answer, quoting from $http documentation regarding the response:

The response object has these properties:

  • data{string|Object} – The response body transformed with the transform functions.

  • status{number} – HTTP status code of the response.

  • headers{function([headerName])} – Header getter function.

  • config{Object} – The configuration object that was used to generate the request.

  • statusText{string} – HTTP status text of the response.

Please note that the argument callback order for $resource (v1.6) is not the same as above:

Success callback is called with (value (Object|Array), responseHeaders (Function), status (number), statusText (string)) arguments, where the value is the populated resource instance or collection object. The error callback is called with (httpResponse) argument.

Use sed to replace all backslashes with forward slashes

If your text is in a Bash variable, then Parameter Substitution ${var//\\//} can replace substrings:

$ p='C:\foo\bar.xml'
$ printf '%s\n' "$p"
$ printf '%s\n' "${p//\\//}"

This may be leaner and clearer that filtering through a command such as tr or sed.

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

AngularJS ng-click to go to another page (with Ionic framework)

Use <a> with href instead of a <button> solves my problem.

<ion-nav-buttons side="secondary">
  <a class="button icon-right ion-plus-round" href="#/app/gosomewhere"></a>

Nesting CSS classes

Not directly. But you can use extensions such as LESS to help you achieve the same.

How to control the line spacing in UILabel

From Interface Builder (Storyboard/XIB):

enter image description here


SWift 4

Using label extension

extension UILabel {

    // Pass value for any one of both parameters and see result
    func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {

        guard let labelText = self.text else { return }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.lineHeightMultiple = lineHeightMultiple

        let attributedString:NSMutableAttributedString
        if let labelattributedText = self.attributedText {
            attributedString = NSMutableAttributedString(attributedString: labelattributedText)
        } else {
            attributedString = NSMutableAttributedString(string: labelText)

        // Line spacing attribute
        attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))

        self.attributedText = attributedString

Now call extension function

let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"

// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) .  // try values 1.0 to 5.0

// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0

Or using label instance (Just copy & execute this code to see result)

let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40

// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))

// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))

label.attributedText = attrString

Swift 3

let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString

How to use greater than operator with date?

you have enlosed start_date with single quote causing it to become string, use backtick instead

SELECT * FROM `la_schedule` WHERE `start_date` > '2012-11-18';

Python list directory, subdirectory, and files

Here is a one-liner:

import os

[val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]
# Meta comment to ease selecting text

The outer most val for sublist in ... loop flattens the list to be one dimensional. The j loop collects a list of every file basename and joins it to the current path. Finally, the i loop iterates over all directories and sub directories.

This example uses the hard-coded path ./ in the os.walk(...) call, you can supplement any path string you like.

Note: os.path.expanduser and/or os.path.expandvars can be used for paths strings like ~/

Extending this example:

Its easy to add in file basename tests and directoryname tests.

For Example, testing for *.jpg files:

... for j in i[2] if j.endswith('.jpg')] ...

Additionally, excluding the .git directory:

... for i in os.walk('./') if '.git' not in i[0].split('/')]

What is the most efficient way to create HTML elements using jQuery?

If you have a lot of HTML content (more than just a single div), you might consider building the HTML into the page within a hidden container, then updating it and making it visible when needed. This way, a large portion of your markup can be pre-parsed by the browser and avoid getting bogged down by JavaScript when called. Hope this helps!

How should the ViewModel close the form?

Where you need to close the window, simply put this in the viewmodel:


  foreach (Window window in Application.Current.Windows)
            if (window.DataContext == this)

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->

return .Cell(i,1) <> Empty

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)


"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

orphan removal has the same effect as ON DELETE CASCADE in the following scenario:- Lets say we have a simple many to one relationship between student entity and a guide entity, where many students can be mapped to the same guide and in database we have a foreign key relation between Student and Guide table such that student table has id_guide as FK.

    @Table(name = "student", catalog = "helloworld")
    public class Student implements {
     @GeneratedValue(strategy = IDENTITY)
     @Column(name = "id")
     private Integer id;

    @JoinColumn(name = "id_guide")
    private Guide guide;

// The parent entity

    @Table(name = "guide", catalog = "helloworld")
    public class Guide implements {

private static final long serialVersionUID = 9017118664546491038L;

@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;

@Column(name = "name", length = 45)
private String name;

@Column(name = "salary", length = 45)
private String salary;

 @OneToMany(mappedBy = "guide", orphanRemoval=true) 
 private Set<Student> students = new  HashSet<Student>(0);

In this scenario, the relationship is such that student entity is the owner of the relationship and as such we need to save the student entity in order to persist the whole object graph e.g.

    Guide guide = new Guide("John", "$1500");
    Student s1 = new Student(guide, "Roy","ECE");
    Student s2 = new Student(guide, "Nick", "ECE");

Here we are mapping the same guide with two different student objects and since the CASCADE.PERSIST is used , the object graph will be saved as below in the database table(MySql in my case)

STUDENT table:-

ID Name Dept Id_Guide

1     Roy     ECE    1

2    Nick    ECE    1

GUIDE Table:-

ID NAME Salary

1    John     $1500

and Now if I want to remove one of the students, using

      Student student1 = em.find(Student.class,1);

and when a student record is removed the corresponding guide record should also be removed, that's where CASCADE.REMOVE attribute in the Student entity comes into picture and what it does is ;it removes the student with identifier 1 as well the corresponding guide object(identifier 1). But in this example, there is one more student object which is mapped to the same guide record and unless we use the orphanRemoval=true attribute in the Guide Entity , the remove code above will not work.

How do you cast a List of supertypes to a List of subtypes?

The best safe way is to implement an AbstractList and cast items in implementation. I created ListUtil helper class:

public class ListUtil
    public static <TCastTo, TCastFrom extends TCastTo> List<TCastTo> convert(final List<TCastFrom> list)
        return new AbstractList<TCastTo>() {
            public TCastTo get(int i)
                return list.get(i);

            public int size()
                return list.size();

    public static <TCastTo, TCastFrom> List<TCastTo> cast(final List<TCastFrom> list)
        return new AbstractList<TCastTo>() {
            public TCastTo get(int i)
                return (TCastTo)list.get(i);

            public int size()
                return list.size();

You can use cast method to blindly cast objects in list and convert method for safe casting. Example:

void test(List<TestA> listA, List<TestB> listB)
    List<TestB> castedB = ListUtil.cast(listA); // all items are blindly casted
    List<TestB> convertedB = ListUtil.<TestB, TestA>convert(listA); // wrong cause TestA does not extend TestB
    List<TestA> convertedA = ListUtil.<TestA, TestB>convert(listB); // OK all items are safely casted

How to add buttons at top of map fragment API v2 layout

extending de Almeida's answer I am editing code little bit here. since previous code was hiding gps location icon I did following way which worked better.

 <LinearLayout xmlns:android=""


    android:padding="4dp" >

        android:textColor="@drawable/textcolor_radiobutton" />
        android:background="#aaa" />

        android:textColor="@drawable/textcolor_radiobutton" />

        android:background="#aaa" />

        android:textColor="@drawable/textcolor_radiobutton" />
        android:background="#aaa" />

        android:textColor="@drawable/textcolor_radiobutton" />

    android:scrollbars="vertical" />

Select rows of a matrix that meet a condition

If the dataset is called data, then all the rows meeting a condition where value of column 'pm2.5' > 300 can be received by -

data[data['pm2.5'] >300,]

Can I use multiple versions of jQuery on the same page?

It is possible to load the second version of the jQuery use it and then restore to the original or keep the second version if there was no jQuery loaded before. Here is an example:

<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
    var jQueryTemp = jQuery.noConflict(true);
    var jQueryOriginal = jQuery || jQueryTemp;
    if (window.jQuery){
        console.log('Original jQuery: ', jQuery.fn.jquery);
        console.log('Second jQuery: ', jQueryTemp.fn.jquery);
    window.jQuery = window.$ = jQueryTemp;
<script type="text/javascript">
    console.log('Script using second: ', jQuery.fn.jquery);
<script type="text/javascript">
    // Restore original jQuery:
    window.jQuery = window.$ = jQueryOriginal;
    console.log('Script using original or the only version: ', jQuery.fn.jquery);

Laravel password validation rule

Sounds like a good job for regular expressions.

Laravel validation rules support regular expressions. Both 4.X and 5.X versions are supporting it :

This might help too:

ERROR: Sonar server 'http://localhost:9000' can not be reached

In file in conf folder I had hardcoaded ip of my machine where sobarqube was installed in property 235.22 I commented this and it started working for me.

How can I return pivot table output in MySQL?

This basically is a pivot table.

A nice tutorial on how to achieve this can be found here:

I advise reading this post and adapt this solution to your needs.


After the link above is currently not available any longer I feel obliged to provide some additional information for all of you searching for mysql pivot answers in here. It really had a vast amount of information, and I won't put everything from there in here (even more since I just don't want to copy their vast knowledge), but I'll give some advice on how to deal with pivot tables the sql way generally with the example from peku who asked the question in the first place.

Maybe the link comes back soon, I'll keep an eye out for it.

The spreadsheet way...

Many people just use a tool like MSExcel, OpenOffice or other spreadsheet-tools for this purpose. This is a valid solution, just copy the data over there and use the tools the GUI offer to solve this.

But... this wasn't the question, and it might even lead to some disadvantages, like how to get the data into the spreadsheet, problematic scaling and so on.

The SQL way...

Given his table looks something like this:

CREATE TABLE `test_pivot` (
  `pid` bigint(20) NOT NULL AUTO_INCREMENT,
  `company_name` varchar(32) DEFAULT NULL,
  `action` varchar(16) DEFAULT NULL,
  `pagecount` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`pid`)

Now look into his/her desired table:

company_name    EMAIL   PRINT 1 pages   PRINT 2 pages   PRINT 3 pages
CompanyA        0       0               1               3
CompanyB        1       1               2               0

The rows (EMAIL, PRINT x pages) resemble conditions. The main grouping is by company_name.

In order to set up the conditions this rather shouts for using the CASE-statement. In order to group by something, well, use ... GROUP BY.

The basic SQL providing this pivot can look something like this:

SELECT  P.`company_name`,
            WHEN P.`action`='EMAIL' 
            THEN 1 
            ELSE NULL 
    ) AS 'EMAIL',
            WHEN P.`action`='PRINT' AND P.`pagecount` = '1' 
            THEN P.`pagecount` 
            ELSE NULL 
    ) AS 'PRINT 1 pages',
            WHEN P.`action`='PRINT' AND P.`pagecount` = '2' 
            THEN P.`pagecount` 
            ELSE NULL 
    ) AS 'PRINT 2 pages',
            WHEN P.`action`='PRINT' AND P.`pagecount` = '3' 
            THEN P.`pagecount` 
            ELSE NULL 
    ) AS 'PRINT 3 pages'
FROM    test_pivot P
GROUP BY P.`company_name`;

This should provide the desired result very fast. The major downside for this approach, the more rows you want in your pivot table, the more conditions you need to define in your SQL statement.

This can be dealt with, too, therefore people tend to use prepared statements, routines, counters and such.

Some additional links about this topic:

Can I change the viewport meta tag in mobile safari on the fly?

in your <head>

<meta id="viewport"
      content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />

somewhere in your javascript

      "initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");

... but good luck with tweaking it for your device, fiddling for hours... and i'm still not there!


What is exactly the base pointer and stack pointer? To what do they point?

ESP is the current stack pointer, which will change any time a word or address is pushed or popped onto/off off the stack. EBP is a more convenient way for the compiler to keep track of a function's parameters and local variables than using the ESP directly.

Generally (and this may vary from compiler to compiler), all of the arguments to a function being called are pushed onto the stack by the calling function (usually in the reverse order that they're declared in the function prototype, but this varies). Then the function is called, which pushes the return address (EIP) onto the stack.

Upon entry to the function, the old EBP value is pushed onto the stack and EBP is set to the value of ESP. Then the ESP is decremented (because the stack grows downward in memory) to allocate space for the function's local variables and temporaries. From that point on, during the execution of the function, the arguments to the function are located on the stack at positive offsets from EBP (because they were pushed prior to the function call), and the local variables are located at negative offsets from EBP (because they were allocated on the stack after the function entry). That's why the EBP is called the Frame Pointer, because it points to the center of the function call frame.

Upon exit, all the function has to do is set ESP to the value of EBP (which deallocates the local variables from the stack, and exposes the entry EBP on the top of the stack), then pop the old EBP value from the stack, and then the function returns (popping the return address into EIP).

Upon returning back to the calling function, it can then increment ESP in order to remove the function arguments it pushed onto the stack just prior to calling the other function. At this point, the stack is back in the same state it was in prior to invoking the called function.

How to store token in Local or Session Storage in Angular 2?

As a general rule, the token should not be stored on the localStorage neither the sessionStorage. Both places are accessible from JS and the JS should not care about the authentication token.

IMHO The token should be stored on a cookie with the HttpOnly and Secure flag as suggested here:

Append TimeStamp to a File Name

For Current date and time as the name for a file on the file system. Now call the string.Format method, and combine it with DateTime.Now, for a method that outputs the correct string based on the date and time.

using System;
using System.IO;

class Program
    static void Main()
        // Write file containing the date with BIN extension
        string n = string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin",
        File.WriteAllText(n, "abc");

Output :



text- The first part of the output required Files will all start with text-

{0: Indicates that this is a string placeholder The zero indicates the index of the parameters inserted here

yyyy- Prints the year in four digits followed by a dash This has a "year 10000" problem

MM- Prints the month in two digits

dd_ Prints the day in two digits followed by an underscore

hh- Prints the hour in two digits

mm- Prints the minute, also in two digits

ss- As expected, it prints the seconds

tt Prints AM or PM depending on the time of day

How to position two divs horizontally within another div

Its quite a common misconception that you need a clear:both div at the bottom, when you really don't. While foxy's answer is correct, you don't need that non-semantic, useless clearing div. All you need to do is stick an overflow:hidden onto the container:

#sub-title { overflow:hidden; }

What is the easiest way to install BLAS and LAPACK for scipy?

For Debian Jessie and Stretch installing the following packages resolves the issue:

sudo apt install libblas3 liblapack3 liblapack-dev libblas-dev

Your next issue is very likely going to be a missing Fortran compiler, resolve this by installing it like this:

sudo apt install gfortran

If you want an optimized scipy, you can also install the optional libatlas-base-dev package:

sudo apt install libatlas-base-dev


If you have any issue with a missing Python.h file like this:

Python.h: No such file or directory

Then have a look at this post:

100% width background image with an 'auto' height

Tim S. was much closer to a "correct" answer then the currently accepted one. If you want to have a 100% width, variable height background image done with CSS, instead of using cover (which will allow the image to extend out from the sides) or contain (which does not allow the image to extend out at all), just set the CSS like so:

body {
    background-image: url(img.jpg);
    background-position: center top;
    background-size: 100% auto;

This will set your background image to 100% width and allow the height to overflow. Now you can use media queries to swap out that image instead of relying on JavaScript.

EDIT: I just realized (3 months later) that you probably don't want the image to overflow; you seem to want the container element to resize based on it's background-image (to preserve it's aspect ratio), which is not possible with CSS as far as I know.

Hopefully soon you'll be able to use the new srcset attribute on the img element. If you want to use img elements now, the currently accepted answer is probably best.

However, you can create a responsive background-image element with a constant aspect ratio using purely CSS. To do this, you set the height to 0 and set the padding-bottom to a percentage of the element's own width, like so:

.foo {
    height: 0;
    padding: 0; /* remove any pre-existing padding, just in case */
    padding-bottom: 75%; /* for a 4:3 aspect ratio */
    background-image: url(foo.png);
    background-position: center center;
    background-size: 100%;
    background-repeat: no-repeat;

In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value. This works because padding percentage is always calculated based on width, even if it's vertical padding.

How to retrieve element value of XML using Java?

You can make a class which extends org.xml.sax.helpers.DefaultHandler and call

start_<tag_name>(Attributes attrs);



For it is:



And then extends that class and implement xml configuration file parsers you want. Example:

  public void startElement(String uri, String name, String qname,
                           org.xml.sax.Attributes attrs) 
                  throws org.xml.sax.SAXException {
    Class[] args = new Class[2];
    args[0] = uri.getClass();
    args[1] = org.xml.sax.Attributes.class;
    try {
      String mname = name.replace("-", "");
      java.lang.reflect.Method m = 
            getClass().getDeclaredMethod("start" + mname, args);
      m.invoke(this, new Object[] { uri, (org.xml.sax.Attributes)attrs }); 
catch (IllegalAccessException e) { throw new RuntimeException(e); }
catch (NoSuchMethodException e) { throw new RuntimeException(e); }
catch (java.lang.reflect.InvocationTargetException e) { org.xml.sax.SAXException se = new org.xml.sax.SAXException(e.getTargetException()); se.setStackTrace(e.getTargetException().getStackTrace()); }

and in a particular configuration parser:

   public void start_Request(String uri, org.xml.sax.Attributes attrs) {
     // make sure to read attributes correctly
     System.err.println("Request, name="+ attrs.getValue(0);

How to install a specific version of a ruby gem?

As others have noted, in general use the -v flag for the gem install command.

If you're developing a gem locally, after cutting a gem from your gemspec:

$ gem install gemname-version.gem

Assuming version 0.8, it would look like this:

$ gem install gemname-0.8.gem

Peak-finding algorithm for Python/SciPy

To detect both positive and negative peaks, PeakDetect is helpful.

from peakdetect import peakdetect

peaks = peakdetect(data, lookahead=20) 
# Lookahead is the distance to look ahead from a peak to determine if it is the actual peak. 
# Change lookahead as necessary 
higherPeaks = np.array(peaks[0])
lowerPeaks = np.array(peaks[1])
plt.plot(higherPeaks[:,0], higherPeaks[:,1], 'ro')
plt.plot(lowerPeaks[:,0], lowerPeaks[:,1], 'ko')


How to check if an environment variable exists and get its value?

You could just use parameter expansion:


If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

So try this:


There's also the ${parameter-word} form, which substitutes the default value only when parameter is unset (but not when it's null).

To demonstrate the difference between the two:

$ unset DEPLOY_ENV
$ echo "'${DEPLOY_ENV:-default_value}' '${DEPLOY_ENV-default_value}'"
'default_value' 'default_value'
$ echo "'${DEPLOY_ENV:-default_value}' '${DEPLOY_ENV-default_value}'"
'default_value' ''

Better naming in Tuple classes than "Item1", "Item2"

I think I would create a class but another alternative is output parameters.

public void GetOrderRelatedIds(out int OrderGroupId, out int OrderTypeId, out int OrderSubTypeId, out int OrderRequirementId)

Since your Tuple only contains integers you could represent it with a Dictionary<string,int>

var orderIds = new Dictionary<string, int> {
    {"OrderGroupId", 1},
    {"OrderTypeId", 2},
    {"OrderSubTypeId", 3},
    {"OrderRequirementId", 4}.

but I don't recommend that either.

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";"POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

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

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";

There has been an error processing your request, Error log record number

A common solution is to upgrade magento setup by running this command

php bin/magento setup:upgrade && php bin/magento setup:di:compile

Otherwise just check var/report/{error number}

Datetime in where clause

WHERE datetime_column >= '20081220 00:00:00.000'
  AND datetime_column < '20081221 00:00:00.000'

What is the technology behind wechat, whatsapp and other messenger apps?

The WhatsApp Architecture Facebook Bought For $19 Billion explains the architecture involved in design of whatsapp.

Here is the general explanation from the link

  • WhatsApp server is almost completely implemented in Erlang.

  • Server systems that do the backend message routing are done in Erlang.

  • Great achievement is that the number of active users is managed with a really small server footprint. Team consensus is that it is largely because of Erlang.

  • Interesting to note Facebook Chat was written in Erlang in 2009, but they went away from it because it was hard to find qualified programmers.

  • WhatsApp server has started from ejabberd

  • Ejabberd is a famous open source Jabber server written in Erlang.

  • Originally chosen because its open, had great reviews by developers, ease of start and the promise of Erlang’s long term suitability for large communication system.

  • The next few years were spent re-writing and modifying quite a few parts of ejabberd, including switching from XMPP to internally developed protocol, restructuring the code base and redesigning some core components, and making lots of important modifications to Erlang VM to optimize server performance.

  • To handle 50 billion messages a day the focus is on making a reliable system that works. Monetization is something to look at later, it’s far far down the road.

  • A primary gauge of system health is message queue length. The message queue length of all the processes on a node is constantly monitored and an alert is sent out if they accumulate backlog beyond a preset threshold. If one or more processes falls behind that is alerted on, which gives a pointer to the next bottleneck to attack.

  • Multimedia messages are sent by uploading the image, audio or video to be sent to an HTTP server and then sending a link to the content along with its Base64 encoded thumbnail (if applicable).

  • Some code is usually pushed every day. Often, it’s multiple times a day, though in general peak traffic times are avoided. Erlang helps being aggressive in getting fixes and features into production. Hot-loading means updates can be pushed without restarts or traffic shifting. Mistakes can usually be undone very quickly, again by hot-loading. Systems tend to be much more loosely-coupled which makes it very easy to roll changes out incrementally.

  • What protocol is used in Whatsapp app? SSL socket to the WhatsApp server pools. All messages are queued on the server until the client reconnects to retrieve the messages. The successful retrieval of a message is sent back to the whatsapp server which forwards this status back to the original sender (which will see that as a "checkmark" icon next to the message). Messages are wiped from the server memory as soon as the client has accepted the message

  • How does the registration process work internally in Whatsapp? WhatsApp used to create a username/password based on the phone IMEI number. This was changed recently. WhatsApp now uses a general request from the app to send a unique 5 digit PIN. WhatsApp will then send a SMS to the indicated phone number (this means the WhatsApp client no longer needs to run on the same phone). Based on the pin number the app then request a unique key from WhatsApp. This key is used as "password" for all future calls. (this "permanent" key is stored on the device). This also means that registering a new device will invalidate the key on the old device.

How to select an element with 2 classes

Just chain them together:

.a.b {
  color: #666;

Implement a simple factory pattern with Spring 3 annotations

Based on solution by Pavel Cerný here we can make an universal typed implementation of this pattern. To to it, we need to introduce NamedService interface:

    public interface NamedService {
       String name();

and add abstract class:

public abstract class AbstractFactory<T extends NamedService> {

    private final Map<String, T> map;

    protected AbstractFactory(List<T> list) { = list
                .collect(Collectors.toMap(NamedService::name, Function.identity()));

     * Factory method for getting an appropriate implementation of a service
     * @param name name of service impl.
     * @return concrete service impl.

    public T getInstance(@NonNull final String name) {
        T t = map.get(name);
        if(t == null)
            throw new RuntimeException("Unknown service name: " + name);
        return t;

Then we create a concrete factory of specific objects like MyService:

 public interface MyService extends NamedService {
           String name();
           void doJob();

public class MyServiceFactory extends AbstractFactory<MyService> {

    protected MyServiceFactory(List<MyService> list) {

where List the list of implementations of MyService interface at compile time.

This approach works fine if you have multiple similar factories across app that produce objects by name (if producing objects by a name suffice you business logic of course). Here map works good with String as a key, and holds all the existing implementations of your services.

if you have different logic for producing objects, this additional logic can be moved to some another place and work in combination with these factories (that get objects by name).

Merging cells in Excel using Apache POI

i made a method that merge cells and put border.

protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
    CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
    if (border) {
        setBordersToMergedCells(sheet, cellMerge);


protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
    RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);

How to add a custom button to the toolbar that calls a JavaScript function?

In case anybody is interested, I wrote a solution for this using Prototype. In order to get the button to appear correctly, I had to specify extraPlugins: 'ajaxsave' from inside the CKEDITOR.replace() method call.

Here is the plugin.js:

    init: function(editor)
    var pluginName = 'ajaxsave';

    editor.addCommand( pluginName,
        exec : function( editor )
            new Ajax.Request('ajaxsave.php',
                method:     "POST",
                parameters: { filename: 'index.html', editor: editor.getData() },
                onFailure:  function() { ThrowError("Error: The server has returned an unknown error"); },
                on0:        function() { ThrowError('Error: The server is not responding. Please try again.'); },
                onSuccess:  function(transport) {

                    var resp = transport.responseText;

                    //Successful processing by ckprocess.php should return simply 'OK'. 
                    if(resp == "OK") {
                        //This is a custom function I wrote to display messages. Nicer than alert() 
                        ShowPageMessage('Changes have been saved successfully!');
                    } else {

        canUndo : true

        label: 'Save',
        command: pluginName,
        className : 'cke_button_save'

How to set variable from a SQL query?

There are three approaches:

  2. SET -- Microsoft Recommended approach

Below query details the advantage and disadvantage of each:

-- First way, 
DECLARE @test int = (SELECT 1)
       , @test2 int = (SELECT a from (values (1),(2)) t(a)) -- throws error

-- advantage: declare and set in the same place
-- Disadvantage: can be used only during declaration. cannot be used later

-- Second way
DECLARE @test int  
       , @test2 int 

SET @test = (select 1)
SET @test2 = (SELECT a from (values (1),(2)) t(a)) -- throws error

-- Advantage: ANSI standard. 
-- Disadvantage: cannot set more than one variable at a time

-- Third way
DECLARE @test int, @test2 int 
SELECT @test = (select 1)
      ,@test2 = (SELECT a from (values (1),(2)) t(a)) -- throws error

-- Advantage: Can set more than one variable at a time
-- Disadvantage: Not ANSI standard

Pass entire form as data in jQuery Ajax function

The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.

My solution:

<form id="form_1" action="result.php" method="post"
 onsubmit="sendForm(;return false">
    <input type="hidden" name="something" value="1">


function sendForm(form_id){
    var form = $('#'+form_id);
        type: 'POST',
        url: $(form).attr('action'),
        data: $(form).serialize(),
        success: function(result) {

How do I return multiple values from a function?

I prefer:

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

It seems everything else is just extra code to do the same thing.

Limiting Powershell Get-ChildItem by File Creation Date Range

Fixed it...

Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} | 
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt

Python Pandas Counting the Occurrences of a Specific value

Couple of ways using count or sum

In [338]: df
  col1 education
0    a       9th
1    b       9th
2    c       8th

In [335]: df.loc[ == '9th', 'education'].count()
Out[335]: 2

In [336]: ( == '9th').sum()
Out[336]: 2

In [337]: df.query('education == "9th"').education.count()
Out[337]: 2

Getting Hour and Minute in PHP

You can use the following solution to solve your problem:

echo date('H:i');

How to convert rdd object to dataframe in spark

I tried to explain the solution using the word count problem. 1. Read the file using sc

  1. Produce word count
  2. Methods to create DF

    • rdd.toDF method
    • rdd.toDF("word","count")
      • spark.createDataFrame(rdd,schema)

    Read file using spark

    val rdd=sc.textFile("D://cca175/data/")  

    Rdd to Dataframe

    val df=sc.textFile("D://cca175/data/").toDF("t1")

    Method 1

    Create word count RDD to Dataframe

    val df=rdd.flatMap(x=>x.split(" ")).map(x=>(x,1)).reduceByKey((x,y)=>(x+y)).toDF("word","count")


    Create Dataframe from Rdd

    val df=spark.createDataFrame(wordRdd) 
    # with header   
    val df=spark.createDataFrame(wordRdd).toDF("word","count")


    Define Schema

    import org.apache.spark.sql.types._

    val schema=new StructType(). add(StructField("word",StringType,true)). add(StructField("count",StringType,true))

    Create RowRDD

    import org.apache.spark.sql.Row

    Create DataFrame from RDD with schema

    val df=spark.createDataFrame(rowRdd,schema)

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

As biziclop mentioned, some sort of metric space tree would probably be your best option. I have experience using kd-trees and quad trees to do these sorts of range queries and they're amazingly fast; they're also not that hard to write. I'd suggest looking into one of these structures, as they also let you answer other interesting questions like "what's the closest point in my data set to this other point?"

Need to navigate to a folder in command prompt

I prefer to use

pushd d:\windows\movie

because it requires no switches yet the working directory will change to the correct drive and path in one step.

Added plus:

  • also works with UNC paths if an unused drive letter is available for automatic drive mapping,
  • easy to go back to the previous working directory: just enter popd.

What is duck typing?

Duck typing:

If it talks and walks like a duck, then it is a duck

This is typically called abduction (abductive reasoning or also called retroduction, a clearer definition I think):

  • from C (conclusion, what we see) and R (rule, what we know), we accept/decide/assume P (Premise, property) in other words a given fact

    ... the very basis of medical diagnosis

    with ducks: C = walks, talks, R = like a duck, P = it's a duck

Back to programming:

  • object o has method/property mp1 and interface/type T requires/defines mp1

  • object o has method/property mp2 and interface/type T requires/defines mp2

  • ...

So, more than simply accepting mp1... on any object as long has it meets some definition of mp1..., compiler/runtime should also be okay with the assertion o is of type T

And well, is it the case with examples above? Is Duck typing is essentially no typing at all? Or should we call it implicit typing?

Most simple code to populate JTable from ResultSet

This is my approach:

String[] columnNames = {"id", "Nome", "Sobrenome","Email"};

List<Student> students = _repo.getAll();

Object[][] data = new Object[students.size()][4];

int index = 0;
for(Student s : students) {
    data[index][0] = s.getId();
    data[index][1] = s.getFirstName();
    data[index][2] = s.getLastName();
    data[index][3] = s.getEmail();

DefaultTableModel model = new DefaultTableModel(data, columnNames);

table = new JTable(model);

Change app language programmatically in Android

Locale configuration should be set in each activity before setting the content - this.setContentView(R.layout.main);

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

I think that the usage of @Html.LabelForModel() should be explained in more detail.

The LabelForModel Method returns an HTML label element and the property name of the property that is represented by the model.

You could refer to the following code:

Code in model:

using System.ComponentModel;

public class MyModel
    [DisplayName("A property")]
    public string Test { get; set; }

Code in view:

<div class="form-group">

    @Html.LabelFor(model => model.Test, new { @class = "control-label col-md-2" })

    <div class="col-md-10">
        @Html.EditorFor(model => model.Test)
        @Html.ValidationMessageFor(model => model.Test)

The output screenshot:

enter image description here

Reference to answer on the forum

Proper use of the IDisposable interface

Your given code sample is not a good example for IDisposable usage. Dictionary clearing normally shouldn't go to the Dispose method. Dictionary items will be cleared and disposed when it goes out of scope. IDisposable implementation is required to free some memory/handlers that will not release/free even after they out of scope.

The following example shows a good example for IDisposable pattern with some code and comments.

public class DisposeExample
    // A base class that implements IDisposable. 
    // By implementing IDisposable, you are announcing that 
    // instances of this type allocate scarce resources. 
    public class MyResource: IDisposable
        // Pointer to an external unmanaged resource. 
        private IntPtr handle;
        // Other managed resource this class uses. 
        private Component component = new Component();
        // Track whether Dispose has been called. 
        private bool disposed = false;

        // The class constructor. 
        public MyResource(IntPtr handle)
            this.handle = handle;

        // Implement IDisposable. 
        // Do not make this method virtual. 
        // A derived class should not be able to override this method. 
        public void Dispose()
            // This object will be cleaned up by the Dispose method. 
            // Therefore, you should call GC.SupressFinalize to 
            // take this object off the finalization queue 
            // and prevent finalization code for this object 
            // from executing a second time.

        // Dispose(bool disposing) executes in two distinct scenarios. 
        // If disposing equals true, the method has been called directly 
        // or indirectly by a user's code. Managed and unmanaged resources 
        // can be disposed. 
        // If disposing equals false, the method has been called by the 
        // runtime from inside the finalizer and you should not reference 
        // other objects. Only unmanaged resources can be disposed. 
        protected virtual void Dispose(bool disposing)
            // Check to see if Dispose has already been called. 
                // If disposing equals true, dispose all managed 
                // and unmanaged resources. 
                    // Dispose managed resources.

                // Call the appropriate methods to clean up 
                // unmanaged resources here. 
                // If disposing is false, 
                // only the following code is executed.
                handle = IntPtr.Zero;

                // Note disposing has been done.
                disposed = true;


        // Use interop to call the method necessary 
        // to clean up the unmanaged resource.
        private extern static Boolean CloseHandle(IntPtr handle);

        // Use C# destructor syntax for finalization code. 
        // This destructor will run only if the Dispose method 
        // does not get called. 
        // It gives your base class the opportunity to finalize. 
        // Do not provide destructors in types derived from this class.
            // Do not re-create Dispose clean-up code here. 
            // Calling Dispose(false) is optimal in terms of 
            // readability and maintainability.
    public static void Main()
        // Insert code here to create 
        // and use the MyResource object.

How can I create an editable combo box in HTML/Javascript?

try doing this

<div style="position: absolute;top: 32px; left: 430px;" id="outerFilterDiv">
<input name="filterTextField" type="text" id="filterTextField" tabindex="2"  style="width: 140px;
    position: absolute; top: 1px; left: 1px; z-index: 2;border:none;" />
        <div style="position: absolute;" id="filterDropdownDiv">
<select name="filterDropDown" id="filterDropDown" tabindex="1000"
    onchange="DropDownTextToBox(this,'filterTextField');" style="position: absolute;
    top: 0px; left: 0px; z-index: 1; width: 165px;">
    <option value="-1" selected="selected" disabled="disabled">-- Select Column Name --</option>

please look at following example fiddle

How to force a line break on a Javascript concatenated string?

You can't have multiple lines in a text box, you need a textarea. Then it works with \n between the values.

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

Change background color of R plot

Old question but I have a much better way of doing this. Rather than using rect() use polygon. This allows you to keep everything in plot without using points. Also you don't have to mess with par at all. If you want to keep things automated make the coordinates of polygon a function of your data.
polygon(c(-min(df[,1])^2,-min(df[,1])^2,max(df[,1])^2,max(df[,1])^2),c(-min(df[,2])^2,max(df[,2])^2,max(df[,2])^2,-min(df[,2])^2), col="grey")

Nested lists python

If you really need the indices you can just do what you said again for the inner list:

l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
    for index2 in xrange(len(l[index1])):
        print index1, index2, l[index1][index2]

But it is more pythonic to iterate through the list itself:

for inner_l in l:
    for item in inner_l:
        print item

If you really need the indices you can also use enumerate:

for index1, inner_l in enumerate(l):
    for index2, item in enumerate(inner_l):
        print index1, index2, item, l[index1][index2]

Selecting rows where remainder (modulo) is 1 after division by 2?

select * from table where value % 2 = 1 works fine in mysql.

Remove all git files from a directory?

How to remove all .git directories under a folder in Linux.

Run this find command, it will list all .git directories under the current folder:

find . -type d -name ".git" \
&& find . -name ".gitignore" \
&& find . -name ".gitmodules"



There should only be like 3 or 4 .git directories because git only has one .git folder for every project. You can rm -rf yourpath each of the above by hand.

If you feel like removing them all in one command and living dangerously:

//Retrieve all the files named ".git" and pump them into 'rm -rf'
//WARNING if you don't understand why/how this command works, DO NOT run it!

( find . -type d -name ".git" \
  && find . -name ".gitignore" \
  && find . -name ".gitmodules" ) | xargs rm -rf

//WARNING, if you accidentally pipe a `.` or `/` or other wildcard
//into xargs rm -rf, then the next question you will have is: "why is
//the bash ls command not found?  Requiring an OS reinstall.

How to write a confusion matrix in Python?

Only with numpy, we can do as follow considering efficiency:

def confusion_matrix(pred, label, nc=None):
    assert pred.size == label.size
    if nc is None:
        nc = len(unique(label))
        logging.debug("Number of classes assumed to be {}".format(nc))

    confusion = np.zeros([nc, nc])
    # avoid the confusion with `0`
    tran_pred = pred + 1
    for i in xrange(nc):    # current class
        mask = (label == i)
        masked_pred = mask * tran_pred
        cls, counts = unique(masked_pred, return_counts=True)
        # discard the first item
        cls = [cl - 1 for cl in cls][1:]
        counts = counts[1:]
        for cl, count in zip(cls, counts):
            confusion[i, cl] = count
    return confusion

For other features such as plot, mean-IoU, see my repositories.

Is there a way to get a list of column names in sqlite?

As far as I can tell Sqlite doesn't support INFORMATION_SCHEMA. Instead it has sqlite_master.

I don't think you can get the list you want in just one command. You can get the information you need using sql or pragma, then use regex to split it into the format you need

SELECT sql FROM sqlite_master WHERE name='tablename';

gives you something like

CREATE TABLE tablename(
        col2 NVARCHAR(100) NOT NULL,
        col3 NVARCHAR(100) NOT NULL,

Or using pragma

PRAGMA table_info(tablename);

gives you something like


Is "else if" faster than "switch() case"?

Believing this performance evaluation, the switch case is faster.

This is the conclusion:

The results show that the switch statement is faster to execute than the if-else-if ladder. This is due to the compiler's ability to optimise the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer. However, because each case within a switch statement does not rely on earlier cases, the compiler is able to re-order the testing in such a way as to provide the fastest execution.

All libraries must use the exact same version specification

After searching and combining answers, 2018 version of this question and it worked for me:

1) On navigation tab change it to project view

2) Navigate to [YourProjectName]/.idea/libraries/

3) Delete all files starting with Gradle__com_android_support_[libraryName]

E.g: Gradle__com_android_support_animated_vector_drawable_26_0_0.xml

4) In your gradle file define a variable and use it to replace version number like ${variableName}

Def variable:

ext {
    support_library_version = '28.0.0' //use the version of choice

Use variable:

implementation "${support_library_version}"

example gradle:

dependencies {
    ext {
        support_library_version = '28.0.0' //use the version of choice

    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"
    implementation "${support_library_version}"


Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

How To Convert A Number To an ASCII Character?

To get ascii to a number, you would just cast your char value into an integer.

char ascii = 'a'
int value = (int)ascii

Variable value will now have 97 which corresponds to the value of that ascii character

(Use this link for reference)

twitter bootstrap 3.0 typeahead ajax example

With bootstrap3-typeahead, I made it to work with the following code:

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
jQuery(document).ready(function() {
        source: function (query, process) {
            return $.get('search?q=' + query, function (data) {
                return process(data.search_results);

The backend provides search service under the search GET endpoint, receiving the query in the q parameter, and returns a JSON in the format { 'search_results': ['resultA', 'resultB', ... ] }. The elements of the search_resultsarray are displayed in the typeahead input.

How to distinguish between left and right mouse click with jQuery

$.fn.rightclick = function(func){
        if(event.button == 2) {
            var oncontextmenu = document.oncontextmenu;
            document.oncontextmenu = function(){return false;};
            setTimeout(function(){document.oncontextmenu = oncontextmenu;},300);
            return false;


Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
    static void Main(string[] args)
        BaseClient clientbase = new BaseClient("", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;

    public async Task<BaseResponse> GetCallAsync(string endpoint)
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            return baseresponse;
        catch (Exception ex)
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        return baseresponse;

public class BaseResponse
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }

public class BaseClient
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
        HttpClientHandler handler = new HttpClientHandler()
            Proxy = new WebProxy(""),
            UseProxy = false,

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();


builder for HashMap

There's ImmutableMap.builder() in Guava.

CSS - center two images in css side by side

You can't have two elements with the same ID.

Aside from that, you are defining them as block elemnts, meaning (in layman's terms) that they are being forced to appear on their own line.

Instead, try something like this:

<div class="link"><a href="..."><img src="..."... /></a></div>
<div class="link"><a href="..."><img src="..."... /></a></div>


.link {
    width: 50%;
    float: left;
    text-align: center;

'NoneType' object is not subscriptable?

The print() function returns None. You are trying to index None. You can not, because 'NoneType' object is not subscriptable.

Put the [0] inside the brackets. Now you're printing everything, and not just the first term.

How can I remove the top and right axis in matplotlib?

(This is more of an extension comment, in addition to the comprehensive answers here.)

Note that we can hide each of these three elements independently of each other:

  • To hide the border (aka "spine"): ax.set_frame_on(False) or ax.spines['top'].set_visible(False)

  • To hide the ticks: ax.tick_params(top=False)

  • To hide the labels: ax.tick_params(labeltop=False)

How to Calculate Execution Time of a Code Snippet in C++

In some programs I wrote I used RDTS for such purpose. RDTSC is not about time but about number of cycles from processor start. You have to calibrate it on your system to get a result in second, but it's really handy when you want to evaluate performance, it's even better to use number of cycles directly without trying to change them back to seconds.

(link above is to a french wikipedia page, but it has C++ code samples, english version is here)

Cancel split window in Vim

To close all splits, I usually place the cursor in the window that shall be the on-ly visible one and then do :on which makes the current window the on-ly visible window. Nice mnemonic to remember.

Edit: :help :on showed me that these commands are the same:

  • :on
  • :only
  • CTRL-w CTRL-o
  • And yes, also CTRL-W o has the same effect (as Nathan answered).

Each of these four closes all windows except the active one.

C dynamically growing array

I can use pointers, but I am a bit afraid of using them.

If you need a dynamic array, you can't escape pointers. Why are you afraid though? They won't bite (as long as you're careful, that is). There's no built-in dynamic array in C, you'll just have to write one yourself. In C++, you can use the built-in std::vector class. C# and just about every other high-level language also have some similar class that manages dynamic arrays for you.

If you do plan to write your own, here's something to get you started: most dynamic array implementations work by starting off with an array of some (small) default size, then whenever you run out of space when adding a new element, double the size of the array. As you can see in the example below, it's not very difficult at all: (I've omitted safety checks for brevity)

typedef struct {
  int *array;
  size_t used;
  size_t size;
} Array;

void initArray(Array *a, size_t initialSize) {
  a->array = malloc(initialSize * sizeof(int));
  a->used = 0;
  a->size = initialSize;

void insertArray(Array *a, int element) {
  // a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
  // Therefore a->used can go up to a->size 
  if (a->used == a->size) {
    a->size *= 2;
    a->array = realloc(a->array, a->size * sizeof(int));
  a->array[a->used++] = element;

void freeArray(Array *a) {
  a->array = NULL;
  a->used = a->size = 0;

Using it is just as simple:

Array a;
int i;

initArray(&a, 5);  // initially 5 elements
for (i = 0; i < 100; i++)
  insertArray(&a, i);  // automatically resizes as necessary
printf("%d\n", a.array[9]);  // print 10th element
printf("%d\n", a.used);  // print number of elements

How to go to a specific element on page?

The standard technique in plugin form would look something like this:

(function($) {
    $.fn.goTo = function() {
        $('html, body').animate({
            scrollTop: $(this).offset().top + 'px'
        }, 'fast');
        return this; // for chaining...

Then you could just say $('#div_element2').goTo(); to scroll to <div id="div_element2">. Options handling and configurability is left as an exercise for the reader.

cannot import name patterns

Pattern module in not available from django 1.8. So you need to remove pattern from your import and do something similar to the following:

from django.conf.urls import include, url
from django.contrib import admin


urlpatterns = [                 
    # here we are not using pattern module like in previous django versions
    url(r'^admin/', include(,

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field of type string

Trying to get Laravel 5 email to work

You should restart the server and run this commands:

php artisan cache:clear
php artisan view:clear
php artisan route:clear
php artisan config:clear
php artisan config:cache

That should work.

Why is using "" for array iteration a bad idea?

The for/in works with two types of variables: hashtables (associative arrays) and array (non-associative).

JavaScript will automatically determine the way its passes through the items. So if you know that your array is really non-associative you can use for (var i=0; i<=arrayLen; i++), and skip the auto-detection iteration.

But in my opinion, it's better to use for/in, the process required for that auto-detection is very small.

A real answer for this will depend on how the browser parsers/interpret the JavaScript code. It can change between browsers.

I can't think of other purposes to not using for/in;

var arr = ['a', 'b', 'c'];
for (var i in arr)

var arr = {
   item1 : 'a',
   item2 : 'b',
   item3 : 'c'

for (var i in arr)

jQuery ajax post file field

This should help. How can I upload files asynchronously?

As the post suggest I recommend a plugin located here

Manually Set Value for FormBuilder Control

You could try this:

deptSelected(selected: { id: string; text: string }) {
  console.log(selected) // Shows proper selection!

  // This is how I am trying to set the value

For more details, you could have a look at the corresponding JS Doc regarding the second parameter of the updateValue method:

How to link external javascript file onclick of button

You can load all your scripts in the head tag, and whatever your script is doing in function braces. But make sure you change the scope of the variables if you are using those variables outside the script.

Create a unique number with javascript time

A better approach would be:

new Date().valueOf();

instead of

new Date().getUTCMilliseconds();

valueOf() is "most likely" a unique number.

Update multiple values in a single statement

Have you tried with a sub-query for every field:

    TotalX = (SELECT SUM(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalY = (SELECT SUM(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalZ = (SELECT SUM(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)

Setting focus on an HTML input box on page load

This is one of the common issues with IE and fix for this is simple. Add .focus() twice to the input.

Fix :-

function FocusOnInput() {
    var element = document.getElementById('txtContactMobileNo');
    setTimeout(function () { element.focus(); }, 1);

And call FocusOnInput() on $(document).ready(function () {.....};

When to use LinkedList over ArrayList in Java?

An important feature of a linked list (which I didn't read in another answer) is the concatenation of two lists. With an array this is O(n) (+ overhead of some reallocations) with a linked list this is only O(1) or O(2) ;-)

Important: For Java its LinkedList this is not true! See Is there a fast concat method for linked list in Java?

GSON - Date format

You can specify you format Gson gson = builder.setDateFormat("yyyy-MM-dd").create(); in this method instead of yyyy-MM-dd you can use anyother formats

 GsonBuilder builder = new GsonBuilder();
                        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                                return new Date(json.getAsJsonPrimitive().getAsLong());

                        Gson gson = builder.setDateFormat("yyyy-MM-dd").create();

image.onload event and browser cache

There are two possible solutions for these kind of situations:

  1. Use the solution suggested on this post
  2. Add a unique suffix to the image src to force browser downloading it again, like this:

    var img = new Image();
    img.src = "img.jpg?_="+(new Date().getTime());
    img.onload = function () {
        alert("image is loaded");

In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again

What is the use of GO in SQL Server Management Studio & Transact SQL?

Since Management Studio 2005 it seems that you can use GO with an int parameter, like:

GO 10

The above will insert 10 rows into mytable. Generally speaking, GO will execute the related sql commands n times.

How to set DataGrid's row Background, based on a property value using data bindings

The same can be done without DataTrigger too:

     <Style TargetType="DataGridRow">
         <Setter Property="Background" >
                 <Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
                         <x:Array Type="SolidColorBrush">
                             <SolidColorBrush Color="{StaticResource RedColor}"/>
                             <SolidColorBrush Color="{StaticResource TransparentColor}"/>

Where BooleanToBrushConverter is the following class:

public class BooleanToBrushConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        if (value == null)
            return Brushes.Transparent;

        Brush[] brushes = parameter as Brush[];
        if (brushes == null)
            return Brushes.Transparent;

        bool isTrue;
        bool.TryParse(value.ToString(), out isTrue);

        if (isTrue)
            var brush =  (SolidColorBrush)brushes[0];
            return brush ?? Brushes.Transparent;
            var brush = (SolidColorBrush)brushes[1];
            return brush ?? Brushes.Transparent;

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        throw new NotImplementedException();

python NameError: name 'file' is not defined

file() is not supported in Python 3

Use open() instead; see Built-in Functions - open().

Add CSS class to a div in code behind

Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.

public static void RemoveCssClass(this WebControl control, String css) {
  control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());

public static void AddCssClass(this WebControl control, String css) {
  css += " " + control.CssClass;
  control.CssClass = css;

Usage: hlCreateNew.AddCssClass("disabled");

Usage: hlCreateNew.RemoveCssClass("disabled");


remove partition by and add group by clause,

      ,SUM(ICount) totalSum
  FROM Table 
WHERE DateId  = 20130618

urlencoded Forward slash is breaking URL

Apache denies all URLs with %2F in the path part, for security reasons: scripts can't normally (ie. without rewriting) tell the difference between %2F and / due to the PATH_INFO environment variable being automatically URL-decoded (which is stupid, but a long-standing part of the CGI specification so there's nothing can be done about it).

You can turn this feature off using the AllowEncodedSlashes directive, but note that other web servers will still disallow it (with no option to turn that off), and that other characters may also be taboo (eg. %5C), and that %00 in particular will always be blocked by both Apache and IIS. So if your application relied on being able to have %2F or other characters in a path part you'd be limiting your compatibility/deployment options.

I am using urlencode() while preparing the search URL

You should use rawurlencode(), not urlencode() for escaping path parts. urlencode() is misnamed, it is actually for application/x-www-form-urlencoded data such as in the query string or the body of a POST request, and not for other parts of the URL.

The difference is that + doesn't mean space in path parts. rawurlencode() will correctly produce %20 instead, which will work both in form-encoded data and other parts of the URL.

Node.js: get path from the request

Combining solutions above when using express request:

let url=url.parse(req.originalUrl);
let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';

this will handle all cases like


etc. Some examples:

> urls
[ 'http://localhost/page',
  'http://localhost:3000' ]
> => url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '' )
[ 'page', 'page', 'page', '', '', '', 'page', 'page', '', '' ]

Get a particular cell value from HTML table using JavaScript

I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .

row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;

Here #table_body is the id of the table body tag .

What's the difference between '$(this)' and 'this'?

Yeah, by using $(this), you enabled jQuery functionality for the object. By just using this, it only has generic Javascript functionality.

How to change xampp localhost to another folder ( outside xampp folder)?

Edit the httpd.conf file and replace the line DocumentRoot "/home/user/www" to your liked one.

The default DocumentRoot path will be different for windows [the above is for linux].

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

My solution was to insert <packaging>pom</packaging> between artifactId and version


"Object doesn't support property or method 'find'" in IE

Here is a work around. You can use filter instead of find; but filter returns an array of matching objects. find only returns the first match inside an array. So, why not use filter as following;

data.filter(function (x) {
         return x.Id === e

Negative regex for Perl string pattern match

If my understanding is correct then you want to match any line which has Clinton and Reagan, in any order, but not Bush. As suggested by Stuck, here is a version with lookahead assertions:


use strict;
use warnings;

my $regex = qr/

while (<DATA>) {
    next unless (/$regex/);
    print $_, "\n";

shouldn't match - reagan came first, then clinton, finally bush
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
shouldn't match - last two: clinton and bush
shouldn't match - reverse: bush and clinton
shouldn't match - and then came obama, along comes mary
shouldn't match - to clinton with perl


first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan

as desired it matches any line which has Reagan and Clinton in any order.

You may want to try reading how lookahead assertions work with examples at

they are very tasty :)

How to make a HTTP PUT request?

protected void UpdateButton_Click(object sender, EventArgs e)
            var values = string.Format("Name={0}&Family={1}&Id={2}", NameToUpdateTextBox.Text, FamilyToUpdateTextBox.Text, IdToUpdateTextBox.Text);
            var bytes = Encoding.ASCII.GetBytes(values);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://localhost:51436/api/employees"));
            request.Method = "PUT";
            request.ContentType = "application/x-www-form-urlencoded";
            using (var requestStream = request.GetRequestStream())
                requestStream.Write(bytes, 0, bytes.Length);
            var response =  (HttpWebResponse) request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
                UpdateResponseLabel.Text = "Update completed";
                UpdateResponseLabel.Text = "Error in update";

How to get the first column of a pandas DataFrame as a Series?

This works great when you want to load a series from a csv file

x = pd.read_csv('x.csv', index_col=False, names=['x'],header=None).iloc[:,0]

<class 'pandas.core.series.Series'>
0    110.96
1    119.40
2    135.89
3    152.32
4    192.91
5    177.20
6    181.16
7    177.30
8    200.13
9    235.41
Name: x, dtype: float64

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Why calling react setState method doesn't mutate the state immediately?

You could try using ES7 async/await. For instance using your example:

handleChange: async function(event) {
    await this.setState({value:});

Is there a pretty print for PHP?

The best I found yet is this:

echo "<pre>";
echo "</pre>";

And if you want it more detailed:

echo "<pre>";
echo "</pre>";

Adding a <pre> HTML tag in a web development environment will respect the newlines \n of the print function correctly, without having to add some html <br>

How to get item's position in a list?

I think that it might be useful to use the curselection() method from thte Tkinter library:

from Tkinter import * 

This method works on Tkinter listbox widgets, so you'll need to construct one of them instead of a list.

This will return a position like this:

('0',) (although later versions of Tkinter may return a list of ints instead)

Which is for the first position and the number will change according to the item position.

For more information, see this page:


How to paste yanked text into the Vim command line


If you are using Vim in Mac OS X, unfortunately it comes with older version, and not complied with clipboard options. Luckily, Homebrew can easily solve this problem.

Install Vim:

brew install vim --with-lua --with-override-system-vi

Install the GUI version of Vim:

brew install macvim --with-lua --with-override-system-vi

Restart the terminal for it to take effect.

Append the following line to ~/.vimrc
set clipboard=unnamed

Now you can copy the line in Vim with yy and paste it system-wide.

What is the purpose of mvnw and mvnw.cmd files?

The Maven Wrapper is an excellent choice for projects that need a specific version of Maven (or for users that don't want to install Maven at all). Instead of installing many versions of it in the operating system, we can just use the project-specific wrapper script.

mvnw: it's an executable Unix shell script used in place of a fully installed Maven

mvnw.cmd: it's for Windows environment

Use Cases

The wrapper should work with different operating systems such as:

  • Linux
  • OSX
  • Windows
  • Solaris

After that, we can run our goals like this for the Unix system:

./mvnw clean install

And the following command for Batch:

./mvnw.cmd clean install

If we don't have the specified Maven in the wrapper properties, it'll be downloaded and installed in the folder $USER_HOME/.m2/wrapper/dists of the system.

Maven Wrapper plugin

Maven Wrapper plugin to make auto installation in a simple Spring Boot project.

First, we need to go in the main folder of the project and run this command:

mvn -N io.takari:maven:wrapper

We can also specify the version of Maven:

mvn -N io.takari:maven:wrapper -Dmaven=3.5.2

The option -N means –non-recursive so that the wrapper will only be applied to the main project of the current directory, not in any submodules.

Source 1 (further reading):

Get class list for element with jQuery

You should try this one:


It returns an array of all current classes of the element.

MATLAB error: Undefined function or method X for input arguments of type 'double'

I am pretty sure that the reason why this problem happened is because of the license of the toolbox (package) in which this function belongs in. Write which divrat and see what will be the result. If it returns path of the function and the comment Has no license available, then the problem is related to the license. That means, license of the package is not set correctly. Mostly it happens if the package (toolbox) of this function is added later, i.e., after installation of the original matlab. Please check and solve the license issue, then it will work fine.

Android Gradle Could not reserve enough space for object heap

Faced this issue on Android studio 4.1, windows 10.

The solution that worked for me:

1 - Go to file which is in the root directory of the project.

2 - Comment this line or similar one (org.gradle.jvmargs=-Xmx1536m) to let android studio decide on the best compatible option.

3 - Now close any open project from File -> close project.

4 - On the Welcome window, Go to Configure > Settings.

5 - Go to Build, Execution, Deployment > Compiler

6 - Change Build process heap size (Mbytes) to 1024 and VM Options to -Xmx512m.

Now close the android studio and restart it. The issue will be gone.

How to add data via $.ajax ( serialize() + extra data ) like this

What kind of data?

data: $('#myForm').serialize() + "&moredata=" + morevalue

The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.

How to log SQL statements in Spring Boot?

This works for me (YAML):

        show_sql: true
        format_sql: true
        type: trace

Navigate to another page with a button in angular 2

Having the router link on the button seems to work fine for me:

<button class="nav-link" routerLink="/" (click)="hideMenu()">
     <i class="fa fa-home"></i> 

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

For me I had to manually uninstall mysql

brew uninstall mysql
rm -rf /usr/local/var/mysql
brew install mysql

Splitting a continuous variable into equal sized groups

ntile from dplyr now does this but behaves weirdly with NA's.

I've used similar code in the following function that works in base R and does the equivalent of the cut2 solution above:

ntile_ <- function(x, n) {
    b <- x[!]
    q <- floor((n * (rank(b, ties.method = "first") - 1)/length(b)) + 1)
    d <- rep(NA, length(x))
    d[!] <- q

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

I think the annotation you are looking for is:

public class CompanyName implements Serializable {
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;

And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):

SQL Server : trigger how to read value for Insert, Update, Delete

Please note that inserted, deleted means the same thing as inserted CROSS JOIN deleted and gives every combination of every row. I doubt this is what you want.

Something like this may help get you started...

  CASE WHEN inserted.primaryKey IS NULL THEN 'This is a delete'
       WHEN  deleted.primaryKey IS NULL THEN 'This is an insert'
                                        ELSE 'This is an update'
  END  as Action,
    ON inserted.primaryKey = deleted.primaryKey

Depending on what you want to do, you then reference the table you are interested in with inserted.userID or deleted.userID, etc.

Finally, be aware that inserted and deleted are tables and can (and do) contain more than one record.

If you insert 10 records at once, the inserted table will contain ALL 10 records. The same applies to deletes and the deleted table. And both tables in the case of an update.

EDIT Examplee Trigger after OPs edit.

ALTER TRIGGER [dbo].[UpdateUserCreditsLeft] 
  ON  [dbo].[Order]

  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.

    CreditsLeft = CASE WHEN inserted.UserID IS NULL THEN <new value for a  DELETE>
                       WHEN  deleted.UserID IS NULL THEN <new value for an INSERT>
                                                    ELSE <new value for an UPDATE>
        ON inserted.UserID = deleted.UserID  -- This assumes UserID is the PK on UpdateUserCreditsLeft
      ON User.UserID = COALESCE(inserted.UserID, deleted.UserID)


If the PrimaryKey of UpdateUserCreditsLeft is something other than UserID, use that in the FULL OUTER JOIN instead.

Passing variables through handlebars partial

This is very possible if you write your own helper. We are using a custom $ helper to accomplish this type of interaction (and more):


Adds support for passing arguments to partials. Arguments are merged with 
the context for rendering only (non destructive). Use `:token` syntax to 
replace parts of the template path. Tokens are replace in order.

USAGE: {{$ '' context=newContext foo='bar' }}
USAGE: {{$ 'path.:1.:2' replaceOne replaceTwo foo='bar' }}


Handlebars.registerHelper('$', function(partial) {
    var values, opts, done, value, context;
    if (!partial) {
        console.error('No partial name given.');
    values =, 1);
    opts = values.pop();
    while (!done) {
        value = values.pop();
        if (value) {
            partial = partial.replace(/:[^\.]+/, value);
        else {
            done = true;
    partial = Handlebars.partials[partial];
    if (!partial) {
        return '';
    context = _.extend({}, opts.context||this, _.omit(opts, 'context', 'fn', 'inverse'));
    return new Handlebars.SafeString( partial(context) );

Why doesn't wireshark detect my interface?

For *nix OSes, run wireshark with sudo privileges. You need to be superuser in order to be able to view interfaces. Just like running tcpdump -D vs sudo tcpdump -D, the first one won't show any of the interfaces, won't compalain/prompt for sudo privileges either.

So, from terminal, run:

$ sudo wireshark

Applying styles to tables with Twitter Bootstrap

bootstrap provides various classes for table

 <table class="table"></table>
 <table class="table table-bordered"></table>
 <table class="table table-hover"></table>
 <table class="table table-condensed"></table>
 <table class="table table-responsive"></table>

How to adjust layout when soft keyboard appears

I use this Extended class frame And when I need to recalculate the height size onLayout I override onmeasure and subtract keyboardHeight using getKeyboardHeight()

My create frame who needs resize with softkeyboard

SizeNotifierFrameLayout frameLayout = new SizeNotifierFrameLayout(context) {
            private boolean first = true;

            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                super.onLayout(changed, left, top, right, bottom);

                if (changed) {
                    first = false;

            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) - getKeyboardHeight(), MeasureSpec.EXACTLY));

            protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
                boolean result = super.drawChild(canvas, child, drawingTime);
                if (child == actionBar) {
                    parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
                return result;



public class SizeNotifierFrameLayout extends FrameLayout {

    public interface SizeNotifierFrameLayoutDelegate {
        void onSizeChanged(int keyboardHeight, boolean isWidthGreater);

    private Rect                            rect            = new Rect();
    private Drawable                        backgroundDrawable;
    private int                             keyboardHeight;
    private int                             bottomClip;
    private SizeNotifierFrameLayoutDelegate delegate;
    private boolean                         occupyStatusBar = true;

    public SizeNotifierFrameLayout(Context context) {

    public Drawable getBackgroundImage() {
        return backgroundDrawable;

    public void setBackgroundImage(Drawable bitmap) {
        backgroundDrawable = bitmap;

    public int getKeyboardHeight() {
        View rootView = getRootView();
        int usableViewHeight = rootView.getHeight() - ( != 0 ? AndroidUtilities.statusBarHeight : 0) - AndroidUtilities.getViewInset(rootView);
        return usableViewHeight - (rect.bottom -;

    public void notifyHeightChanged() {
        if (delegate != null) {
            keyboardHeight = getKeyboardHeight();
            final boolean isWidthGreater = AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y;
            post(new Runnable() {
                public void run() {
                    if (delegate != null) {
                        delegate.onSizeChanged(keyboardHeight, isWidthGreater);

    public void setBottomClip(int value) {
        bottomClip = value;

    public void setDelegate(SizeNotifierFrameLayoutDelegate delegate) {
        this.delegate = delegate;

    public void setOccupyStatusBar(boolean value) {
        occupyStatusBar = value;

    protected boolean isActionBarVisible() {
        return true;

    protected void onDraw(Canvas canvas) {
        if (backgroundDrawable != null) {
            if (backgroundDrawable instanceof ColorDrawable) {
                if (bottomClip != 0) {
                    canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight() - bottomClip);
                backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
                if (bottomClip != 0) {
            } else if (backgroundDrawable instanceof BitmapDrawable) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) backgroundDrawable;
                if (bitmapDrawable.getTileModeX() == Shader.TileMode.REPEAT) {
                    float scale = 2.0f / AndroidUtilities.density;
                    canvas.scale(scale, scale);
                    backgroundDrawable.setBounds(0, 0, (int) Math.ceil(getMeasuredWidth() / scale), (int) Math.ceil(getMeasuredHeight() / scale));
                } else {
                    int actionBarHeight =
                            (isActionBarVisible() ? ActionBar.getCurrentActionBarHeight() : 0) + (Build.VERSION.SDK_INT >= 21 && occupyStatusBar ? AndroidUtilities.statusBarHeight : 0);
                    int   viewHeight = getMeasuredHeight() - actionBarHeight;
                    float scaleX     = (float) getMeasuredWidth() / (float) backgroundDrawable.getIntrinsicWidth();
                    float scaleY     = (float) (viewHeight + keyboardHeight) / (float) backgroundDrawable.getIntrinsicHeight();
                    float scale      = scaleX < scaleY ? scaleY : scaleX;
                    int   width      = (int) Math.ceil(backgroundDrawable.getIntrinsicWidth() * scale);
                    int   height     = (int) Math.ceil(backgroundDrawable.getIntrinsicHeight() * scale);
                    int   x          = (getMeasuredWidth() - width) / 2;
                    int   y          = (viewHeight - height + keyboardHeight) / 2 + actionBarHeight;
                    canvas.clipRect(0, actionBarHeight, width, getMeasuredHeight() - bottomClip);
                    backgroundDrawable.setBounds(x, y, x + width, y + height);
        } else {

    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

Authenticate Jenkins CI for Github private repository

I had a similar problem with gitlab. It turns out I had restricted the users that are allowed to login via ssh. This won't affect github users, but in case people end up here for gitlab (and the like) issues, ensure you add git to the AllowUsers setting in /etc/ssh/sshd_config:

# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes
AllowUsers batman git

How to get text and a variable in a messagebox

Why not use:

Dim msg as String = String.Format("Variable = {0}", variable)

More info on String.Format

python plot normal distribution

you can get cdf easily. so pdf via cdf

    import numpy as np
    import matplotlib.pyplot as plt
    import scipy.interpolate
    import scipy.stats

    def setGridLine(ax):
        ax.grid(which='major', linestyle='-', linewidth=0.5, color='grey')
        ax.grid(which='minor', linestyle=':', linewidth=0.5, color='#a6a6a6')
        ax.tick_params(which='both', # Options for both major and minor ticks
                        top=False, # turn off top ticks
                        left=False, # turn off left ticks
                        right=False,  # turn off right ticks
                        bottom=False) # turn off bottom ticks

    data1 = np.random.normal(0,1,1000000)

    f2 = scipy.interpolate.interp1d(x, y,kind='linear')
    x2 = np.linspace(x[0],x[-1],1001)
    y2 = f2(x2)

    y2b = np.diff(y2)/np.diff(x2)

    f3 = scipy.interpolate.interp1d(x, y,kind='cubic')
    x3 = np.linspace(x[0],x[-1],1001)
    y3 = f3(x3)

    y3b = np.diff(y3)/np.diff(x3)

    cdf = scipy.stats.norm.cdf(bins_centers)
    pdf = scipy.stats.norm.pdf(bins_centers)

    plt.rcParams["font.size"] = 18
    fig, ax = plt.subplots(3,1,figsize=(10,16))



    for idx in range(3):

How to convert a string of numbers to an array of numbers?

You can use to convert each element into a number.

var a = "1,2,3,4";

var b = a.split(',').map(function(item) {
    return parseInt(item, 10);

Check the Docs

Or more elegantly as pointed out by User: thg435

var b = a.split(',').map(Number);

Where Number() would do the rest:check here

Note: For older browsers that don't support map, you can add an implementation yourself like: = || function(_x) {
    for(var o=[], i=0; i<this.length; i++) { 
        o[i] = _x(this[i]); 
    return o;

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

Go to File->Project Structure->SDK Location and check if the path for SDK and JDK location specified by you is correct. If its not then set the correct path. Then It will work.

Does not contain a definition for and no extension method accepting a first argument of type could be found

placeBets(betList, stakeAmt) is an instance method not a static method. You need to create an instance of CBetfairAPI first:

MyBetfair api = new MyBetfair();
ArrayList bets = api.placeBets(betList, stakeAmt);

ReferenceError: document is not defined (in plain JavaScript)

It depends on when the self executing anonymous function is running. It is possible that it is running before window.document is defined.

In that case, try adding a listener

window.addEventListener('load', yourFunction, false);
// ..... or 
window.addEventListener('DOMContentLoaded', yourFunction, false);

yourFunction () {
  // some ocde


Update: (after the update of the question and inclusion of the code)

Read the following about the issues in referencing DOM elements from a JavaScript inserted and run in head element:
- “getElementsByTagName(…)[0]” is undefined?
- Traversing the DOM

Not equal to != and !== in PHP

$a !== $b TRUE if $a is not equal to $b, or they are not of the same type

Please Refer to