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?

The webfonts link works now, in all browsers!

Simply add your themes to the font link separated by a pipe (|), like this

<link href="|Material+Icons+Outlined" rel="stylesheet">

Then reference the class, like this:

// class="material-icons" or class="material-icons-outlined"

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

This pattern will also work with Angular Material:

<mat-icon class="material-icons-outlined">account_balance</mat-icon>

Adding an .env file to React Project

You have to install npm install env-cmd

Make .env in the root directory and update like this & REACT_APP_ is the compulsory prefix for the variable name.


Update package.json

  "scripts": {
    "start": "env-cmd react-scripts start",
    "build": "env-cmd react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"

What is pipe() function in Angular

RxJS Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections.

For example, RxJS defines operators such as map(), filter(), concat(), and flatMap().

You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.

The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.

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

When I used the Scaffold-DbContext command, it didn't include the "[key]" annotation in the model files or the "entity.HasKey(..)" entry in the "modelBuilder.Entity" blocks. My solution was to add a line like this in every "modelBuilder.Entity" block in the *Context.cs file:

entity.HasKey(X => x.Id);

I'm not saying this is better, or even the right way. I'm just saying that it worked for me.

How to Pass data from child to parent component Angular

Hello you can make use of input and output. Input let you to pass variable form parent to child. Output the same but from child to parent.

The easiest way is to pass "startdate" and "endDate" as input

<calendar [startDateInCalendar]="startDateInSearch" [endDateInCalendar]="endDateInSearch" ></calendar>

In this way you have your startdate and enddate directly in search page. Let me know if it works, or think another way. Thanks

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

This answer is to give a better understanding of this warning

Deprecation warning is caused when you use moment to create time object, var today = moment();.

If this warning is okay with you then I have a simpler method.

Don't use date object from js use moment instead. For example use moment() to get the current date.

Or convert the js date object to moment date. You can simply do that specifying the format of your js date object.

ie, moment("js date", "js date format");


moment("2014 04 25", "YYYY MM DD");

(BUT YOU CAN ONLY USE THIS METHOD UNTIL IT'S DEPRECIATED, this may be depreciated from moment in the future)

How do you format code on save in VS Code

For MAC user, add this line into your Default Settings

File path is: /Users/USER_NAME/Library/Application Support/Code/User/settings.json

"tslint.autoFixOnSave": true

Sample of the file would be:

    "window.zoomLevel": 0,
    "workbench.iconTheme": "vscode-icons",
    "typescript.check.tscVersion": false,
    "vsicons.projectDetection.disableDetect": true,
    "typescript.updateImportsOnFileMove.enabled": "always",
    "eslint.autoFixOnSave": true,
    "tslint.autoFixOnSave": true

How to change the datetime format in pandas

The below code worked for me instead of the previous one - try it out !

df['DOB']=pd.to_datetime(df['DOB'].astype(str), format='%m/%d/%Y')

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

Avro is a row-based storage format for Hadoop.

Parquet is a column-based storage format for Hadoop.

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

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


Generating Request/Response XML from a WSDL

I use SOAPUI 5.3.0, it has an option for creating requests/responses (also using WSDL), you can even create a mock service which will respond when you send request. Procedure is as follows:

  1. Right click on your project and select New Mock Service option which will create mock service.
  2. Right click on mock service and select New Mock Operation option which will create response which you can use as template.

EDIT #1:

Check out the SoapUI link for the latest version. There is a Pro version as well as the free open source version.

How to display .svg image using swift

You can use SVGKit for example.

1) Integrate it according to instructions. Drag&dropping the .framework file is fast and easy.

2) Make sure you have an Objective-C to Swift bridge file bridging-header.h with import code in it:

#import <SVGKit/SVGKit.h>
#import <SVGKit/SVGKImage.h>

3) Use the framework like this, assuming that dataFromInternet is NSData, previously downloaded from network:

let anSVGImage: SVGKImage = SVGKImage(data: dataFromInternet)
myIUImageView.image = anSVGImage.UIImage

The framework also allows to init an SVGKImage from other different sources, for example it can download image for you when you provide it with URL. But in my case it was crashing in case of unreachable url, so it turned out to be better to manage networking by myself. More info on it here.

How to save .xlsx data to file as a blob

This works as of: v0.14.0 of

/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */{ url: url, filename: "testsheet.xlsx", saveAs: true });

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

Woks fine for me on ubuntu 16.04. path: /etc/mysql/mysql.cnf

and paste that

# * Basic Settings

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

I imagine that these might possibly be changed with some styling options. But as far as default values go, these are taken from my version of Excel 2010 which should have the defaults.

"Bad" Red Font: 156, 0, 6; Fill: 255, 199, 206

"Good" Green Font: 0, 97, 0; Fill: 198, 239, 206

"Neutral" Yellow Font: 156, 101, 0; Fill: 255, 235, 156

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?

Answer in 2020 (Includes Timezone Support)

The problem we were having is that, by default, ISOStrings aren't localized to your timezone. So, this is kinda hacky, but here's how we ended up solving this issue:

/** Imports Moment for time utilities. */
const moment = require("moment-timezone")

//** Returns now in ISO format in Central Time */
export function getNowISO() {
  return `${moment().toISOString(true).substring(0, 23)}Z`

This will leave you with an exact ISO-formatted, localized string.

Important note: Moment now suggests using other packages for new projects.

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

I use something like this in my document.ready

var height = $(window).height();//gets height from device
var width = $(window).width(); //gets width from 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

There are several problems in your code.

First the big ones:

  1. You are creating a new figure and a new axes in every iteration of your loop ? put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop.

  2. Don't use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords.

  3. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal').

The minor things: You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax. Use ax.set_xlim(a,b) and ax.set_ylim(a,b)

This should be a working minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid

# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)

Output is this:


ORA-00907: missing right parenthesis

Firstly, in histories_T, you are referencing table T_customer (should be T_customers) and secondly, you are missing the FOREIGN KEY clause that REFERENCES orders; which is not being created (or dropped) with the code you provided.

There may be additional errors as well, and I admit Oracle has never been very good at describing the cause of errors - "Mutating Tables" is a case in point.

Let me know if there additional problems you are missing.

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

With so many answers already written, Here's my take.

With Angular 1.5.6 & ui-bootstrap 1.3.3 , just add this on the model & you are done.

ng-model-options="{timezone: 'UTC'}" 

Note: Use this only if you are concerned about the date being 1 day behind & not bothered with extra time of T00:00:00.000Z

Updated Plunkr Here :

Get month and year from date cells Excel

Please try something like:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

You seem to have three main possible scenarios:

  1. Space-separated date with time as text (eg as A1 below)
  2. Hyphen-separated date as text (eg as A2 below)
  3. Formatted date index (as A4 and A5 below)

ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.

I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.

Case #1

This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.

This with =FIND which looks for a space (" ") in C1, starting with the eighth character within C1 counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.

Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.


=VALUE(LEFT(C1,FIND(" ",C1,8))) 

returns 40671 in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.

Case #2

If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:


Takes the last four characters of C2, hence 2011 in this example.


Starting at the fourth character, takes the next two characters of C2, hence 05 in this example (representing May).


Takes the first two characters of C2, hence 08 in this example (representing the 8th day of the month). Date is not a text function so does not need to be wrapped in =VALUE.

Taken together


also returns 40671 in this example, but from different input from Case #1.

Case #3

Is simple because already a date serial number, so just


is sufficient.

Put the above together to cover all three cases in a single formula:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:

SO23928568 example

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

well since we use functions to handle an onchange event, we can do it like this:

class Form extends Component {
 constructor(props) {
  this.handlePasswordChange = this.handlePasswordChange.bind(this);
  this.state = { password: '' }

 aForceChange() {
  // something happened and a passwordChange
  // needs to be triggered!!

  // simple, just call the onChange handler
  this.handlePasswordChange('my password');

 handlePasswordChange(value) {
 // do something

 render() {
  return (
   <input type="text" value={this.state.password} onChange={changeEvent => this.handlePasswordChange(} />

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

JPG vs. JPEG image formats

They are identical. JPG is simply a holdover from the days of DOS when file extensions were required to be 3 characters long. You can find out more information about the JPEG standard here. A question very similar to this one was asked over at SuperUser, where the accepted answer should give you some more detailed information.

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

From the Web Designer’s Guide to PNG Image Format

PNG-8 and PNG-24

There are two PNG formats: PNG-8 and PNG-24. The numbers are shorthand for saying "8-bit PNG" or "24-bit PNG." Not to get too much into technicalities — because as a web designer, you probably don’t care — 8-bit PNGs mean that the image is 8 bits per pixel, while 24-bit PNGs mean 24 bits per pixel.

To sum up the difference in plain English: Let’s just say PNG-24 can handle a lot more color and is good for complex images with lots of color such as photographs (just like JPEG), while PNG-8 is more optimized for things with simple colors, such as logos and user interface elements like icons and buttons.

Another difference is that PNG-24 natively supports alpha transparency, which is good for transparent backgrounds. This difference is not 100% true because Adobe products’ Save for Web command allows PNG-8 with alpha transparency.

Get first and last day of month using threeten, LocalDate

if you want to do it only with the LocalDate-class:

LocalDate initial = LocalDate.of(2014, 2, 13);

LocalDate start = LocalDate.of(initial.getYear(), initial.getMonthValue(),1);

// Idea: the last day is the same as the first day of next month minus one day.
LocalDate end = LocalDate.of(initial.getYear(), initial.getMonthValue(), 1).plusMonths(1).minusDays(1);

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

When I had this problem, I had literally just forgot to fill in a parameter value in the XAML of the code.

For some reason though, the exception would send me to the CS of the WPF program rather than the XAML. No idea why.

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #

# ============ #
# OS generated #
# ============ #

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

How to use Select2 with JSON via Ajax request?

Here you have an example

    minimumInputLength: 2,
    tags: [],
    ajax: {
        url: URL,
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        data: function (term) {
            return {
                term: term
        results: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.completeName,
                        slug: item.slug,

It's quite easy

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'

Solution #1: Your statement

.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does not refer to a proper Range to act upon. Instead,

.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does (and similarly in some other cases).

Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

There are two checks that you can do to make this quite evident:

  1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

  2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

    Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    and see the different outcomes.

Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

Excel VBA date formats

Use value(cellref) on the side to evaluate the cells. Strings will produce the "#Value" error, but dates resolve to a number (e.g. 43173).

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

To throw another potential solution into the mix, I had a settings folder as well as a in my project dir. (I was switching back from environment-based settings files to one file. I have since reconsidered.)

Python was getting confused about whether I wanted to import project/ or project/settings/ I removed the settings dir and everything now works fine.

Compare two date formats in javascript/jquery

try with new Date(obj).getTime()

if( new Date(fit_start_time).getTime() > new Date(fit_end_time).getTime() )
    alert(fit_start_time + " is greater."); // your code
else if( new Date(fit_start_time).getTime() < new Date(fit_end_time).getTime() )
    alert(fit_end_time + " is greater."); // your code
    alert("both are same!"); // your code

Trigger an action after selection select2

//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
    console.log("Action Before Selected");
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);

//when a Department removing
$('#department_id').on('select2-removing', function (e) {
    console.log("Action Before Deleted");
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);

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

from tkinter import *
from PIL import ImageTk, Image'wm', 'iconphoto', Tk._w, ImageTk.PhotoImage('./resources/favicon.ico')))

The above worked for me.

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

It might be too late to answer this in 2019. but I tried all the answers and none worked for me. So I solved it simply this way:

@Html.EditorFor(m => m.SellDateForInstallment, "{0:dd/MM/yyyy}", 
               new {htmlAttributes = new { @class = "form-control", @type = "date" } })

EditorFor is what worked for me.

Note that SellDateForInstallment is a Nullable datetime object.

public DateTime? SellDateForInstallment { get; set; } // Model property

SimpleDateFormat parse loses timezone

All I needed was this :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

try {
    String d = sdf.format(new Date());
} catch (Exception e) {
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

Output : slightly dubious, but I want only the date to be consistent

2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013

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

Why the value had to be given in yyyy-MM-dd?

According to the input type = date spec of HTML 5, the value has to be in the format yyyy-MM-dd since it takes the format of a valid full-date which is specified in RFC3339 as

full-date = date-fullyear "-" date-month "-" date-mday

There is nothing to do with Angularjs since the directive input doesn't support date type.

How do I get Firefox to accept my formatted value in the date input?

FF doesn't support date type of input for at least up to the version 24.0. You can get this info from here. So for right now, if you use input with type being date in FF, the text box takes whatever value you pass in.

My suggestion is you can use Angular-ui's Timepicker and don't use the HTML5 support for the date input.

Reset select2 value and show placeholder

So, to reset the form some of you will have a reset button. Add the following code inside the script tag

    placeholder: "this is a placeholder",

Or just to empty select field without keeping a placeholder:


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

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    ' Assumes that the filter was previously applied
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

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

This worked for me.

     * return date in specific format, given a timestamp.
     * @param  timestamp  $datetime
     * @return string
    public static function showDateString($timestamp)
      if ($timestamp !== NULL) {
        $date = new DateTime();
        return $date->format("d-m-Y");
      return '';

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

h/H = 12/24 hours means you will write hh:mm = 12 hours format and HH:mm = 24 hours format

How do DATETIME values work in SQLite?

Store it in a field of type long. See Date.getTime() and new Date(long)

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

I had faced same issue whenever I tried executing curl on my https server.

About to connect() to localhost port 443 (#0)
Trying ::1...
Connected to localhost (::1) port 443 (#0)
Initializing NSS with certpath: sql:/etc/pki/nssdb

Observed this issue when I configured keystore path incorrectly. After correcting keystore path it worked.

Regular expression to match standard 10 digit phone number

I find this regular expression most useful for me for 10 digit contact number :




enter image description here

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

Determine the data type of your data source column, "CreateDate". Make sure it is producing an actual datetime field and not something like a varchar. If your data source is a stored procedure, it is entirely possible that CreateDate is being processed to produce a varchar in order to format the date, like so:

SELECT CONVERT(varchar,TableName.CreateDate,126) AS CreateDate 
FROM TableName ...

Using CONVERT like this is often done to make query results fill the requirements of whatever other code is going to be processing those results. Style 126 is ISO 8601 format, an international standard that works with any language setting. I don't know what your industry is, but that was probably intentional. You don't want to mess with it. This style (126) produces a string representation of a date in the form '2013-04-29T18:15:20.270' just like you reported! However, if CreateDate's been processed this way then there's no way you'll be able to get your bf1.DataFormatString to show "29/04/2013" instead. You must first start with a datetime type column in your original SQL data source first for bf1 to properly consume it. So just add it to the data source query, and call it by a different name like CreateDate2 so as not to disturb whatever other code already depends on CreateDate, like this:

SELECT CONVERT(varchar,TableName.CreateDate,126) AS CreateDate, 
       TableName.CreateDate AS CreateDate2
FROM TableName ...

Then, in your code, you'll have to bind bf1 to "CreateDate2" instead of the original "CreateDate", like so:

BoundField bf1 = new BoundField();
bf1.DataField = "CreateDate2";
bf1.DataFormatString = "{0:dd/MM/yyyy}";
bf1.HtmlEncode = false;
bf1.HeaderText = "Sample Header 2";


Voila! Your date should now show "29/04/2013" instead!

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

From this: (source)

function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Byte';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];

Note : This is original code, Please use fixed version below. Aliceljm does not active her copied code anymore

Now, Fixed version unminified, and ES6'ed: (by community)

function formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];

Now, Fixed version : (by Stackoverflow's community, + Minified by JSCompress)

function formatBytes(a,b=2){if(0===a)return"0 Bytes";const c=0>b?0:b,d=Math.floor(Math.log(a)/Math.log(1024));return parseFloat((a/Math.pow(1024,d)).toFixed(c))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}

Usage :

// formatBytes(bytes,decimals)

formatBytes(1024);       // 1 KB
formatBytes('1024');     // 1 KB
formatBytes(1234);       // 1.21 KB
formatBytes(1234, 3);    // 1.205 KB

Demo / source :

function formatBytes(bytes, decimals = 2) {_x000D_
    if (bytes === 0) return '0 Bytes';_x000D_
    const k = 1024;_x000D_
    const dm = decimals < 0 ? 0 : decimals;_x000D_
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];_x000D_
    const i = Math.floor(Math.log(bytes) / Math.log(k));_x000D_
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];_x000D_
// ** Demo code **_x000D_
var p = document.querySelector('p'),_x000D_
    input = document.querySelector('input');_x000D_
function setText(v){_x000D_
    p.innerHTML = formatBytes(v);_x000D_
// bind 'input' event_x000D_
input.addEventListener('input', function(){ _x000D_
    setText( this.value )_x000D_
// set initial text_x000D_
<input type="text" value="1000">_x000D_

PS : Change k = 1000 or sizes = ["..."] as you want (bits or bytes)

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?

It seems that in the debug log for Java 6 the request is send in SSLv2 format.

main, WRITE: SSLv2 client hello message, length = 110

This is not mentioned as enabled by default in Java 7.
Change the client to use SSLv3 and above to avoid such interoperability issues.

Look for differences in JSSE providers in Java 7 and Java 6

python dict to numpy structured array

Even more simple if you accept using pandas :

import pandas
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
df = pandas.DataFrame(result, index=[0])
print df

gives :

          0         1         2         3  4         5         6
0  1.118175  0.556608  0.471827  0.487167  1  0.139508  0.209416

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 came up with:

.select2-selection__rendered {
    line-height: 2em !important;
.select2-container .select2-selection--single {
    height: 2em !important;
.select2-selection__arrow {
    height: 2em !important;


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

Change the date range to "General" format and save the workbook once, and change them back to date format (eg, numberformat = "d/m/yyyy") before save & close the book. savechanges parameter is true.

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

This works perfectly for me, not matter how the date was coded previously.

data$created_date1 <- mdy_hm(data$created_at)
data$created_date1 <- as.Date(data$created_date1)

How to format a date using ng-model?

I use the following directive that makes me and most users very happy! It uses moment for parsing and formatting. It looks a little bit like the one by SunnyShah, mentioned earlier.


.directive('appDatetime', function ($window) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            var moment = $window.moment;


            element.on('change', function (e) {
                var element =;
                element.value = formatter(ngModel.$modelValue);

            function parser(value) {
                var m = moment(value);
                var valid = m.isValid();
                ngModel.$setValidity('datetime', valid);
                if (valid) return m.valueOf();
                else return value;

            function formatter(value) {
                var m = moment(value);
                var valid = m.isValid();
                if (valid) return m.format("LLLL");
                else return value;


        } //link

}); //appDatetime

In my form i use it like this:

<label>begin: <input type="text" ng-model="doc.begin" app-datetime required /></label>
<label>end: <input type="text" ng-model="doc.end" app-datetime required /></label>

This will bind a timestamp (milliseconds since 1970) to doc.begin and doc.end.

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

Try with this

Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.pptx;", getLegalFileName(CurrentPresentation.Presentation_NM)));

What Are The Best Width Ranges for Media Queries

You can take a look here for a longer list of screen sizes and respective media queries.

Or go for Bootstrap media queries:

/* Large desktop */
@media (min-width: 1200px) { ... }

/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }

/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }

/* Landscape phones and down */
@media (max-width: 480px) { ... }

Additionally you might wanty to take a look at Foundation's media queries with the following default settings:

// Media Queries

$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;

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

Without opening an IDE to check my brain works properly for syntax at this time of day...

If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.


DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");

would give you the date as a string in the format you request.

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"

     string ImagePath = "";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
        string a = "";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
            Stream receiveStream = response.GetResponseStream();
            if (receiveStream.CanRead)
            { a = "OK"; }

        catch { }

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

If you want to return a File to be downloaded, specially if you want to integrate with some javascript libs of file upload/download, then the code bellow should do the job:

public Response download(@PathParam("key") String key,
                         @Context HttpServletResponse response) throws IOException {
    try {
        //Get your File or Object from wherever you want...
            //you can use the key parameter to indentify your file
            //otherwise it can be removed
        //let's say your file is called "object"
        response.setContentLength((int) object.getContentLength());
        response.setHeader("Content-Disposition", "attachment; filename="
                + object.getName());
        ServletOutputStream outStream = response.getOutputStream();
        byte[] bbuf = new byte[(int) object.getContentLength() + 1024];
        DataInputStream in = new DataInputStream(
        int length = 0;
        while ((in != null) && ((length = != -1)) {
            outStream.write(bbuf, 0, length);
    } catch (S3ServiceException e) {
    } catch (ServiceException e) {
    return Response.ok().build();

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

These days (May 2017), MATLAB still suffer from a robust method to export figures, especially in GNU/Linux systems when exporting figures in batch mode. The best option is to use the extension export_fig

Just download the source code from Github and use it:

plot(cos(linspace(0, 7, 1000)));
set(gcf, 'Position', [100 100 150 150]);
export_fig test2.png

How to make Sonar ignore some classes for codeCoverage metric?

At the time of this writing (which is with SonarQube 4.5.1), the correct property to set is sonar.coverage.exclusions, e.g.:


This seems to be a change from just a few versions earlier. Note that this excludes the given classes from coverage calculation only. All other metrics and issues are calculated.

In order to find the property name for your version of SonarQube, you can try going to the General Settings section of your SonarQube instance and look for the Code Coverage item (in SonarQube 4.5.x, that's General Settings → Exclusions → Code Coverage). Below the input field, it gives the property name mentioned above ("Key: sonar.coverage.exclusions").

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

 import datetime

Current Date and time

     #2019-09-08 09:12:12.473393

Current date only


Current year only


Current month only


Current day only


Datatable date sorting dd/mm/yyyy issue

You can resolve this issue with php.

$mydate = strtotime($startdate);
$newformat = date('d-m-Y',$mydate);
echo '<tr>';
echo '  <td data-sort="'. $mydate .'">'.$newformat .'</td>';

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)

You can know the correct content-type for any file by just doing the following:

1) Select interested file,

2) And run in console this:


You can also set attribute "multiple" for your input to check content-type for several files at a time and do next:

for (var i = 0; i < $('.file-input')[0].files.length; i++){

Attribute accept has some problems with multiple attribute and doesn't work correctly in this case.

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

As alternative

    function FormatPhone(tt,e){
  var t = $(tt);
  var v1 = t.val();
  var k = e.which;
  if(k!=8 && v1.length===18){
  var q = String.fromCharCode((96 <= k && k <= 105)? k-48 : k);
  if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=8 && e.keyCode!=39) {
      var v = t.val();
      var l = v.length;
          t.val('+7 ');
        else if(l===4){
            t.val('+7 (');
            t.val('+7 ('+q);
        else if(l===7){
        else if(l===9){
          t.val(v1+' '+q);
        else if(l===13||l===16){
        else if(l>18){
            t.val('+7 ');

Format datetime in mvc 4

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.

My finally working solution:

$(function () {
    $ = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();

You have to include before:


You can install moment.js using:

Install-Package Moment.js

Google Play app description formatting

Another alternative to cut, copy and paste emojis is:

MySQL date format DD/MM/YYYY select query?

for my case this worked

str_to_date(date, '%e/%m/%Y' )

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

You can always format a date by extracting the parts and combine them using string functions:

var date = new Date();_x000D_
var dateStr =_x000D_
  ("00" + (date.getMonth() + 1)).slice(-2) + "/" +_x000D_
  ("00" + date.getDate()).slice(-2) + "/" +_x000D_
  date.getFullYear() + " " +_x000D_
  ("00" + date.getHours()).slice(-2) + ":" +_x000D_
  ("00" + date.getMinutes()).slice(-2) + ":" +_x000D_
  ("00" + date.getSeconds()).slice(-2);_x000D_

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

Without using regex, you can just do:

def get_num(x):
    return int(''.join(ele for ele in x if ele.isdigit()))


>>> get_num(x)
>>> get_num(y)
>>> get_num(banana)
>>> get_num(orange)


Answering the follow up question.

If we know that the only period in a given string is the decimal point, extracting a float is quite easy:

def get_num(x):
    return float(''.join(ele for ele in x if ele.isdigit() or ele == '.'))


>>> get_num('dfgd 45.678fjfjf')

DB2 Date format

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

Example using Hyperlink in WPF

I liked Arthur's idea of a reusable handler, but I think there's a simpler way to do it:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
    if (sender.GetType() != typeof (Hyperlink))
    string link = ((Hyperlink) sender).NavigateUri.ToString();

Obviously there could be security risks with starting any kind of process, so be carefull.

python-pandas and databases like mysql

As Wes says, io/sql's read_sql will do it, once you've gotten a database connection using a DBI compatible library. We can look at two short examples using the MySQLdb and cx_Oracle libraries to connect to Oracle and MySQL and query their data dictionaries. Here is the example for cx_Oracle:

import pandas as pd
import cx_Oracle

ora_conn = cx_Oracle.connect('your_connection_string')
df_ora = pd.read_sql('select * from user_objects', con=ora_conn)    
print 'loaded dataframe from Oracle. # Records: ', len(df_ora)

And here is the equivalent example for MySQLdb:

import MySQLdb
mysql_cn= MySQLdb.connect(host='myhost', 
                port=3306,user='myusername', passwd='mypassword', 
df_mysql = pd.read_sql('select * from VIEWS;', con=mysql_cn)    
print 'loaded dataframe from MySQL. records:', len(df_mysql)

Sublime Text 2 Code Formatting

Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.

For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).


MySQL date formats - difficulty Inserting a date

Looks like you've not encapsulated your string properly. Try this:

INSERT INTO custorder VALUES ('Kevin','yes'), STR_TO_DATE('1-01-2012', '%d-%m-%Y');

Alternatively, you can do the following but it is not recommended. Make sure that you use STR_TO-DATE it is because when you are developing web applications you have to explicitly convert String to Date which is annoying. Use first One.

INSERT INTO custorder VALUES ('Kevin','yes'), '2012-01-01';

I'm not confident that the above SQL is valid, however, and you may want to move the date part into the brackets. If you can provide the exact error you're getting, I might be able to more directly help with the issue.

milliseconds to time in javascript

Not to reinvent the wheel, here is my favourite one-liner solution:

 * Convert milliseconds to time string (hh:mm:ss:mss)._x000D_
 * @param Number ms_x000D_
 * @return String_x000D_
function time(ms) {_x000D_
    return new Date(ms).toISOString().slice(11, -1);_x000D_
console.log( time(12345 * 1000) );  // "03:25:45.000"

Method Date.prototype.toISOString() returns a string in simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. This method is supported in all modern browsers (IE9+) and JavaScript engines.

UPDATE: The solution above is always limited to range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000). To make it working with any input value, I have extended it into a nice universal prototype method:

 * Convert (milli)seconds to time string (hh:mm:ss[:mss])._x000D_
 * @param Boolean isSec_x000D_
 * @return String_x000D_
Number.prototype.toTime = function(isSec) {_x000D_
    var ms = isSec ? this * 1e3 : this,_x000D_
        lm = ~(4 * !!isSec),  /* limit fraction */_x000D_
        fmt = new Date(ms).toISOString().slice(11, lm);_x000D_
    if (ms >= 8.64e7) {  /* >= 24 hours */_x000D_
        var parts = fmt.split(/:(?=\d{2}:)/);_x000D_
        parts[0] -= -24 * (ms / 8.64e7 | 0);_x000D_
        return parts.join(':');_x000D_
    return fmt;_x000D_
console.log( (12345 * 1000).toTime()     );  // "03:25:45.000"_x000D_
console.log( (123456 * 789).toTime()     );  // "27:03:26.784"_x000D_
console.log(  12345.       .toTime(true) );  // "03:25:45"_x000D_
console.log(  123456789.   .toTime(true) );  // "34293:33:09"

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

This function handels "HH:MM:SS" as well as "MM:SS" or "SS".

function hmsToSecondsOnly(str) {
    var p = str.split(':'),
        s = 0, m = 1;

    while (p.length > 0) {
        s += m * parseInt(p.pop(), 10);
        m *= 60;

    return s;

ValueError: unsupported format character while forming strings

You could escape the % in %20 like so:

print "Hello%%20World%s" %"!"

or you could try using the string formatting routines instead, like:

print "Hello%20World{0}".format("!")

matplotlib savefig in jpeg format

You can save an image as 'png' and use the python imaging library (PIL) to convert this file to 'jpg':

import Image
import matplotlib.pyplot as plt


The original:

enter image description here

The JPEG image:

enter image description here

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

try this

var  insert = DateTime.ParseExact(line[i], "M/d/yyyy h:mm", CultureInfo.InvariantCulture);

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

Found a nice solution in another Stackoverflow post (using only standard libraries + dealing with jpg as well): JohnTESlade answer

And another solution (the quick way) for those who can afford running 'file' command within python, run:

import os
info = os.popen("file foo.jpg").read()
print info


foo.jpg: JPEG image data...density 28x28, segment length 16, baseline, precision 8, 352x198, frames 3

All you gotta do now is to format the output to capture the dimensions. 352x198 in my case.

How to change Git log date formats

The format option %ai was what I wanted:

%ai: author date, ISO 8601-like format


When should the xlsm or xlsb formats be used?

.xlsx loads 4 times longer than .xlsb and saves 2 times longer and has 1.5 times a bigger file. I tested this on a generated worksheet with 10'000 rows * 1'000 columns = 10'000'000 (10^7) cells of simple chained =…+1 formulas:

¦              ¦ .xlsx  ¦ .xlsb  ¦
¦ loading time ¦ 165s   ¦  43s   ¦
¦ saving time  ¦ 115s   ¦  61s   ¦
¦ file size    ¦  91 MB ¦  65 MB ¦

(Hardware: Core2Duo 2.3 GHz, 4 GB RAM, 5.400 rpm SATA II HD; Windows 7, under somewhat heavy load from other processes.)

Beside this, there should be no differences. More precisely,

both formats support exactly the same feature set

cites this blog post from 2006-08-29. So maybe the info that .xlsb does not support Ribbon code is newer than the upper citation, but I figure that forum source of yours is just wrong. When cracking open the binary file, it seems to condensedly mimic the OOXML file structure 1-to-1: Blog article from 2006-08-07

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

If you're using IIS with Windows Authentification and Entity Framework, be careful to use authorize.

I tried to POST without authorize and it didn't work, and get this error on db.SaveChangesAsync();, while all other verbs GET and DELETE were working.

But when I added AuthorizeAttribute as annotation, it worked.

public async Task<IHttpActionResult> Post(...){

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

Don't re-invent the wheel. Use a pre-built solution for parsing dates, like

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.

1 Assuming you use it properly, of course. See comments.

Convert date formats in bash

#since this was yesterday
date -dyesterday +%Y%m%d

#more precise, and more recommended
date -d'27 JUN 2011' +%Y%m%d

#assuming this is similar to yesterdays `date` question from you 
date -d'last-monday' +%Y%m%d

#going on @seth's comment you could do this
DATE="27 jun 2011"; date -d"$DATE" +%Y%m%d

#or a method to read it from stdin
read -p "  Get date >> " DATE; printf "  AS YYYYMMDD format >> %s"  `date
-d"$DATE" +%Y%m%d`    

#which then outputs the following:
#Get date >> 27 june 2011   
#AS YYYYMMDD format >> 20110627

#if you really want to use awk
echo "27 june 2011" | awk '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}' | bash

#note | bash just redirects awk's output to the shell to be executed
#FS is field separator, in this case you can use $0 to print the line
#But this is useful if you have more than one date on a line

More on Dates

note this only works on GNU date

I have read that:

Solaris version of date, which is unable to support -d can be resolve with replacing version of date

Check whether a path is valid

You can try this code:

  // Path is not valid

I'm not sure it covers all the cases...

How to do URL decoding in Java?

public String decodeString(String URL)

    String urlString="";
    try {
        urlString = URLDecoder.decode(URL,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block


        return urlString;


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

If all your DateTime types are rendered the same way you can use a custom DateTime display template.

In your Views folder create a folder named "DisplayTemplates" either under your controller specific views folder, or under "Shared" folder (these work similar to partials).

Inside create a file named DateTime.cshtml that takes DateTime as the @model and code how you want to render your date:

@model System.DateTime

Now you can just use this in your views and it should work:

@Html.DisplayFor(mod => mod.MyDateTime)

As long as you follow the convention of adding it to the "DisplayTemplates" folder and naming the file to match the type your are displaying, MVC will automatically use that to display your values. This also works for editing scenarios using "EditorTemplates".

Here's some more information on templates.

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 you have libx264 installed and configured with ffmpeg to convert video to h264... Then you can try with -vcodec libx264... The -format option is for showing available formats, this is not a conversion option I think...

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

1) I am using WAMP.

2) I have installed Open Office (from apache

3) $output_dir = "C:/wamp/www/projectfolder/"; this is my project folder where i want to create output file.

4) I have already placed my input file here C:/wamp/www/projectfolder/wordfile.docx";

Then I Run My Code.. (given below)

    function MakePropertyValue($name,$value,$osm){
    $oStruct = $osm->Bridge_GetStruct("");
    $oStruct->Name = $name;
    $oStruct->Value = $value;
    return $oStruct;
    function word2pdf($doc_url, $output_url){

    //Invoke the service manager
    $osm = new COM("") or die ("Please be sure that is installed.\n");
    //Set the application to remain hidden to avoid flashing the document onscreen
    $args = array(MakePropertyValue("Hidden",true,$osm));
    //Launch the desktop
    $oDesktop = $osm->createInstance("");
    //Load the .doc file, and pass in the "Hidden" property from above
    $oWriterDoc = $oDesktop->loadComponentFromURL($doc_url,"_blank", 0, $args);
    //Set up the arguments for the PDF output
    $export_args = array(MakePropertyValue("FilterName","writer_pdf_Export",$osm));
    //Write out the PDF

    $output_dir = "C:/wamp/www/projectfolder/";
    $doc_file = "C:/wamp/www/projectfolder/wordfile.docx";
    $pdf_file = "outputfile_name.pdf";

    $output_file = $output_dir . $pdf_file;
    $doc_file = "file:///" . $doc_file;
    $output_file = "file:///" . $output_file;

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

SimpleDateFormat sdf=new SimpleDateFormat("EEE");

EEE stands for day of week for example Thursday is displayed as Thu.

Reset Excel to default borders

If you have applied border and/or fill on a cell, you need to clear both to go back to the default borders.

You may apply 'None' as the border option and expect the default borders to show, but it will not when the cell fill is white. It's not immediately obvious that it has a white fill, as unfilled cells are also white.

In this case, apply a 'No Fill' on the cells, and you will get the default borders back.

Screenshot of Excel indicating locations of No Border and No Fill options

That's it. No messy format painting, no 'Clear Formats', none of those destructive methods. Easy, quick and painless.

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

Double value to round up in Java

Note the comma in your string: "1,07". DecimalFormat uses a locale-specific separator string, while Double.parseDouble() does not. As you happen to live in a country where the decimal separator is ",", you can't parse your number back.

However, you can use the same DecimalFormat to parse it back:

DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;

But you really should do this instead:

double finalValue = Math.round( value * 100.0 ) / 100.0;

Note: As has been pointed out, you should only use floating point if you don't need a precise control over accuracy. (Financial calculations being the main example of when not to use them.)

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

Try this one - it includes validation for international formats too.


This regex validates the following format:

  • (541) 754-3010 Domestic
  • +1-541-754-3010 International
  • 1-541-754-3010 Dialed in the US
  • 001-541-754-3010 Dialed from Germany
  • 191 541 754 3010 Dialed from France

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

Update: Webm with an alpha channel is now supported in Chrome and Firefox.

For other browers, there are workarounds, but they involve re-rendering the video using Canvas and it is kind of a hack. seeThru is one example. It works pretty well on HTML5 desktop browsers (even IE9) but it doesn't seem to work very well on mobile. I couldn't get it to work at all on Chrome for Android. It did work on Firefox for Android but with a pretty lousy framerate. I think you might be out of luck for mobile, although I'd love to be proven wrong.

How to parse dates in multiple formats using SimpleDateFormat

In Apache commons lang, DateUtils class we have a method called parseDate. We can use this for parsing the date.

Also another library Joda-time also have the method to parse the date.

Rotating videos with FFmpeg

This script that will output the files with the directory structure under "fixedFiles". At the moment is fixed to MOV files and will execute a number of transformations depending on the original "rotation" of the video. Works with iOS captured videos on a Mac running Mavericks, but should be easily exportable. Relies on having installed both exiftool and ffmpeg.


# rotation of 90 degrees. Will have to concatenate.
#ffmpeg -i <originalfile> -metadata:s:v:0 rotate=0 -vf "transpose=1" <destinationfile>
#/VLC -I dummy -vvv <originalfile> --sout='#transcode{width=1280,vcodec=mp4v,vb=16384,vfilter={canvas{width=1280,height=1280}:rotate{angle=-90}}}:std{access=file,mux=mp4,dst=<outputfile>}\' vlc://quit

#Allowing blanks in file names
IFS=$(echo -en "\n\b")

#Bit Rate

#where to store fixed files

VLC_START="/Applications/ -I dummy -vvv"

# Processing of MOV in the wrong orientation
for f in `find . -regex '\./.*\.MOV'` 
  ROTATION=`exiftool "$f" |grep Rotation|cut -c 35-38`
  SHORT_DIMENSION=`exiftool "$f" |grep "Image Size"|cut -c 39-43|sed 's/x//'`
  BITRATE_INT=`exiftool "$f" |grep "Avg Bitrate"|cut -c 35-38|sed 's/\..*//'`
  echo Short dimension [$SHORT_DIMENSION] $BITRATE_INT

  if test "$ROTATION" != ""; then
    DEST=$(dirname ${f})
    echo "Processing $f with rotation $ROTATION in directory $DEST"
    mkdir -p $FIXED_FILES_DIR/"$DEST"

    if test "$ROTATION" == "0"; then
      cp "$f" "$FIXED_FILES_DIR/$f"

    elif test "$ROTATION" == "180"; then
#      $(eval $VLC_START \"$f\" "--sout="\'"#transcode{vfilter={rotate{angle=-"$ROTATION"}},vcodec=mp4v,vb=$BR}:std{access=file,mux=mp4,dst=\""$FIXED_FILES_DIR/$f"\"}'" $VLC_END )
      $(eval ffmpeg -i \"$f\" -vf hflip,vflip -r 30 -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\")

    elif test "$ROTATION" == "270"; then
      $(eval ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=2,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" )

#      $(eval $VLC_START \"$f\" "--sout="\'"#transcode{scale=1,width=$SHORT_DIMENSION,vcodec=mp4v,vb=$BR,vfilter={canvas{width=$SHORT_DIMENSION,height=$SHORT_DIMENSION}:rotate{angle=-"$ROTATION"}}}:std{access=file,mux=mp4,dst=\""$FIXED_FILES_DIR/$f"\"}'" $VLC_END )
      echo ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=1,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" 
      $(eval ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=1,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" )



echo ==================================================================
sleep 1

# Processing of AVI files for my Panasonic TV
# Use ffmpegX + QuickBatch. Bitrate at 16384. Camera res 640x424
for f in `find . -regex '\./.*\.AVI'` 
  DEST=$(dirname ${f})
  DEST_FILE=`echo "$f" | sed 's/.AVI/.MOV/'`
  mkdir -p $FIXED_FILES_DIR/"$DEST"
  echo "Processing $f in directory $DEST"
  $(eval ffmpeg -i \"$f\" -r 20 -acodec libvo_aacenc -b:a 128k -vcodec mpeg4 -b:v 8M -flags +aic+mv4 \"$FIXED_FILES_DIR/$DEST_FILE\" )
echo ==================================================================



Select method of Range class failed via VBA

Here is a solution worked for me and also, I found all of the above solutions are correct. My excel model got corrupted and which is why my code (similar to this one) stopped working. Here is what worked for me and is working every time-

  1. Calculate the workbook- Formulas->Calculate Now (under calculation section)
  2. Save the workbook
  3. Close and re-open the file. It was fixed and works every time.

Using ffmpeg to encode a high quality video

You need to specify the -vb option to increase the video bitrate, otherwise you get the default which produces smaller videos but with more artifacts.

Try something like this:

ffmpeg -r 25 -i %4d.png -vb 20M myvideo.mpg

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

Chris Nolet cleaner example of Lasnv answer is very good, but I recently found out that if you trying to find your youtube link in text and put some random text after the youtube url, regexp matches way more than needed. Improved Chris Nolet answer:


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

You could use this command:

ffmpeg -i input.wav -vn -ar 44100 -ac 2 -b:a 192k output.mp3

Explanation of the used arguments in this example:

  • -i - input file

  • -vn - Disable video, to make sure no video (including album cover image) is included if the source would be a video file

  • -ar - Set the audio sampling frequency. For output streams it is set by default to the frequency of the corresponding input stream. For input streams this option only makes sense for audio grabbing devices and raw demuxers and is mapped to the corresponding demuxer options.

  • -ac - Set the number of audio channels. For output streams it is set by default to the number of input audio channels. For input streams this option only makes sense for audio grabbing devices and raw demuxers and is mapped to the corresponding demuxer options. So used here to make sure it is stereo (2 channels)

  • -b:a - Converts the audio bitrate to be exact 192kbit per second

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

I tried to convert ddmmyy format to date("Y-m-d" format but was not working when I directly pass ddmmyy =date('dmy')

then realized it has to be in yyyy-mm-dd format so. used substring to organize

$strParam = '20'.substr($_GET['date'], 4, 2).'-'.substr($_GET['date'], 2, 2).'-'.substr($_GET['date'], 0, 2);  

then passed to date("Y-m-d",strtotime($strParam));

it worked!

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?

Just save some one time. I spent 3 hours to find out that it was just html encoding problem. Try this

   $param = stripslashes($row['your column name']);
  $param = $row['your column name'];

$param = json_decode(html_entity_decode($param),true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;

Java SimpleDateFormat for time zone with a colon separator?

if you used the java 7, you could have used the following Date Time Pattern. Seems like this pattern is not supported in the Earlier version of java.

String dateTimeString  = "2010-03-01T00:00:00-08:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date date = df.parse(dateTimeString);

For More information refer to the SimpleDateFormat documentation.

How can I mix LaTeX in with Markdown?

RStudio has a good free IDE that allows for Markdown and LaTeX.

jQuery and TinyMCE: textarea value doesn't submit

I had this problem for a while and triggerSave() didn't work, nor did any of the other methods.

So I found a way that worked for me ( I'm adding this here because other people may have already tried triggerSave and etc... ):

   selector: '.tinymce', // This is my <textarea> class
   setup : function(ed) {
                  ed.on('change', function(e) {
                     // This will print out all your content in the tinyMce box
                     console.log('the content '+ed.getContent());
                     // Your text from the tinyMce box will now be passed to your  text area ... 
   ... Your other tinyMce settings ...

When you're submitting your form or whatever all you have to do is grab the data from your selector ( In my case: .tinymce ) using $('.tinymce').text().

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

Just a necrocomment for using string.Join and LINQ.

ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
dlgOpenMockImage.Filter = string.Format("{0}| All image files ({1})|{1}|All files|*", 
    string.Join("|", codecs.Select(codec => 
    string.Format("{0} ({1})|{1}", codec.CodecName, codec.FilenameExtension)).ToArray()),
    string.Join(";", codecs.Select(codec => codec.FilenameExtension).ToArray()));

Best way to check if a URL is valid

Using filter_var() will fail for urls with non-ascii chars, e.g. (ães). The following function encode all non-ascii chars (e.g. before calling filter_var().

Hope this helps someone.


function validate_url($url) {
    $path = parse_url($url, PHP_URL_PATH);
    $encoded_path = array_map('urlencode', explode('/', $path));
    $url = str_replace($path, implode('/', $encoded_path), $url);

    return filter_var($url, FILTER_VALIDATE_URL) ? true : false;

// example
if(!validate_url("")) {
    echo "NOT A URL";
else {
    echo "IS A URL";

Date only from TextBoxFor()

Sure you can use Html.EditorFor. But if you want to use TextBoxFor and use format from DisplayFormat attribute you can use it in this way:

@Html.TextBoxFor(model => model.dtArrivalDate, ModelMetadata.FromLambdaExpression(model => model.dtArrivalDate, ViewData).EditFormatString)

or create next extension:

public static class HtmlExtensions
    public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
        return htmlHelper.TextBoxFor(expression, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).EditFormatString, htmlAttributes);

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;"

The reason for this is PHP doesn't recognise utf-8.

Here you can check it for all Special Characters in HTML

Convert seconds to hh:mm:ss in Python

>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)

How to get number of rows using SqlDataReader in C#

There are only two options:

  • Find out by reading all rows (and then you might as well store them)

  • run a specialized SELECT COUNT(*) query beforehand.

Going twice through the DataReader loop is really expensive, you would have to re-execute the query.

And (thanks to Pete OHanlon) the second option is only concurrency-safe when you use a transaction with a Snapshot isolation level.

Since you want to end up storing all rows in memory anyway the only sensible option is to read all rows in a flexible storage (List<> or DataTable) and then copy the data to any format you want. The in-memory operation will always be much more efficient.

How to mark-up phone numbers?

I used tel: for my project.

It worked in Chrome, Firefox, IE9&8, Chrome mobile and the mobile Browser on my Sony Ericsson smartphone.

But callto: did not work in the mobile Browsers.

Format XML string to print friendly XML string

This one, from kristopherjohnson is heaps better:

  1. It doesn't require an XML document header either.
  2. Has clearer exceptions
  3. Adds extra behaviour options: OmitXmlDeclaration = true, NewLineOnAttributes = true
  4. Less lines of code

    static string PrettyXml(string xml)
        var stringBuilder = new StringBuilder();
        var element = XElement.Parse(xml);
        var settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        settings.Indent = true;
        settings.NewLineOnAttributes = true;
        using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
        return stringBuilder.ToString();

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

The specific answer to this question is found in these two lines below:

//pull the last two digits of the year_x000D_
console.log(new Date().getFullYear().toString().substr(2,2));

Formatting Full Date Time Example (MMddyy): jsFiddle


    //A function for formatting a date to MMddyy_x000D_
function formatDate(d)_x000D_
    //get the month_x000D_
    var month = d.getMonth();_x000D_
    //get the day_x000D_
    var day = d.getDate();_x000D_
    //get the year_x000D_
    var year = d.getFullYear();_x000D_
    //pull the last two digits of the year_x000D_
    year = year.toString().substr(2,2);_x000D_
    //increment month by 1 since it is 0 indexed_x000D_
    month = month + 1;_x000D_
    //converts month to a string_x000D_
    month = month + "";_x000D_
    //if month is 1-9 pad right with a 0 for two digits_x000D_
    if (month.length == 1)_x000D_
        month = "0" + month;_x000D_
    //convert day to string_x000D_
    day = day + "";_x000D_
    //if day is between 1-9 pad right with a 0 for two digits_x000D_
    if (day.length == 1)_x000D_
        day = "0" + day;_x000D_
    //return the string "MMddyy"_x000D_
    return month + day + year;_x000D_
var d = new Date();_x000D_

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

    function focusCampo(id){
        var inputField = document.getElementById(id);
        if (inputField != null && inputField.value.length != 0){
            if (inputField.createTextRange){
                var FieldRange = inputField.createTextRange();
            }else if (inputField.selectionStart || inputField.selectionStart == '0') {
                var elemLen = inputField.value.length;
                inputField.selectionStart = elemLen;
                inputField.selectionEnd = elemLen;


works for all ie browsers..

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

While SimpleDateFormat will indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating dates extensively in your projects it would probably be worth looking into.

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?

Round tripping dates through strings has always been a pain...but the docs to indicate that the 'o' specifier is the one to use for round tripping which captures the UTC state. When parsed the result will usually have Kind == Utc if the original was UTC. I've found that the best thing to do is always normalize dates to either UTC or local prior to serializing then instruct the parser on which normalization you've chosen.

DateTime now = DateTime.Now;
DateTime utcNow = now.ToUniversalTime();

string nowStr = now.ToString( "o" );
string utcNowStr = utcNow.ToString( "o" );

now = DateTime.Parse( nowStr );
utcNow = DateTime.Parse( nowStr, null, DateTimeStyles.AdjustToUniversal );

Debug.Assert( now == utcNow );

Converting a Java Keystore into PEM Format

The keytool command will not allow you to export the private key from a key store. You have to write some Java code to do this. Open the key store, get the key you need, and save it to a file in PKCS #8 format. Save the associated certificate too.

KeyStore ks = KeyStore.getInstance("jks");
/* Load the key store. */
char[] password = ...;
/* Save the private key. */
FileOutputStream kos = new FileOutputStream("tmpkey.der");
Key pvt = ks.getKey("your_alias", password);
/* Save the certificate. */
FileOutputStream cos = new FileOutputStream("tmpcert.der");
Certificate pub = ks.getCertificate("your_alias");

Use OpenSSL utilities to convert these files (which are in binary format) to PEM format.

openssl pkcs8 -inform der -nocrypt < tmpkey.der > tmpkey.pem
openssl x509 -inform der < tmpcert.der > tmpcert.pem

Plotting with C#

See Samples Environment for Microsoft Chart Controls:

The samples environment for Microsoft Chart Controls for .NET Framework contains over 200 samples for both ASP.NET and Windows Forms. The samples cover every major feature in Chart Controls for .NET Framework. They enable you to see the Chart controls in action as well as use the code as templates for your own web and windows applications.

Seems to be more business oriented, but may be of some value to science students and scientists.

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

You shouldn't have to care that much. RFC 3339, according to itself, is a set of standards derived from ISO 8601. There's quite a few minute differences though, and they're all outlined in RFC 3339. I could go through them all here, but you'd probably do better just reading the document for yourself in the event you're worried:

How to use unicode characters in Windows command line?

A quick decision for .bat files if you computer displays your path/file name correct when you typing it in DOS-window:

  1. copy con temp.txt [press Enter]
  2. Type the path/file name [press Enter]
  3. Press Ctrl-Z [press Enter]

This way you create a .txt file - temp.txt. Open it in Notepad, copy the text (don't worry it will look unreadable) and paste it in your .bat file. Executing the .bat created this way in DOS-window worked for m? (Cyrillic, Bulgarian).

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

In case you're like me and are too lazy or in a hurry and don't want to download additional software, you can use It's very straight forward and supports several highlight themes and many programming languages. my case I was using Visual Studio Code, which doesn't allow copying with format due to CSS involved in styling (as reported here).

Copy the text from the Preview box and then in Word go to Insert -> Textbox, paste the Preview from the website, highlight all the text, and then disable spell checking for that textbox.

This is what the code looks like finally.code as seen in Word

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

You could use a Mixin.

/// <summary>
/// Adds "mixins" to the Boolean class.
/// </summary>
public static class BooleanMixins
    /// <summary>
    /// Converts the value of this instance to its equivalent string representation (either "Yes" or "No").
    /// </summary>
    /// <param name="boolean"></param>
    /// <returns>string</returns>
    public static string ToYesNoString(this Boolean boolean)
        return boolean ? "Yes" : "No";

Sql Server string to date conversion

convert string to datetime in MSSQL implicitly

create table tmp 

insert into tmp (ENTRYDATETIME) values (getdate());
insert into tmp (ENTRYDATETIME) values ('20190101');  --convert string 'yyyymmdd' to datetime

select * from tmp where ENTRYDATETIME > '20190925'  --yyyymmdd 
select * from tmp where ENTRYDATETIME > '20190925 12:11:09.555'--yyyymmdd HH:MIN:SS:MS

Custom Date/Time formatting in SQL Server

Not answering your question specifically, but isn't that something that should be handled by the presentation layer of your application. Doing it the way you describe creates extra processing on the database end as well as adding extra network traffic (assuming the database exists on a different machine than the application), for something that could be easily computed on the application side, with more rich date processing libraries, as well as being more language agnostic, especially in the case of your first example which contains the abbreviated month name. Anyway the answers others give you should point you in the right direction if you still decide to go this route.

Excel CSV - Number cell format

There isn’t an easy way to control the formatting Excel applies when opening a .csv file. However listed below are three approaches that might help.

My preference is the first option.

Option 1 – Change the data in the file

You could change the data in the .csv file as follows ...,=”005”,... This will be displayed in Excel as ...,005,...

Excel will have kept the data as a formula, but copying the column and using paste special values will get rid of the formula but retain the formatting

Option 2 – Format the data

If it is simply a format issue and all your data in that column has a three digits length. Then open the data in Excel and then format the column containing the data with this custom format 000

Option 3 – Change the file extension to .dif (Data interchange format)

Change the file extension and use the file import wizard to control the formats. Files with a .dif extension are automatically opened by Excel when double clicked on.

Step by step:

  • Change the file extension from .csv to .dif
  • Double click on the file to open it in Excel.
  • The 'File Import Wizard' will be launched.
  • Set the 'File type' to 'Delimited' and click on the 'Next' button.
  • Under Delimiters, tick 'Comma' and click on the 'Next' button.
  • Click on each column of your data that is displayed and select a 'Column data format'. The column with the value '005' should be formatted as 'Text'.
  • Click on the finish button, the file will be opened by Excel with the formats that you have specified.

How do you perform address validation?

Here's a free and sort of "outside the box" way to do it. Not 100% perfect, but it should reject blatantly non-existent addresses.

Submit the entire address to Google's geocoding web service. This service attempts to return the exact coordinates of the location you feed it, i.e. latitude and longitude.

In my experience if the address is invalid you will get a result of 602 from the service. There's definitely a possibility of false positives or false negatives, but used in conjunction with other consistency checks it could be useful.

(Yahoo's geocoding web service, on the other hand, will return the coordinates of the center of the town if the town exists but the rest of the address is bogus. Potentially useful as long as you pay close attention to the "precision" field in the result).

How to validate phone numbers using regex

Here's one that works well in JavaScript. It's in a string because that's what the Dojo widget was expecting.

It matches a 10 digit North America NANP number with optional extension. Spaces, dashes and periods are accepted delimiters.

"^(\\(?\\d\\d\\d\\)?)( |-|\\.)?\\d\\d\\d( |-|\\.)?\\d{4,4}(( |-|\\.)?[ext\\.]+ ?\\d+)?$"

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

It is interesting that custom format "yyyy-MM-ddTHH:mm:ssK" (without ms) is the quickest format method.

Also it is interesting that "S" format is slow on Classic and fast on Core...

Of course numbers are very close, between some rows difference is insignificant (tests with suffix _Verify are the same as those that are without that suffix, demonstrates results repeatability)

BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
  [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
  Clr    : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
  Core   : .NET Core 4.6.25009.03, 64bit RyuJIT

               Method |  Job | Runtime |       Mean |     Error |    StdDev |     Median |        Min |        Max | Rank |  Gen 0 | Allocated |
--------------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
           CustomDev1 |  Clr |     Clr | 1,089.0 ns | 22.179 ns | 20.746 ns | 1,079.9 ns | 1,068.9 ns | 1,133.2 ns |    8 | 0.1086 |     424 B |
           CustomDev2 |  Clr |     Clr | 1,032.3 ns | 19.897 ns | 21.289 ns | 1,024.7 ns | 1,000.3 ns | 1,072.0 ns |    7 | 0.1165 |     424 B |
     CustomDev2WithMS |  Clr |     Clr | 1,168.2 ns | 16.543 ns | 15.474 ns | 1,168.5 ns | 1,149.3 ns | 1,189.2 ns |   10 | 0.1625 |     592 B |
              FormatO |  Clr |     Clr | 1,563.7 ns | 31.244 ns | 54.721 ns | 1,532.5 ns | 1,497.8 ns | 1,703.5 ns |   14 | 0.2897 |     976 B |
              FormatS |  Clr |     Clr | 1,243.5 ns | 24.615 ns | 31.130 ns | 1,229.3 ns | 1,200.6 ns | 1,324.2 ns |   13 | 0.2865 |     984 B |
       FormatS_Verify |  Clr |     Clr | 1,217.6 ns | 11.486 ns | 10.744 ns | 1,216.2 ns | 1,205.5 ns | 1,244.3 ns |   12 | 0.2885 |     984 B |
        CustomFormatK |  Clr |     Clr |   912.2 ns | 17.915 ns | 18.398 ns |   916.6 ns |   878.3 ns |   934.1 ns |    4 | 0.0629 |     240 B |
 CustomFormatK_Verify |  Clr |     Clr |   894.0 ns |  3.877 ns |  3.626 ns |   893.8 ns |   885.1 ns |   900.0 ns |    3 | 0.0636 |     240 B |
           CustomDev1 | Core |    Core |   989.1 ns | 12.550 ns | 11.739 ns |   983.8 ns |   976.8 ns | 1,015.5 ns |    6 | 0.1101 |     423 B |
           CustomDev2 | Core |    Core |   964.3 ns | 18.826 ns | 23.809 ns |   954.1 ns |   935.5 ns | 1,015.6 ns |    5 | 0.1267 |     423 B |
     CustomDev2WithMS | Core |    Core | 1,136.0 ns | 21.914 ns | 27.714 ns | 1,138.1 ns | 1,099.9 ns | 1,200.2 ns |    9 | 0.1752 |     590 B |
              FormatO | Core |    Core | 1,201.5 ns | 16.262 ns | 15.211 ns | 1,202.3 ns | 1,178.2 ns | 1,225.5 ns |   11 | 0.0656 |     271 B |
              FormatS | Core |    Core |   993.5 ns | 19.272 ns | 24.372 ns |   999.4 ns |   954.2 ns | 1,029.5 ns |    6 | 0.0633 |     279 B |
       FormatS_Verify | Core |    Core | 1,003.1 ns | 17.577 ns | 16.442 ns | 1,009.2 ns |   976.1 ns | 1,024.3 ns |    6 | 0.0674 |     279 B |
        CustomFormatK | Core |    Core |   878.2 ns | 17.017 ns | 20.898 ns |   877.7 ns |   851.4 ns |   928.1 ns |    2 | 0.0555 |     215 B |
 CustomFormatK_Verify | Core |    Core |   863.6 ns |  3.968 ns |  3.712 ns |   863.0 ns |   858.6 ns |   870.8 ns |    1 | 0.0550 |     215 B |


    public class BenchmarkDateTimeFormat
        public static DateTime dateTime = DateTime.Now;

        public string CustomDev1()
            var d = dateTime.ToUniversalTime();
            var sb = new StringBuilder(20);

            if (d.Month <= 9)
            if (d.Day <= 9)
            if (d.Hour <= 9)
            if (d.Minute <= 9)
            if (d.Second <= 9)
            var text = sb.ToString();
            return text;

        public string CustomDev2()
            var u = dateTime.ToUniversalTime();
            var sb = new StringBuilder(20);
            var y = u.Year;
            var d = u.Day;
            var M = u.Month;
            var h = u.Hour;
            var m = u.Minute;
            var s = u.Second;
            if (M <= 9)
            if (d <= 9)
            if (h <= 9)
            if (m <= 9)
            if (s <= 9)
            var text = sb.ToString();
            return text;

        public string CustomDev2WithMS()
            var u  = dateTime.ToUniversalTime();
            var sb = new StringBuilder(23);
            var y  = u.Year;
            var d  = u.Day;
            var M  = u.Month;
            var h  = u.Hour;
            var m  = u.Minute;
            var s  = u.Second;
            var ms = u.Millisecond;
            if (M <= 9)
            if (d <= 9)
            if (h <= 9)
            if (m <= 9)
            if (s <= 9)
            var text = sb.ToString();
            return text;
        public string FormatO()
            var text = dateTime.ToUniversalTime().ToString("o");
            return text;
        public string FormatS()
            var text = string.Concat(dateTime.ToUniversalTime().ToString("s"),"Z");
            return text;

        public string FormatS_Verify()
            var text = string.Concat(dateTime.ToUniversalTime().ToString("s"), "Z");
            return text;

        public string CustomFormatK()
            var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
            return text;

        public string CustomFormatK_Verify()
            var text = dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");
            return text;
    } was used

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

Does this include:

  • International numbers?
  • Extensions?
  • Other information besides the actual number (like "ask for bobby")?

If all of these are no, I would use a 10 char field and strip out all non-numeric data. If the first is a yes and the other two are no, I'd use two varchar(50) fields, one for the original input and one with all non-numeric data striped and used for indexing. If 2 or 3 are yes, I think I'd do two fields and some kind of crazy parser to determine what is extension or other data and deal with it appropriately. Of course you could avoid the 2nd column by doing something with the index where it strips out the extra characters when creating the index, but I'd just make a second column and probably do the stripping of characters with a trigger.

Update: to address the AJAX issue, it may not be as bad as you think. If this is realistically the main way anything is done to the table, store only the digits in a secondary column as I said, and then make the index for that column the clustered one.

What is the argument for printf that formats a long?

I think you mean:

unsigned long n;
printf("%lu", n);   // unsigned long


long n;
printf("%ld", n);   // signed long

What is the Difference Between Mercurial and Git?

The big difference is on Windows. Mercurial is supported natively, Git isn't. You can get very similar hosting to with (actually even better as you get a free private repository). I was using msysGit for a while but moved to Mercurial and been very happy with it.

Most Pythonic way to provide global configuration variables in

How about just using the built-in types like this:

config = {
    "mysql": {
        "user": "root",
        "pass": "secret",
        "tables": {
            "users": "tb_users"
        # etc

You'd access the values as follows:


If you are willing to sacrifice the potential to compute expressions inside your config tree, you could use YAML and end up with a more readable config file like this:

  - user: root
  - pass: secret
  - tables:
    - users: tb_users

and use a library like PyYAML to conventiently parse and access the config file

How to insert special characters into a database?

use mysql_real_escape_string

So what does mysql_real_escape_string do?

This PHP library function prepends backslashes to the following characters: \n, \r, \, \x00, \x1a, ‘ and “. The important part is that the single and double quotes are escaped, because these are the characters most likely to open up vulnerabilities.

Please inform yourself about sql_injection. You can use this link as a start

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here

Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

How to resolve : Can not find the tag library descriptor for ""

I will throw one more solution into the mix. I downloaded a sample app and it was crimping only on this taglib. Turns out it didn't care for the single quotes around the attributes.

<%@ taglib prefix='c' uri='' %>

Once I changed those and made sure jstl.jar was in the web app, i was good to go.

Remove Top Line of Text File with PowerShell

skip` didn't work, so my workaround is

$LinesCount = $(get-content $file).Count
get-content $file |
    select -Last $($LinesCount-1) | 
    set-content "$file-temp"
move "$file-temp" $file -Force

Updating Python on Mac

I recommend using pyenv to manage your local python versions (both 2.x and 3.x) instead of installing new versions directly with homebrew or building new python versions from source manually. Essentially, pyenv can do two key things for you:

  • Install different python versions under some directory. Doing pyenv install 3.8.1 will install python 3.8.1 under ~/.pyenv/versions/3.8.1.
  • Modify your shell environment (PATH) with shims so that when you do pyenv local 3.8.1, calling python will invoke the new interpreter instead of your system python.

MacOSX Specific Installation

The pyenv repo is pretty detailed on how to install for different systems and what it's actually doing, but here's the basic steps for mac:

  1. Install homebrew if you don't already have it and use it to install pyenv with brew install pyenv
  2. Once you have pyenv installed, update your .bash_profile file to include:
if command -v pyenv 1>/dev/null 2>&1; then
    eval "$(pyenv init -)"

Now install some python using pyenv and then switch to it with the pyenv local command (you can see all your versions with pyenv versions).

pyenv install 3.8.1 && pyenv local 3.8.1

Note: you may need to create a new shell or reload your bash_profile in your current shell for the pyenv initialization to do its thing (set up shims).

With this setup, you'll be able to keep your system macosx python and switch to whatever new version of python you want available through pyenv.

PL/SQL print out ref cursor returned by a stored procedure

Note: This code is untested

Define a record for your refCursor return type, call it rec. For example:

TYPE MyRec IS RECORD (col1 VARCHAR2(10), col2 VARCHAR2(20), ...);  --define the record
rec MyRec;        -- instantiate the record

Once you have the refcursor returned from your procedure, you can add the following code where your comments are now:

  FETCH refCursor INTO rec;

How to select/get drop down option in Selenium 2

This is the code to select value from the drop down

The value for selectlocator will be the xpath or name of dropdown box, and for optionLocator will have the value to be selected from the dropdown box.

public static boolean select(final String selectLocator,
        final String optionLocator) {
    try {
        for (int k = 0; k <= new Select(element(selectLocator))
                .getOptions().size() - 1; k++) {
        if (combo1.contains(optionLocator)) {
            new Select(element(selectLocator)).selectByValue(optionLocator);
            combocheck = element(selectLocator).getValue();
            combo = "";

            return true;
        } else {
            combo = "The Value " + optionLocator
                    + " Does Not Exist In The Combobox";
            return false;
    } catch (Exception e) {
        return false;

private static RenderedWebElement element(final String locator) {
    try {

        return (RenderedWebElement) drivers.findElement(by(locator));
    } catch (Exception e) {
        return (RenderedWebElement) drivers.findElement(by(locator));



Failed to connect to mailserver at "localhost" port 25

Change SMTP=localhost to

Check if string ends with one of the strings from a list

I just came across this, while looking for something else.

I would recommend to go with the methods in the os package. This is because you can make it more general, compensating for any weird case.

You can do something like:

import os

the_file = 'aaaa/bbbb/ccc.ddd'

extensions_list = ['ddd', 'eee', 'fff']

if os.path.splitext(the_file)[-1] in extensions_list:
    # Do your thing.

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 


<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>


<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>


<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>


<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>


<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :


<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>


<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>


<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

What are alternatives to document.write?

The question depends on what you are actually trying to do.

Usually, instead of doing document.write you can use someElement.innerHTML or better, document.createElement with an someElement.appendChild.

You can also consider using a library like jQuery and using the modification functions in there:

display html page with node.js

If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.

at the command line

:\> cd <path you wish your server to reside>
:\> npm install connect

Then in a file (I named) Server.js

var connect = require('connect'),
   http = require('http');


:\>node Server.js


If you don't want to display the directory contents, exclude the .use( line.

So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.

If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.

Update 1/28/2014:

I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.

End Update

Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.

Commands I used (for better or worse):

Create a new file called node

:\>gedit /usr/local/bin/node
exec /nodejs "$@"

sudo chmod -x /usr/local/bin/node

That ought to make

node Server.js 

work just fine

TypeScript enum to object array

Here's the simple function with correct typing I use

 * Helper to produce an array of enum values.
 * @param enumeration Enumeration object.
export function enumToArray<T, G extends keyof T = keyof T>(enumeration: T): T[G][] {
  // tslint:disable: comment-format

  // enum Colors {
  //   WHITE = 0,
  //   BLACK = 1,
  // }
  // Object.values(Colors) will produce ['WHITE', 'BLACK', 0, 1]

  // So, simply slice the second half
  const enumValues = Object.values(enumeration);
  return enumValues.slice(enumValues.length / 2, enumValues.length) as T[G][];

Usage example:

enum Colors {
  Red = 1,
  Blue = 2,

Explain the "setUp" and "tearDown" Python methods used in test cases

Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.

setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

Generally, bash works better than python only in those environments where python is not available. :)

Seriously, I have to deal with both languages daily, and will take python instantly over bash if given the choice. Alas, I am forced to use bash on certain "small" platforms because someone has (mistakenly, IMHO) decided that python is "too large" to fit.

While it is true that bash might be faster than python for some select tasks, it can never be as quick to develop with, or as easy to maintain (at least after you get past 10 lines of code or so). Bash's sole strong point wrt python or ruby or lua, etc., is its ubiquity.

What's the difference between TRUNCATE and DELETE in SQL

"Truncate doesn't log anything" is correct. I'd go further:

Truncate is not executed in the context of a transaction.

The speed advantage of truncate over delete should be obvious. That advantage ranges from trivial to enormous, depending on your situation.

However, I've seen truncate unintentionally break referential integrity, and violate other constraints. The power that you gain by modifying data outside a transaction has to be balanced against the responsibility that you inherit when you walk the tightrope without a net.

Disabling swap files creation in vim

For anyone trying to set this for Rails projects, add

set directory=tmp,/tmp

into your


So the .swp files will be in their natural location - the tmp directory (per project).

Jenkins: Failed to connect to repository

Let me add here that one very minor issue that could generate this type of error is the missing .git extension in the repository URL. Ensure you enter the fully qualified URL ending with .git. I use bitbucket so what I do do is do click 'clone' and the fully qualified URL is automatically generated for me. There is a similar approach with github.

How do I analyze a program's core dump file with GDB when it has command-line parameters?

Just skip the parameters. GDB doesn't need them:

gdb ./exe

jQuery: Handle fallback for failed AJAX Request

I believe that what you are looking for is error option for the jquery ajax object

getJSON is a wrapper to the $.ajax object, but it doesn't provide you with access to the error option.

EDIT: dcneiner has given a good example of the code you would need to use. (Even before I could post my reply)

C# "must declare a body because it is not marked abstract, extern, or partial"

You DO NOT have to provide a body for getters and setters IF you'd like the automated compiler to provide a basic implementation.

This DOES however require you to make sure you're using the v3.5 compiler by updating your web.config to something like

   <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
    <providerOption name="CompilerVersion" value="v3.5"/>
    <providerOption name="WarnAsError" value="false"/>

How to include !important in jquery

It is also possible to add more important properties:

inputObj.attr('style', 'color:black !important; background-color:#428bca !important;');

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=

Is there a System.Web.WebPages.Razor.dll in the bin folder of your web app? What is its version? (Explorer right click, properties) I'm guessing it's not Just get the nuget packages for v3.0.0.0, perhaps by copying the packages folder from your colleague. Or install it manually:

EDIT: if you copy stuff from your colleague, also copy the relevant version numbers into packages.config. This is what tells nuget which versions to put into the packages folder.

What is the difference between x86 and x64

x86 is a 32 bit instruction set, x86_64 is a 64 bit instruction set... the difference is simple architecture. in case of windows os you better use the x86/32bit version for compatibility issues. in case of Linux you will not be able to use a 64 bit s/w if the os does not have the long mode flag.

Whatever I recommend if you have a windows 7 32 bit OS then go for 32bit or x86 binaries and as for Ubuntu 12.04 use command uname -a or grep lm /proc/cpuinfo (grep lm /proc/cpuinfo does not return value for 32 bit as 32 bit os does not has the cpuinfo flag) to know the architecture OS your OS then use the binaries according to your OS.

** Note. Remember you can always install 64 bit os in 32 bit system as long as it supports enhanced 64 bit.. 64 bit os works better some times for multi purpose work and also supports more ram than 32bits. also you can install 32bit s/w in 64 bit os..

** OS = Operating system.

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

Just select all of the files you want to compare, then open the context menu (Right-Click on the file) and choose Compare With, Then select each other..

Entity Framework Timeouts

For Entity framework 6 I use this annotation and works fine.

  public partial class MyDbContext : DbContext
      private const int TimeoutDuration = 300;

      public MyDbContext ()
          : base("name=Model1")
          this.Database.CommandTimeout = TimeoutDuration;
       // Some other codes

The CommandTimeout parameter is a nullable integer that set timeout values as seconds, if you set null or don't set it will use default value of provider you use.

How to escape special characters of a string with single backslashes

Utilize the output of built-in repr to deal with \r\n\t and process the output of re.escape is what you want:

re.escape(repr(a)[1:-1]).replace('\\\\', '\\')

How to generate a unique hash code for string input in android...?

I use this i tested it as key from my EhCacheManager Memory map ....

Its cleaner i suppose

     * Return Hash256 of String value
     * @param text
     * @return 
    public static String getHash256(String text) {
        try {
            return org.apache.commons.codec.digest.DigestUtils.sha256Hex(text);
        } catch (Exception ex) {
            Logger.getLogger(HashUtil.class.getName()).log(Level.SEVERE, null, ex);
            return "";

am using maven but this is the jar commons-codec-1.9.jar

Get all rows from SQLite

Update queueAll() method as below:

public Cursor queueAll() {

     String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
     Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);

     return cursor;

Update readFileFromSQLite() method as below:

public ArrayList<String> readFileFromSQLite() {

    fileName = new ArrayList<String>();

    fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);

    cursor = fileSQLiteAdapter.queueAll();

    if (cursor != null) {
        if (cursor.moveToFirst()) {
                String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
            } while (cursor.moveToNext());


    return fileName;

Get checkbox values using checkbox name using jquery

$('[name="CheckboxName"]:checked').each(function () {
    // do stuff

fastest MD5 Implementation in JavaScript

js-md5 supports UTF-8 string, array, ArrayBuffer, AMD....

and fast. jsperf

How to get the last element of a slice?

For just reading the last element of a slice:


For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

Decode HTML entities in Python string?

Beautiful Soup 4 allows you to set a formatter to your output

If you pass in formatter=None, Beautiful Soup will not modify strings at all on output. This is the fastest option, but it may lead to Beautiful Soup generating invalid HTML/XML, as in these examples:

# <html>
#  <body>
#   <p>
#    Il a dit <<Sacré bleu!>>
#   </p>
#  </body>
# </html>

link_soup = BeautifulSoup('<a href="">A link</a>')
# <a href="">A link</a>

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

Good question.

  • @@IDENTITY: returns the last identity value generated on your SQL connection (SPID). Most of the time it will be what you want, but sometimes it isn't (like when a trigger is fired in response to an INSERT, and the trigger executes another INSERT statement).

  • SCOPE_IDENTITY(): returns the last identity value generated in the current scope (i.e. stored procedure, trigger, function, etc).

  • IDENT_CURRENT(): returns the last identity value for a specific table. Don't use this to get the identity value from an INSERT, it's subject to race conditions (i.e. multiple connections inserting rows on the same table).

  • IDENTITY(): used when declaring a column in a table as an identity column.

For more reference, see:

To summarize: if you are inserting rows, and you want to know the value of the identity column for the row you just inserted, always use SCOPE_IDENTITY().

What is the difference between an expression and a statement in Python?

Expressions always evaluate to a value, statements don't.


variable declaration and assignment are statements because they do not return a value

const list = [1,2,3];

Here we have two operands - a variable 'sum' on the left and an expression on the right. The whole thing is a statement, but the bit on the right is an expression as that piece of code returns a value.

const sum = list.reduce((a, b)=> a+ b, 0);  

Function calls, arithmetic and boolean operations are good examples of expressions.

Expressions are often part of a statement.

The distinction between the two is often required to indicate whether we require a pice of code to return a value.

How to add a class to a given element?

In YUI, if you include yuidom, you can use



How can I merge two MySQL tables?

You can also try:

  INTO table_1 
  FROM table_2

which allows those rows in table_1 to supersede those in table_2 that have a matching primary key, while still inserting rows with new primary keys.


   INTO table_1
   FROM table_2

will update those rows already in table_1 with the corresponding row from table_2, while inserting rows with new primary keys.

Adding options to select with javascript

Often you have an array of related records, I find it easy and fairly declarative to fill select this way:

selectEl.innerHTML = => '<option value="''">''</option>').join('');

This will replace existing options.
You can use selectEl.insertAdjacentHTML('afterbegin', str); to add them to the top instead.
And selectEl.insertAdjacentHTML('beforeend', str); to add them to the bottom of the list.

IE11 compatible syntax: (c) { return '<option value="''">''</option>'; }).join('');

Disable browser 'Save Password' functionality

I have a work around, which may help.

You could make a custom font hack. So, make a custom font, with all the characters as a dot / circle / star for example. Use this as a custom font for your website. Check how to do this in inkscape: how to make your own font

Then on your log in form use:

<form autocomplete='off'  ...>
   <input type="text" name="email" ...>
   <input type="text" name="password" class="password" autocomplete='off' ...>
   <input type=submit>

Then add your css:

@font-face {
    font-family: 'myCustomfont';
    src: url('myCustomfont.eot');
    src: url('myCustomfont?#iefix') format('embedded-opentype'),
         url('myCustomfont.woff') format('woff'),
         url('myCustomfont.ttf') format('truetype'),
         url('myCustomfont.svg#myCustomfont') format('svg');
    font-weight: normal;
    font-style: normal;

.password {

Pretty cross browser compatible. I have tried IE6+, FF, Safari and Chrome. Just make sure that the oet font that you convert does not get corrupted. Hope it helps?

Better way to call javascript function in a tag

Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.

Both of your suggestions break with CSP enabled because they allow inline Javascript (which could be injected by a hacker) to execute in your page.

The best practice is to subscribe to the event in Javascript, as in Konrad Rudolph's answer.

Moving uncommitted changes to a new branch

Just create a new branch:

git checkout -b newBranch

And if you do git status you'll see that the state of the code hasn't changed and you can commit it to the new branch.

Simple (I think) Horizontal Line in WPF?

For anyone else struggling with this: Qwertie's comment worked well for me.

<Border Width="1" Margin="2" Background="#8888"/>

This creates a vertical seperator which you can talior to suit your needs.

How do I get the App version and build number using Swift?


Updated for Swift 4.2

let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String


As pointed out by @azdev on the new version of Xcode you will get a compile error for trying my previous solution, to solve this just edit it as suggested to unwrap the bundle dictionary using a !

let nsObject: AnyObject? = Bundle.main.infoDictionary!["CFBundleShortVersionString"]

End Edit

Just use the same logic than in Objective-C but with some small changes

//First get the nsObject by defining as an optional anyObject
let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary["CFBundleShortVersionString"]

//Then just cast the object as a String, but be careful, you may want to double check for nil
let version = nsObject as! String

I hope this helps you out.


Role/Purpose of ContextLoaderListener in Spring?

ContextLoaderListener is optional. Just to make a point here: you can boot up a Spring application without ever configuring ContextLoaderListener, just a basic minimum web.xml with DispatcherServlet.

Here is what it would look like:


<?xml version="1.0" encoding="UTF-8"?>
  <display-name>Some Minimal Webapp</display-name>



Create a file called dispatcher-servlet.xml and store it under WEB-INF. Since we mentioned index.jsp in welcome list, add this file under WEB-INF.


In the dispatcher-servlet.xml define your beans:

<?xml version="1.0" encoding="UTF-8"?>
    xsi:schemaLocation="        ">

    <bean id="bean1">
    <bean id="bean2">

    <context:component-scan base-package="com.example" />
    <!-- Import your other configuration files too -->
    <import resource="other-configs.xml"/>
    <import resource="some-other-config.xml"/>

    <!-- View Resolver -->
          value="org.springframework.web.servlet.view.JstlView" />
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />

How do I set the value property in AngularJS' ng-options?

The correct answer to this question has been provided by user frm.adiputra, as currently this seems to be the only way to explicitly control the value attribute of the option elements.

However, I just wanted to emphasize that "select" is not a keyword in this context, but it is just a placeholder for an expression. Please refer to the following list, for the definition of the "select" expression as well as other expressions that can be used in ng-options directive.

The use of select as it is depicted in the question:

ng-options='select p.text for p  in resultOptions'

is essentially wrong.

Based on the list of expressions, it seems that trackexpr may be used to specify the value, when options are given in an array of objects, but it has been used with grouping only.

From AngularJS' documentation for ng-options:

  • array / object: an expression which evaluates to an array / object to iterate over.
  • value: local variable which will refer to each item in the array or each property value of object during iteration.
  • key: local variable which will refer to a property name in object during iteration.
  • label: The result of this expression will be the label for element. The expression will most likely refer to the value variable (e.g. value.propertyName).
  • select: The result of this expression will be bound to the model of the parent element. If not specified, select expression will default to value.
  • group: The result of this expression will be used to group options using the DOM element.
  • trackexpr: Used when working with an array of objects. The result of this expression will be used to identify the objects in the array. The trackexpr will most likely refer to the value variable (e.g. value.propertyName).

Add list to set?

Sets can't have mutable (changeable) elements/members. A list, being mutable, cannot be a member of a set.

As sets are mutable, you cannot have a set of sets! You can have a set of frozensets though.

(The same kind of "mutability requirement" applies to the keys of a dict.)

Other answers have already given you code, I hope this gives a bit of insight. I'm hoping Alex Martelli will answer with even more details.

Ruby: character to ascii from a string

Ruby String provides the codepoints method after 1.9.1.

str = 'hello world'
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] 

str = "????"
=> [20320, 22909, 19990, 30028]

How to make the overflow CSS property work with hidden as value

Ok if anyone else is having this problem this may be your answer:

If you are trying to hide absolute positioned elements make sure the container of those absolute positioned elements is relatively positioned.

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

If System.IO.File.Exists(FilePath) Then
    MsgBox("The file exists")
    MsgBox("the file doesn't exist")
End If

How to pass a view's onClick event to its parent on Android?

If you want to both OnTouch and OnClick listener to parent and child view both, please use below trick:

  1. User ScrollView as a Parent view and inside that placed your child view inside Relative/LinearLayout.

  2. Make Parent ScrollView android:fillViewport="true" so View not be scrolled.

  3. Then set OnTouch listener to parent and OnClick listener to Child views. And enjoy both listener callbacks.

Is there a way to crack the password on an Excel VBA Project?

I tried some of solutions above and none of them works for me (excel 2007 xlsm file). Then i found another solution that even retrieve password, not just crack it.

Insert this code into module, run it and give it some time. It will recover your password by brute force.

Sub PasswordBreaker()

'Breaks worksheet password protection.

Dim i As Integer, j As Integer, k As Integer
Dim l As Integer, m As Integer, n As Integer
Dim i1 As Integer, i2 As Integer, i3 As Integer
Dim i4 As Integer, i5 As Integer, i6 As Integer
On Error Resume Next
For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _
Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
If ActiveSheet.ProtectContents = False Then
MsgBox "One usable password is " & Chr(i) & Chr(j) & _
Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
Exit Sub
End If
Next: Next: Next: Next: Next: Next
Next: Next: Next: Next: Next: Next
End Sub

TypeError: unhashable type: 'dict', when dict used as a key for another dict

What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.

Adding a leading zero to some values in column in MySQL

I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):

UPDATE table SET phone_num = concat('0', phone_num) 

I just concated 0 in front of the phone_num.

Split / Explode a column of dictionaries into separate columns with pandas

I know the question is quite old, but I got here searching for answers. There is actually a better (and faster) way now of doing this using json_normalize:

import pandas as pd

df2 = pd.json_normalize(df['Pollutant Levels'])

This avoids costly apply functions...

successful/fail message pop up box after submit?

You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.

Also, remove the onclick="alert()" from your submit. This is the cause for your first undefined message.

  $posted = false;
  if( $_POST ) {
    $posted = true;

    // Database stuff here...
    // $result = mysql_query( ... )
    $result = $_POST['name'] == "danny"; // Dummy result


    if( $posted ) {
      if( $result ) 
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
        echo "<script type='text/javascript'>alert('failed!')</script>";
    <form action="" method="post">
      Name:<input type="text" id="name" name="name"/>
      <input type="submit" value="submit" name="submit"/>

How to Implement DOM Data Binding in JavaScript

Yesterday, I started to write my own way to bind data.

It's very funny to play with it.

I think it's beautiful and very useful. At least on my tests using firefox and chrome, Edge must works too. Not sure about others, but if they support Proxy, I think it will work.

<H1>Bind Context 1</H1>
<input id='a' data-bind='data.test' placeholder='Button Text' />
<input id='b' data-bind='data.test' placeholder='Button Text' />
<input type=button id='c' data-bind='data.test' />
<H1>Bind Context 2</H1>
<input id='d' data-bind='data.otherTest' placeholder='input bind' />
<input id='e' data-bind='data.otherTest' placeholder='input bind' />
<input id='f' data-bind='data.test' placeholder='button 2 text - same var name, other context' />
<input type=button id='g' data-bind='data.test' value='click here!' />
<H1>No bind data</H1>
<input id='h' placeholder='not bound' />
<input id='i' placeholder='not bound'/>
<input type=button id='j' />

Here is the code:

    if ( ! ( 'SmartBind' in window ) ) { // never run more than once
        // This hack sets a "proxy" property for HTMLInputElement.value set property
        var nativeHTMLInputElementValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
        var newDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
        newDescriptor.set=function( value ){
            if ( 'settingDomBind' in this )
            var hasDataBind=this.hasAttribute('data-bind');
            if ( hasDataBind ) {
                var dataBind=this.getAttribute('data-bind');
                if ( ! this.hasAttribute('data-bind-context-id') ) {
                    console.error("Impossible to recover data-bind-context-id attribute", this, dataBind );
                } else {
                    var bindContextId=this.getAttribute('data-bind-context-id');
                    if ( bindContextId in SmartBind.contexts ) {
                        var bindContext=SmartBind.contexts[bindContextId];
                        var dataTarget=SmartBind.getDataTarget(bindContext, dataBind);
                        SmartBind.setDataValue( dataTarget, value);
                    } else {
                        console.error( "Invalid data-bind-context-id attribute", this, dataBind, bindContextId );
                delete this.settingDomBind;
            nativeHTMLInputElementValue.set.bind(this)( value );
        Object.defineProperty(HTMLInputElement.prototype, 'value', newDescriptor);

    var uid= function(){
           return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
               var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
               return v.toString(16);

        // SmartBind Functions
            var _data={};
            var ctx = {
                "id" : uid()    /* Data Bind Context Id */
                , "_data": _data        /* Real data object */
                , "mapDom": {}          /* DOM Mapped objects */
                , "mapDataTarget": {}       /* Data Mapped objects */
   Proxy( _data, SmartBind.getProxyHandler(ctx, "data"))  /* Proxy object to _data */
            return ctx;

        SmartBind.getDataTarget=function(bindContext, bindPath){
            var bindedObject=
                { bindContext: bindContext
                , bindPath: bindPath 
            var dataObj=bindContext;
            var dataObjLevels=bindPath.split('.');
            for( var i=0; i<dataObjLevels.length; i++ ) {
                if ( i == dataObjLevels.length-1 ) { // last level, set value
                    bindedObject={ target: dataObj
                    , item: dataObjLevels[i]
                } else {    // digg in
                    if ( ! ( dataObjLevels[i] in dataObj ) ) {
                        console.warn("Impossible to get data target object to map bind.", bindPath, bindContext);
            return bindedObject ;

        SmartBind.add=function(bindContext, domObj){
            if ( typeof domObj == "undefined" ){
                console.error("No DOM Object argument given ", bindContext);
            if ( ! domObj.hasAttribute('data-bind') ) {
                console.warn("Object has no data-bind attribute", domObj);
            var bindPath=domObj.getAttribute('data-bind');
            if ( bindPath in bindContext.mapDom ) {
            } else {
            var bindTarget=SmartBind.getDataTarget(bindContext, bindPath);
            domObj.addEventListener('input', function(){ SmartBind.setDataValue(bindTarget,this.value); } );
            domObj.addEventListener('change', function(){ SmartBind.setDataValue(bindTarget, this.value); } );

            if ( ! ( 'target' in bindTarget ) ) {
                var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
                if ( 'target' in lBindTarget ) {
                } else {
                    console.warn("Still can't recover the object to bind", bindTarget.bindPath );
            if ( ( 'target' in bindTarget ) ) {
            if ( ! ( 'target' in bindTarget ) ) {
                var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
                if ( 'target' in lBindTarget ) {
                } else {
                    console.warn("Still can't recover the object to bind", bindTarget.bindPath );
            if ( ( 'target' in bindTarget ) ) {
        SmartBind.getProxyHandler=function(bindContext, bindPath){
            return  {
                get: function(target, name){
                    if ( name == '__isProxy' )
                        return true;
                    // just get the value
                    // console.debug("proxy get", bindPath, name, target[name]);
                    return target[name];
                set: function(target, name, value){
                    SmartBind.processBindToDom(bindContext, bindPath+"."+name);
                    // console.debug("proxy set", bindPath, name, target[name], value );
                    // and set all related objects with this
                    if ( value instanceof Object) {
                        if ( !( name in target) || ! ( target[name].__isProxy ) ){
                            target[name]=new Proxy(value, SmartBind.getProxyHandler(bindContext, bindPath+'.'+name));
                        // run all tree to set proxies when necessary
                        var objKeys=Object.keys(value);
                        // console.debug("...objkeys",objKeys);
                        for ( var i=0; i<objKeys.length; i++ ) {
                            if ( typeof value[objKeys[i]] == 'undefined' || value[objKeys[i]] == null || ! ( value[objKeys[i]] instanceof Object ) || value[objKeys[i]].__isProxy )
                            target[name][objKeys[i]]=new Proxy( value[objKeys[i]], SmartBind.getProxyHandler(bindContext, bindPath+'.'+name+"."+objKeys[i]));
                        // TODO it can be faster than run all items
                        var bindKeys=Object.keys(bindContext.mapDom);
                        for ( var i=0; i<bindKeys.length; i++ ) {
                            // console.log("test...", bindKeys[i], " for ", bindPath+"."+name);
                            if ( bindKeys[i].startsWith(bindPath+"."+name) ) {
                                // console.log("its ok, lets update dom...", bindKeys[i]);
                                SmartBind.processBindToDom( bindContext, bindKeys[i] );
                    return true;
        SmartBind.processBindToDom=function(bindContext, bindPath) {
            var domList=bindContext.mapDom[bindPath];
            if ( typeof domList != 'undefined' ) {
                try {
                    for ( var i=0; i < domList.length ; i++){
                        var dataTarget=SmartBind.getDataTarget(bindContext, bindPath);
                        if ( 'target' in dataTarget )
                            console.warn("Could not get data target", bindContext, bindPath);
                } catch (e){
                    console.warn("bind fail", bindPath, bindContext, e);

Then, to set, just:

var bindContext=SmartBind.BindContext();
SmartBind.add(bindContext, document.getElementById('a'));
SmartBind.add(bindContext, document.getElementById('b'));
SmartBind.add(bindContext, document.getElementById('c'));

var bindContext2=SmartBind.BindContext();
SmartBind.add(bindContext2, document.getElementById('d'));
SmartBind.add(bindContext2, document.getElementById('e'));
SmartBind.add(bindContext2, document.getElementById('f'));
SmartBind.add(bindContext2, document.getElementById('g'));

setTimeout( function() {
    document.getElementById('b').value='Via Script works too!'
}, 2000);

document.getElementById('g').addEventListener('click',function(){'Set by js value'

For now, I've just added the HTMLInputElement value bind.

Let me know if you know how to improve it.

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

Go to phpMyAdmin Directory of your Localhost Software Like Xampp, Mamp or others. Then change the host from localhost to and change the port to 3307 . After that go to your data directory and delete all error log files except ibdata1 which is important file to hold your created database table link. Finaly restart mysql.I think your problem will be solved.

Add legend to ggplot2 line plot

Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.

Start with a subset of the original data:

datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600, 
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000, 
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct", 
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44, 
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88, 
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73, 
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97, 
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax", 
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")

You can get the desired effect by (and this also cleans up the original plotting code):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
                      breaks = c("TempMax", "TempMedia", "TempMin"),
                      values = c("red", "green", "blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 

The idea is that each line is given a color by mapping the colour aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes call; you are creating a mapping to this "variable".

scale_colour_manual can now map these strings to the appropriate colors. The result is enter image description here

In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 

(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
                      breaks = c("TempMedia", "TempMax", "TempMin"),
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 

1 = false and 0 = true?

It is common for comparison functions to return 0 on "equals", so that they can also return a negative number for "less than" and a positive number for "greater than". strcmp() and memcmp() work like this.

It is, however, idiomatic for zero to be false and nonzero to be true, because this is how the C flow control and logical boolean operators work. So it might be that the return values chosen for this function are fine, but it is the function's name that is in error (it should really just be called compare() or similar).

resize font to fit in a div (on one line)

This may be overkill for what you require, but I found this library to be very helpful:

It's only good for single lines though, so I'm not certain if that fits your requirement.

ListView inside ScrollView is not scrolling on Android

I know this question is asked long ago, but who ever is stuck for now can solve this by adding this line into your ListView


For Example -

                    android:nestedScrollingEnabled="true" />

How to use Git and Dropbox together?

Now in 2014, I have been using Git and Dropbox for about one year and a half without problem. Some points though:

  • All my machines using Dropbox are on Windows, different versions (7 to 8) + 1 mac.
  • I do not share the repository with someone else, so I am the only one to modify it.
  • git push pushes to a remote repository, so that if it ever gets corrupted, I can easily recover it.
  • I had to create aliases in C:\Users with mklink /D link target because some libraries were pointed to absolute locations.

Are parameters in strings.xml possible?

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

If you wish more look at:

Using RegEx in SQL Server

SELECT * from SOME_TABLE where NAME like '%[^A-Z]%'

Or some other expression instead of A-Z

How to determine the number of days in a month in SQL Server?

select add_months(trunc(sysdate,'MM'),1) -  trunc(sysdate,'MM') from dual;

Installing cmake with home-brew

  1. Download the latest CMake Mac binary distribution here: (current latest is:

  2. Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.

  3. Add this line to your .bashrc file: PATH="/Applications/":"$PATH"

  4. Reload your .bashrc file: source ~/.bashrc

  5. Verify the latest cmake version is installed: cmake --version

  6. You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.

How do I push to GitHub under a different username?

this, should work: git push origin local-name:remote-name

Better, for GitLab I use a second "origin", say "origin2":

git remote add origin2 ...

git push origin2 master

The conventional (short) git push should work implicitly as with the 1st "origin"

How to convert minutes to hours/minutes and add various time values together using jQuery?

I took the liberty of modifying ConorLuddy's answer to address both 24 hour time and 12 hour time.

function minutesToHHMM (mins, twentyFour = false) {
  let h = Math.floor(mins / 60);
  let m = mins % 60;
  m = m < 10 ? '0' + m : m;

  if (twentyFour) {
    h = h < 10 ? '0' + h : h;
    return `${h}:${m}`;
  } else {
    let a = 'am';
    if (h >= 12) a = 'pm';
    if (h > 12) h = h - 12;
    return `${h}:${m} ${a}`;

How to change the default message of the required field in the popover of form-control in bootstrap?

You can use setCustomValidity function when oninvalid event occurs.

Like below:-

<input class="form-control" type="email" required="" 
    placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">


To clear the message once you start entering use oninput="setCustomValidity('') attribute to clear the message.

<input class="form-control" type="email"  required="" placeholder="username"
 oninvalid="this.setCustomValidity('Please Enter valid email')"

C# Convert List<string> to Dictionary<string, string>

By using ToDictionary:

var dictionary = list.ToDictionary(s => s);

If it is possible that any string could be repeated, either do a Distinct call first on the list (to remove duplicates), or use ToLookup which allows for multiple values per key.

How to pass multiple values to single parameter in stored procedure


I have had this exact issue for almost 2 weeks, extremely frustrating but I FINALLY found this site and it was a clear walk-through of what to do.

I hope this helps people because it was exactly what I was looking for

Multiple controllers with AngularJS in single page app

I'm currently in the process of building a single page application. Here is what I have thus far that I believe would be answering your question. I have a base template (base.html) that has a div with the ng-view directive in it. This directive tells angular where to put the new content in. Note that I'm new to angularjs myself so I by no means am saying this is the best way to do it.

app = angular.module('myApp', []);                                                                             

app.config(function($routeProvider, $locationProvider) {                        
       .when('/home/', {                                            
         templateUrl: "templates/home.html",                                               
        .when('/about/', {                                       
            templateUrl: "templates/about.html",     
            controller: 'aboutController',  
            template: 'does not exists'   

app.controller('homeController', [              
    function homeController($scope,) {        
        $scope.message = 'HOME PAGE';                  

app.controller('aboutController', [                  
    function aboutController($scope) {        
        $scope.about = 'WE LOVE CODE';                       



    <div id="sideMenu">
        <!-- MENU CONTENT -->

    <div id="content" ng-view="">
        <!-- Angular view would show here -->


undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable:

call a function in success of datatable ajax call

  "success" : function(data){
       //do stuff here

Remove Select arrow on IE

In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before css to match yours.

In case if it is IE10 then using below css3 it is possible

select::-ms-expand {
    display: none;

However if you're interested in jQuery plugin, try Chosen.js or you can create your own in js.

base 64 encode and decode a string in angular (2+)

Use the btoa() function to encode:

console.log(btoa("password")); // cGFzc3dvcmQ=

To decode, you can use the atob() function:

console.log(atob("cGFzc3dvcmQ=")); // password

Spring data JPA query with parameter properties

This link will help you: Spring Data JPA M1 with SpEL expressions supported. The similar example would be:

@Query("select u from User u where u.firstname = :#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

Regex Letters, Numbers, Dashes, and Underscores

Your expression should already match dashes, because the final - will not be interpreted as a range operator (since the range has no end). To add underscores as well, try:


Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

Here is a manual way to invalidate the cache for all files on CloudFront via AWS

enter image description here

enter image description here

enter image description here

What does the exclamation mark do before the function?

It returns whether the statement can evaluate to false. eg:

!false      // true
!true       // false
!isValid()  // is not valid

You can use it twice to coerce a value to boolean:

!!1    // true
!!0    // false

So, to more directly answer your question:

var myVar = !function(){ return false; }();  // myVar contains true

Edit: It has the side effect of changing the function declaration to a function expression. E.g. the following code is not valid because it is interpreted as a function declaration that is missing the required identifier (or function name):

function () { return false; }();  // syntax error

Postgresql SELECT if string contains

You should use 'tag_name' outside of quotes; then its interpreted as a field of the record. Concatenate using '||' with the literal percent signs:

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || tag_name || '%';

Replace transparency in PNG images with white background

To actually remove the alpha channel from the file, use the alpha off option:

convert in.png -background white -alpha off out.png

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

My machine showed me a BIOS update and I wondered if that has something to do with the sudden popping-up of this error. And after I did the update, the error was resolved and the solution built fine.

How can I specify a local gem in my Gemfile?

You can also reference a local gem with git if you happen to be working on it.

gem 'foo',
  :git => '/Path/to/local/git/repo',
  :branch => 'my-feature-branch'

Then, if it changes I run

bundle exec gem uninstall foo
bundle update foo

But I am not sure everyone needs to run these two steps.

Sum rows in data.frame or matrix

The rowSums function (as Greg mentions) will do what you want, but you are mixing subsetting techniques in your answer, do not use "$" when using "[]", your code should look something more like:

data$new <- rowSums( data[,43:167] )

If you want to use a function other than sum, then look at ?apply for applying general functions accross rows or columns.

Browse and display files in a git repo without cloning

Git is distributed version control system, while Subversion is centralized (client-server) version control system. They work differently; get used to that. Please read my answer explaining the consequences of that difference to git equivalent of svn status -u question at StackOverflow.

Repeating myself a bit: in centralized version control system (like CVS or Subversion) almost all commands are processed on server, and involve network. Very few commands are performed locally. Note that to have good performance of "svn status" and "svn diff" Subversion stores 'pristine copy' of checked-out version on client, to not have to involve network transfer for those common operations (this means that Subversion checkout = 2 x size of working directory at least).

In distributed version control system (like Git, Mercurial or Bazaar), where you have local copy (clone) of a whole repository, almost all commands are performed on client. Very few commands require network connection to other repository (to server).

The number of command you can perform on server is limited.

  • You can list all references on remote with "git ls-remote <URL>".
  • You can get snapshot of (part) of repository (if remote server enabled it) with
    "git archive --remote=<URL> HEAD".
  • You can clone only a few last commits (so called "shallow clone") with
    "git clone --depth=1 <URL>".
  • If server provides git web interface to repository, you can use it to browse.

Programmatically Install Certificate into Mozilla

I was trying to achieve the same thing in Powershell and wrote a script to perform various functions that can be interactively selected. Of course, it's fairly easy to modify the script to automate certain things instead of provide options.

I'm an Infrastructure guy rather than a coder/programmer, so apologies if it's a bit cumbersome (but it does work!!).

Save the following as a PS1:

# NAME: RegisterFireFoxCertificates.ps1
# AUTHOR: Andy Pyne
# DATE  : 22.07.2015
# COMMENT: To provide options for listing, adding, deleting and purging
# FireFox Certificates using Mozilla's NSS Util CertUtil
# Source:
# NOTE: You need a copy of the NSS Util CertUtil and it's associated dll's
# The specific files I used were:
# certutil.exe, fort32.dll, freebl3.dll, libnspr4.dll, libplc4.dll, libplds4.dll, nspr4.dll, 
# nss3.dll, nssckbi.dll, nssdbm3.dll, nssutil3.dll, plc4.dll, plds4.dll, smime3.dll, 
# softokn3.dll, sqlite3.dll, ssl3.dll, swft32.dll


# Setup a few parameters
$ErrorActionPreference = "Silentlycontinue"
$ExecutionPolicyOriginal = Get-ExecutionPolicy
$FireFoxExecutable = "C:\Program Files (x86)\Mozilla Firefox\Firefox.exe" 

# This is the Firefox certificate database
$CertDB = "Cert8.db"

# The Certificate Nickname is a name you want to see on the certificates that you've imported in - so you know they were imported by this process
# However, when you look at the certificates in Firefox, they will be listed under whatever the certificate name was when it was generated
# So if your certificate is listed as 'Company123' when imported, it will still be called that as the Common Name, but when you click to view
# it, you will see that the first item in the Certificate Fields is what you 'nicknamed' it.
$CertificateNickname = "MyCompanyName FF AutoImport Cert"

# The Legacy Certificates are specific/explicit certificates which you wish to delete (The 'purge' option later in the script references these items)
$LegacyCertificates = @("OldCertificate1", "Company Cert XYZ", "Previous Company name", "Unwanted Certificate - 7", "123APTEST123")

# This is the list of databases / Firefox profiles on the machine
$FFDBList = @()

# Making sure our temporary directory is empty
$FFCertLocationLocal = "C:\FFCertTemp"

# The remote location of the certificates and 
$FFCertLocationRemote = "\\myUNC\NETLOGON\FireFoxCert\"

# The local CertUtil executable (this is copied from the remote location above)
$FFCertTool = "$FFCertLocationLocal\CertUtil.exe"

# Making sure our temporary directory is empty
Remove-Item $FFCertLocationLocal -Recurse
New-Item -ItemType Directory -Path $FFCertLocationLocal




# We're going to get a list of the Firefox processes on the machine that are open and close them
# Otherwise the add/delete parts might not be successful with Firefox still running
$FireFoxRunningProcessesList = Get-Process | Where-Object {$_.Name -Match "FireFox"} | Select-Object ProcessName,Id | Format-Table -AutoSize
$FireFoxRunningProcesses = Get-Process | Where-Object {$_.Name -Match "FireFox"} | Select-Object -ExpandProperty Id
If (!$FireFoxRunningProcesses) {}
Else {
Write-Host "The following processes will be stopped to perform certificate manipulation:"
$TerminateProcessQuestion = Read-Host "To auto-terminate (ungracefully!) processes, press 'Y', otherwise, press any other key"
If ($TerminateProcessQuestion -ne 'y') {
Write-Host "Cannot continue as Firefox process is still running, ending script ..."
Else {ForEach ($FireFoxRunningProcess in $FireFoxRunningProcesses) {
[Int]$FireFoxRunningProcess = [Convert]::ToInt32($FireFoxRunningProcess, 10)
Stop-Process -Id $FireFoxRunningProcess -Force}}



# The remote files (certificates and the NSS Tools CertUtil files are copied locally)
$FFCertificateListItemRemote = Get-ChildItem $FFCertLocationRemote -Recurse -Include *.cer,*.dll,certutil.exe
ForEach ($FFCertificateItemRemote in $FFCertificateListItemRemote) {
Copy-Item $FFCertificateItemRemote.FullName -Destination $FFCertLocationLocal}

# Get a list of the local certificates
$FFCertificateListLocal = Get-ChildItem $FFCertLocationLocal -Recurse -filter *.cer

Set-ExecutionPolicy "Unrestricted"

# Find all Firefox profiles and create an array called FFDBList
# Of course, you'll only be able to get to the ones your permissions allow
$LocalProfiles = Get-ChildItem "C:\Users" | Select-Object -ExpandProperty FullName
ForEach ($LocalProfile in $LocalProfiles) {
$FFProfile = Get-ChildItem "$LocalProfile\AppData\Roaming\Mozilla\Firefox\Profiles" | Select-Object -ExpandProperty FullName
If (!$FFProfile) {Write-Host "There is no Firefox Profile for $LocalProfile"}
ELSE {$FFDBList += $FFProfile}

Write-Host "#################################"
Write-Host "The List of FireFox Profiles is:"
Write-Host "#################################"



# Setup 4x functions (List, Delete, Add and Purge)
# - List will simply list certificates from the Firefox profiles
# - Delete will delete the certificates the same as the certificates you're going to add back in
#   So for example, if you have 2x certificates copied earlier for import, 'CompanyA' and 'CompanyZ'
#   then you can delete certificates with these names beforehand. This will prevent the 
#   certificates you want to import being skipped/duplicated because they already exist
# - Add will simply add the list of certificates you've copied locally
# - Purge will allow you to delete 'other' certificates that you've manually listed in the
#   variable '$LegacyCertificates' at the top of the script

# Each of the functions perform the same 4x basic steps
# 1) Do the following 3x things for each of the Firefox profiles
# 2) Do the 2x following things for each of the certificates
# 3) Generate an expression using parameters based on the certificate nickname specified
#    earlier, and the profile and certificate informaiton
# 4) Invoke the expression

Function ListCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
$FFCertificateListItemFull = $FFCertificateListItem.FullName
Write-Host "Listing Certificates for $FFDBitem"
$ExpressionToListCerts = "$FFCertTool -L -d `"$FFDBItem`""
Invoke-Expression $ExpressionToListCerts

Function DeleteOldCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
ForEach ($FFCertificateListItem in $FFCertificateListLocal) {
$FFCertificateListItemFull = $FFCertificateListItem.FullName
Write-Host "Deleting Cert $FFCertificateListItem for $FFDBitem"
$ExpressionToDeleteCerts = "$FFCertTool -D -n `"$CertificateNickname`" -d `"$FFDBItem`""
Invoke-Expression $ExpressionToDeleteCerts

Function AddCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
ForEach ($FFCertificateListItem in $FFCertificateListLocal) {
$FFCertificateListItemFull = $FFCertificateListItem.FullName
Write-Host "Adding $FFCertificateListItem Cert for $FFDBitem"
$ExpressionToAddCerts = "$FFCertTool -A -n `"$CertificateNickname`" -t `"CT,C,C`" -d `"$FFDBItem`" -i `"$FFCertificateListItemFull`""
Write-Host $ExpressionToAddCerts
Invoke-Expression $ExpressionToAddCerts

Function PurgeLegacyCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
ForEach ($LegacyCertificateItem in $LegacyCertificates) {
$LegacyCertificateItemFull = $LegacyCertificateItem.FullName
Write-Host "Purging Old Certs ($LegacyCertificateItem) for $FFDBitem"
#$ExpressionToDeleteLegacyCerts = "$FFCertTool -D -n `"$OldCertificate`" -d `"$FFDBItem`""
$ExpressionToDeleteLegacyCerts = "$FFCertTool -D -n `"$LegacyCertificateItem`" -d `"$FFDBItem`""
ForEach ($LegacyCertificate in $LegacyCertificates) {
Invoke-Expression $ExpressionToDeleteLegacyCerts}



    # Creating a few options to invoke the various functions created above

$CertificateAction = ""

Function CertificateActionSelection {
Do {
$CertificateAction = Read-Host "Would you like to [L]ist all certificates [D]elete all old certificates, [A]dd new certificates, or [P]urge legacy certificates?"
} Until ($CertificateAction -eq "L" -or $CertificateAction -eq "D" -or $CertificateAction -eq "A" -or $CertificateAction -eq "P" )

If ($CertificateAction -eq "L") {ListCertificates}
If ($CertificateAction -eq "D") {DeleteOldCertificates}
If ($CertificateAction -eq "A") {AddCertificates}
If ($CertificateAction -eq "P") {PurgeLegacyCertificates}

Do {
$MoreCertificateActions = Read-Host "Would you like to [L]aunch Firefox (as $env:USERNAME), take a [C]ertificate action, or [Q]uit?"
If ($MoreCertificateActions -eq "L") {
Invoke-Item $FireFoxExecutable
If ($MoreCertificateActions -eq "C") {CertificateActionSelection}

} Until ($MoreCertificateActions -eq "Q")

Remove-Item $FFCertLocationLocal -Recurse
Set-ExecutionPolicy $ExecutionPolicyOriginal


How to get the number of columns from a JDBC ResultSet?

After establising the connection and executing the query try this:

 ResultSet resultSet;
 int columnCount = resultSet.getMetaData().getColumnCount();
 System.out.println("column count : "+columnCount);

Use getElementById on HTMLElement instead of HTMLDocument

I don't like it either.

So use javascript:

Public Function GetJavaScriptResult(doc as HTMLDocument, jsString As String) As String

    Dim el As IHTMLElement
    Dim nd As HTMLDOMTextNode

    Set el = doc.createElement("INPUT")
        el.ID = GenerateRandomAlphaString(100)
    Loop Until Document.getElementById(el.ID) Is Nothing
    el.Style.display = "none"
    Set nd = Document.appendChild(el)

    doc.parentWindow.ExecScript "document.getElementById('" & el.ID & "').value = " & jsString

    GetJavaScriptResult = Document.getElementById(el.ID).Value

    Document.removeChild nd

End Function

Function GenerateRandomAlphaString(Length As Long) As String

    Dim i As Long
    Dim Result As String

    Randomize Timer

    For i = 1 To Length
        Result = Result & Chr(Int(Rnd(Timer) * 26 + 65 + Round(Rnd(Timer)) * 32))
    Next i

    GenerateRandomAlphaString = Result

End Function

Let me know if you have any problems with this; I've changed the context from a method to a function.

By the way, what version of IE are you using? I suspect you're on < IE8. If you upgrade to IE8 I presume it'll update shdocvw.dll to ieframe.dll and you will be able to use document.querySelector/All.


Comment response which isn't really a comment: Basically the way to do this in VBA is to traverse the child nodes. The problem is you don't get the correct return types. You could fix this by making your own classes that (separately) implement IHTMLElement and IHTMLElementCollection; but that's WAY too much of a pain for me to do it without getting paid :). If you're determined, go and read up on the Implements keyword for VB6/VBA.

Public Function getSubElementsByTagName(el As IHTMLElement, tagname As String) As Collection

    Dim descendants As New Collection
    Dim results As New Collection
    Dim i As Long

    getDescendants el, descendants

    For i = 1 To descendants.Count
        If descendants(i).tagname = tagname Then
            results.Add descendants(i)
        End If
    Next i

    getSubElementsByTagName = results

End Function

Public Function getDescendants(nd As IHTMLElement, ByRef descendants As Collection)
    Dim i As Long
    descendants.Add nd
    For i = 1 To nd.Children.Length
        getDescendants nd.Children.Item(i), descendants
    Next i
End Function

Display unescaped HTML in Vue.js

Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.

So for your specific example you would need:

<div id="logapp">    
            <tr v-repeat="logs">
                <td v-html="fail"></td>
                <td v-html="type"></td>
                <td v-html="description"></td>
                <td v-html="stamp"></td>
                <td v-html="id"></td>

How to change the text on the action bar


You can do it programmatically in Kotlin this way. You just ignore it if "supportActionBar" is null:

    supportActionBar?.title = "My text"

Or this way. It throws an exception if "supportActionBar" is null.

    supportActionBar!!.title = "My text"

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

Format in other syntax is possible in this way


Why do we need to install gulp globally and locally?

The question "Why do we need to install gulp globally and locally?" can be broken down into the following two questions:

  1. Why do I need to install gulp locally if I've already installed it globally?

  2. Why do I need to install gulp globally if I've already installed it locally?

Several others have provided excellent answers to theses questions in isolation, but I thought it would be beneficial to consolidate the information in a unified answer.

Why do I need to install gulp locally if I've already installed it globally?

The rationale for installing gulp locally is comprised of several reasons:

  1. Including the dependencies of your project locally ensures the version of gulp (or other dependencies) used is the originally intended version.
  2. Node doesn't consider global modules by default when using require() (which you need to include gulp within your script). Ultimately, this is because the path to the global modules isn't added to NODE_PATH by default.
  3. According to the Node development team, local modules load faster. I can't say why this is, but this would seem to be more relevant to node's use in production (i.e. run-time dependencies) than in development (i.e. dev dependencies). I suppose this is a legitimate reason as some may care about whatever minor speed advantage is gained loading local vs. global modules, but feel free to raise your eyebrow at this reason.

Why do I need to install gulp globally if I've already installed it locally?

  1. The rationale for installing gulp globally is really just the convenience of having the gulp executable automatically found within your system path.

To avoid installing locally you can use npm link [package], but the link command as well as the install --global command doesn't seem to support the --save-dev option which means there doesn't appear to be an easy way to install gulp globally and then easily add whatever version that is to your local package.json file.

Ultimately, I believe it makes more sense to have the option of using global modules to avoid having to duplicate the installation of common tools across all your projects, especially in the case of development tools such as grunt, gulp, jshint, etc. Unfortunately it seems you end up fighting the tools a bit when you go against the grain.

How can I pass a list as a command-line argument with argparse?

You can parse the list as a string and use of the eval builtin function to read it as a list. In this case, you will have to put single quotes into double quote (or the way around) in order to ensure successful string parse.

# declare the list arg as a string
parser.add_argument('-l', '--list', type=str)

# parse
args = parser.parse()

# turn the 'list' string argument into a list object
args.list = eval(args.list)


python --list "[1, 2, 3]"

[1, 2, 3]
<class 'list'>

How to enter a series of numbers automatically in Excel

I have a very simple answer. Just put this formula in cell A2:


and fill down.

This sets row number automatically, even if you remove some rows or sort rows.

Autosorting numbers of row

Parse an HTML string with JS

const parse = Range.prototype.createContextualFragment.bind(document.createRange());

document.body.appendChild( parse('<p><strong>Today is:</strong></p>') ),
document.body.appendChild( parse(`<p style="background: #eee">${new Date()}</p>`) );

Only valid child Nodes within the parent Node (start of the Range) will be parsed. Otherwise, unexpected results may occur:

// <body> is "parent" Node, start of Range
const parseRange = document.createRange();
const parse = Range.prototype.createContextualFragment.bind(parseRange);

// Returns Text "1 2" because td, tr, tbody are not valid children of <body>
parse('<td>1</td> <td>2</td>');
parse('<tr><td>1</td> <td>2</td></tr>');
parse('<tbody><tr><td>1</td> <td>2</td></tr></tbody>');

// Returns <table>, which is a valid child of <body>
parse('<table> <td>1</td> <td>2</td> </table>');
parse('<table> <tr> <td>1</td> <td>2</td> </tr> </table>');
parse('<table> <tbody> <td>1</td> <td>2</td> </tbody> </table>');

// <tr> is parent Node, start of Range
parseRange.setStart(document.createElement('tr'), 0);

// Returns [<td>, <td>] element array
parse('<td>1</td> <td>2</td>');
parse('<tr> <td>1</td> <td>2</td> </tr>');
parse('<tbody> <td>1</td> <td>2</td> </tbody>');
parse('<table> <td>1</td> <td>2</td> </table>');

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);


a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));

    public static class Extenions
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)

                yield return l;

How to select all columns, except one column in pandas?

When the columns are not a MultiIndex, df.columns is just an array of column names so you can do:

df.loc[:, df.columns != 'b']

          a         c         d
0  0.561196  0.013768  0.772827
1  0.882641  0.615396  0.075381
2  0.368824  0.651378  0.397203
3  0.788730  0.568099  0.869127

How to print a stack trace in Node.js?

In case someone is still looking for this like I was, then there is a module we can use called "stack-trace". It is really popular. NPM Link

Then walk through the trace.

  var stackTrace = require('stack-trace');
  var trace = stackTrace.get(); (item){ 
    console.log(new Date().toUTCString() + ' : ' +  item.toString() );  

Or just simply print the trace:

var stackTrace = require('stack-trace');
var trace = stackTrace.get();

How can I maintain fragment state when added to the back stack?

getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener()
        public void onBackStackChanged()
            if (getSupportFragmentManager().getBackStackEntryCount() == 0)
                //setToolbarTitle("Main Activity");
                Log.e("fragment_replace11111", "replace");
public void onBackPressed()
 Fragment fragment = getSupportFragmentManager().findFragmentById(;
  if (fragment instanceof YourFragmentName)
        fragmentReplace(new HomeFragment(),"Home Fragment");
        txt_toolbar_title.setText("Your Fragment");

public void fragmentReplace(Fragment fragment, String fragment_name)
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(, fragment, fragment_name);
        fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
    catch (Exception e)

There is no argument given that corresponds to the required formal parameter - .NET Error

You have a constructor which takes 2 parameters. You should write something like:

new ErrorEventArg(errorMsv, lastQuery)

It's less code and easier to read.


Or, in order for your way to work, you can try writing a default constructor for ErrorEventArg which would have no parameters, like this:

public ErrorEventArg() {}

Python send UDP packet

Manoj answer above is correct, but another option is to use MESSAGE.encode() or encode('utf-8') to convert to bytes. bytes and encode are mostly the same, encode is compatible with python 2. see here for more

full code:

import socket

UDP_IP = ""
UDP_PORT = 5005
MESSAGE = "Hello, World!"

print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

    urllib2.urlopen("", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):

    urllib2.urlopen("", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
        # reraise the original error
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

Is a DIV inside a TD a bad idea?

Using a div instide a td is not worse than any other way of using tables for layout. (Some people never use tables for layout though, and I happen to be one of them.)

If you use a div in a td you will however get in a situation where it might be hard to predict how the elements will be sized. The default for a div is to determine its width from its parent, and the default for a table cell is to determine its size depending on the size of its content.

The rules for how a div should be sized is well defined in the standards, but the rules for how a td should be sized is not as well defined, so different browsers use slightly different algorithms.

How To Auto-Format / Indent XML/HTML in Notepad++

Install Tidy2 plugin. I have Notepad++ v6.2.2, and Tidy2 works fine so far.

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

It is important to define an id in the model

.DataSource(dataSource => dataSource
        .Model(model => model.Id(p =>

How to subtract/add days from/to a date?

The answer probably depends on what format your date is in, but here is an example using the Date class:

dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")

You can even play with different units like weeks.

How to loop over directories in Linux?

If you want to execute multiple commands in a for loop, you can save the result of find with mapfile (bash >= 4) as an variable and go through the array with ${dirlist[@]}. It also works with directories containing spaces.

The find command is based on the answer by Boldewyn. Further information about the find command can be found there.

mapfile -t dirlist < <( find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n' )
for dir in ${dirlist[@]}; do
    echo ">${dir}<"
    # more commands can go here ...

MySql difference between two timestamps in days?

SELECT DATEDIFF( now(), '2013-06-20' );

here datediff takes two arguments 'upto-date', 'from-date'

What i have done is, using now() function, i can get no. of days since 20-june-2013 till today.

Iterate over a Javascript associative array in sorted order

you could even prototype it onto object:

Object.prototype.iterateSorted = function(worker)
    var keys = [];
    for (var key in this)
        if (this.hasOwnProperty(key))

    for (var i = 0; i < keys.length; i++)
        worker(this[ keys[i] ]);

and the usage:

var myObj = { a:1, b:2 };

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

How to check for a valid Base64 encoded string

The answer must depend on the usage of the string. There are many strings that may be "valid base64" according to the syntax suggested by several posters, but that may "correctly" decode, without exception, to junk. Example: the 8char string Portland is valid Base64. What is the point of stating that this is valid Base64? I guess that at some point you'd want to know that this string should or should not be Base64 decoded.

In my case, I have Oracle connection strings that may be in plain text like:

Data source=mydb/DBNAME;User Id=Roland;Password=.....`

or in base64 like


I just have to check for the presence of a semicolon, because that proves that it is NOT base64, which is of course faster than any above method.

How to programmatically close a JFrame

Posting what was in the question body as CW answer.

Wanted to share the results, mainly derived from following camickr's link. Basically I need to throw a WindowEvent.WINDOW_CLOSING at the application's event queue. Here's a synopsis of what the solution looks like

// closing down the window makes sense as a method, so here are
// the salient parts of what happens with the JFrame extending class ..

    public class FooWindow extends JFrame {
        public FooWindow() {
            setBounds(5, 5, 400, 300);  // yeah yeah, this is an example ;P
        public void pullThePlug() {
                WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);

// Here's how that would be employed from elsewhere -

    // someplace the window gets created ..
    FooWindow fooey = new FooWindow();
    // and someplace else, you can close it thusly

Split a python list into other "sublists" i.e smaller lists

I'd say

chunks = [data[x:x+100] for x in range(0, len(data), 100)]

If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange(), changing the above code to:

chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]

Row names & column names in R

I think that using colnames and rownames makes the most sense; here's why.

Using names has several disadvantages. You have to remember that it means "column names", and it only works with data frame, so you'll need to call colnames whenever you use matrices. By calling colnames, you only have to remember one function. Finally, if you look at the code for colnames, you will see that it calls names in the case of a data frame anyway, so the output is identical.

rownames and row.names return the same values for data frame and matrices; the only difference that I have spotted is that where there aren't any names, rownames will print "NULL" (as does colnames), but row.names returns it invisibly. Since there isn't much to choose between the two functions, rownames wins on the grounds of aesthetics, since it pairs more prettily withcolnames. (Also, for the lazy programmer, you save a character of typing.)

Convert String to equivalent Enum value

I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

I guess it gives more granular control but I'm not sure it's really necessary.

public enum Type {

    public static Map<String, Type> typeMapping = Maps.newHashMap();
    static {
        typeMapping.put(, DEBIT);
        typeMapping.put(, CREDIT);

    public static Type getType(String typeName) {
        if (typeMapping.get(typeName) == null) {
            throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
        return typeMapping.get(typeName);

I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

Hide/Show components in react native

Actually, in iOS development by react-native when I use display: 'none' or something like below:

const styles = StyleSheet.create({
  disappearImage: {
    width: 0,
    height: 0

The iOS doesn't load anything else of the Image component like onLoad or etc, so I decided to use something like below:

const styles = StyleSheet.create({
  disappearImage: {
    width: 1,
    height: 1,
    position: 'absolute',
    top: -9000,
    opacity: 0

"cannot be used as a function error"

#include "header.h"

int estimatedPopulation (int currentPopulation, float growthRate)
    return currentPopulation + currentPopulation * growthRate  / 100;

Equivalent of shell 'cd' command to change the working directory?

You can change the working directory with:

import os


There are two best practices to follow when using this method:

  1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
  2. Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

Is an entity body allowed for an HTTP DELETE request?

Using DELETE with a Body is risky... I prefer this approach for List Operations over REST:

Regular Operations

GET /objects/ Gets all Objects

GET /object/ID Gets an Object with specified ID

POST /objects Adds a new Object

PUT /object/ID Adds an Object with specified ID, Updates an Object

DELETE /object/ID Deletes the object with specified ID

All Custom actions are POST

POST /objects/addList Adds a List or Array of Objects included in body

POST /objects/deleteList Deletes a List of Objects included in body

POST /objects/customQuery Creates a List based on custom query in body

If a client doesn't support your extended operations they can work in the regular way.

How to convert a string with comma-delimited items to a list in Python?

Using functional Python:

text=filter(lambda x:x!=',',map(str,text))

How to prevent "The play() request was interrupted by a call to pause()" error?

I have hit this issue, and have a case where I needed to hit pause() then play() but when using pause().then() I get undefined.

I found that if I started play 150ms after pause it resolved the issue. (Hopefully Google fixes soon)

playerMP3.volume = 0;

//Avoid the Promise Error
setTimeout(function () {;
}, 150);

Create, read, and erase cookies with jQuery

As I know, there is no direct support, but you can use plain-ol' javascript for that:

// Cookies
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    else var expires = "";               

    document.cookie = name + "=" + value + expires + "; path=/";

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    return null;

function eraseCookie(name) {
    createCookie(name, "", -1);

How to shutdown a Spring Boot Application in a correct way?

As to @Jean-Philippe Bond 's answer ,

here is a maven quick example for maven user to configure HTTP endpoint to shutdown a spring boot web app using spring-boot-starter-actuator so that you can copy and paste:

1.Maven pom.xml:


#No auth  protected 

#Enable shutdown endpoint

All endpoints are listed here:

3.Send a post method to shutdown the app:

curl -X POST localhost:port/shutdown

Security Note:

if you need the shutdown method auth protected, you may also need


configure details:

CentOS: Enabling GD Support in PHP Installation

  1. You need to find a repo that offers a GD lib matching your current php version. I've had great success using Remi Collet's repo for this purpose. In fact, I used it yesterday to update my php install to the latest 5.4.0RC6 version on my CentOS6 box.
  2. Once you've setup the repo it's a simple matter of running sudo yum install php-gd
  3. Of course, the usual things apply: make sure you restart apache after installing, etc.

What's the best way to use R scripts on the command line (terminal)?

#!/path/to/R won't work because R is itself a script, so execve is unhappy.

I use R --slave -f script

How to run a maven created jar file using just the command line

Just use the exec-maven-plugin.


Then you run you program:

mvn exec:java

Visually managing MongoDB documents and collections

The real answer is ... No.

So far as I have found there is no reasonable or publicly available Windows MonogoDB client which is really very sad since MongoDB is pretty sweet.

I've thought about throwing together a simple app with WPF on Codeplex ... but I haven't been super motivated.

What would features would you be interested in having? Maybe you can inspire me or others?

For example, do you just want to view DBs / collections & perhaps simple edits (so you don't have to use the shell) or do you require something more complex?

How to download the latest artifact from Artifactory repository?

With awk:

     curl  -sS http://the_repo/com/stackoverflow/the_artifact/maven-metadata.xml | grep latest | awk -F'<latest>' '{print $2}' | awk -F'</latest>' '{print $1}'

With sed:

    curl  -sS http://the_repo/com/stackoverflow/the_artifact/maven-metadata.xml | grep latest | sed 's:<latest>::' | sed 's:</latest>::'

How to update SQLAlchemy row entry?

Examples to clarify the important issue in accepted answer's comments

I didn't understand it until I played around with it myself, so I figured there would be others who were confused as well. Say you are working on the user whose id == 6 and whose no_of_logins == 30 when you start.

# 1 (bad)
user.no_of_logins += 1
# result: UPDATE user SET no_of_logins = 31 WHERE = 6

# 2 (bad)
user.no_of_logins = user.no_of_logins + 1
# result: UPDATE user SET no_of_logins = 31 WHERE = 6

# 3 (bad)
setattr(user, 'no_of_logins', user.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = 31 WHERE = 6

# 4 (ok)
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE = 6

# 5 (ok)
setattr(user, 'no_of_logins', User.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE = 6

The point

By referencing the class instead of the instance, you can get SQLAlchemy to be smarter about incrementing, getting it to happen on the database side instead of the Python side. Doing it within the database is better since it's less vulnerable to data corruption (e.g. two clients attempt to increment at the same time with a net result of only one increment instead of two). I assume it's possible to do the incrementing in Python if you set locks or bump up the isolation level, but why bother if you don't have to?

A caveat

If you are going to increment twice via code that produces SQL like SET no_of_logins = no_of_logins + 1, then you will need to commit or at least flush in between increments, or else you will only get one increment in total:

# 6 (bad)
user.no_of_logins = User.no_of_logins + 1
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE = 6

# 7 (ok)
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE = 6
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE = 6

How to find MAC address of an Android device programmatically

With this code you will be also able to get MacAddress in Android 6.0 also

public static String getMacAddr() {
    try {
        List <NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif: all) {
            if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

            byte[] macBytes = nif.getHardwareAddress();
            if (macBytes == null) {
                return "";

            StringBuilder res1 = new StringBuilder();
            for (byte b: macBytes) {
                //res1.append(Integer.toHexString(b & 0xFF) + ":");
                res1.append(String.format("%02X:", b));

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            return res1.toString();
    } catch (Exception ex) {}
    return "02:00:00:00:00:00";

EDIT 1. This answer got a bug where a byte that in hex form got a single digit, will not appear with a "0" before it. The append to res1 has been changed to take care of it.

Java "?" Operator for checking null - What is it? (Not Ternary!)

You can test the code which you have provided and it will give syntax error.So, it is not supported in Java. Groovy does support it and it was proposed for Java 7 (but never got included).

However, you can use the Optional provided in Java 8. This might help you in achieving something on similar line.

Example Code for Optional

Calling onclick on a radiobutton list using javascript

I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick event handler for the radio buttons:

  <script type="text/javascript">
    window.onload = function() {

        var ex1 = document.getElementById('example1');
        var ex2 = document.getElementById('example2');
        var ex3 = document.getElementById('example3');

        ex1.onclick = handler;
        ex2.onclick = handler;
        ex3.onclick = handler;


    function handler() {
  <input type="radio" name="example1" id="example1" value="Example 1" />
  <label for="example1">Example 1</label>
  <input type="radio" name="example2" id="example2" value="Example 2" />
  <label for="example1">Example 2</label>
  <input type="radio" name="example3" id="example3" value="Example 3" />
  <label for="example1">Example 3</label>

How to return a string from a C++ function?

You never give any value to your strings in main so they are empty, and thus obviously the function returns an empty string.


string str1, str2, str3;


string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";

Also, you have several problems in your replaceSubstring function:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::find returns a std::string::size_type (aka. size_t) not an int. Two differences: size_t is unsigned, and it's not necessarily the same size as an int depending on your platform (eg. on 64 bits Linux or Windows size_t is unsigned 64 bits while int is signed 32 bits).
  • What happens if s2 is not part of s1? I'll leave it up to you to find how to fix that. Hint: std::string::npos ;)

<code> vs <pre> vs <samp> for inline and block code snippets

This works for me to display code in frontend:

    width: 100%;
    background: transparent;
    border: none;
    border-radius: 0;
    resize: none;
    outline: none;
    border: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;

<textarea class="content">
<div>my div</div><p>my paragraph</p>

View Live Demo:

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

Javascript close alert box

I want to be able to close an alert box automatically using javascript after a certain amount of time or on a specific event (i.e. onkeypress)

A sidenote: if you have an Alert("data"), you won't be able to keep code running in background (AFAIK)... . the dialog box is a modal window, so you can't lose focus too. So you won't have any keypress or timer running...

Can't push image to Amazon ECR - fails with "no basic auth credentials"

Make sure the user with which you are running Docker locally is the one which you use to eventually push the image. For me running with sudo caused the issue. Removing sudo from the command solved it. Hope this helps and saves someone`s time and nobody makes this same dumb mistake again. Below is the output for your reference.

sudo docker push {your-account-id}{repository-name}:{tag-name}
The push refers to repository [{your-account-id}{repository-name}]
f13afaa342eb: Preparing
d01b75ce3235: Preparing
7eaa58141607: Preparing
519e8c5b2557: Preparing
15d4a3a33fec: Preparing
fdbbf41b1ab8: Waiting
4b88ecda5399: Waiting
e23a8e1e773f: Waiting
6623e2cc11cd: Waiting
no basic auth credentials

Running without the sudo worked perfectly fine

docker push {your-account-id}{repository-name}:{tag-name}
The push refers to repository [{your-account-id}{repository-name}]
f13afaa342eb: Pushed
d01b75ce3235: Pushed
7eaa58141607: Pushed
519e8c5b2557: Pushed
15d4a3a33fec: Pushed
fdbbf41b1ab8: Pushed
4b88ecda5399: Pushed
e23a8e1e773f: Pushed
6623e2cc11cd: Pushed
{tag-name}: digest: sha256:5ceaa5bf7605559582960b6d56a8eece9486ce0950bca9dd63a0dcd38a520bf0 size: 4293

Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

Check if object is a jQuery object

The best way to check the instance of an object is through instanceof operator or with the method isPrototypeOf() which inspects if the prototype of an object is in another object's prototype chain.

obj instanceof jQuery;

But sometimes it might fail in the case of multiple jQuery instances on a document. As @Georgiy Ivankin mentioned:

if I have $ in my current namespace pointing to jQuery2 and I have an object from outer namespace (where $ is jQuery1) then I have no way to use instanceof for checking if that object is a jQuery object

One way to overcome that problem is by aliasing the jQuery object in a closure or IIFE

//aliases jQuery as $
(function($, undefined) {
    /*... your code */

    console.log(obj instanceof $);

    /*... your code */
//imports jQuery1

Other way to overcome that problem is by inquiring the jquery property in obj

'jquery' in obj

However, if you try to perform that checking with primitive values, it will throw an error, so you can modify the previous checking by ensuring obj to be an Object

'jquery' in Object(obj)

Although the previous way is not the safest (you can create the 'jquery' property in an object), we can improve the validation by working with both approaches:

if (obj instanceof jQuery || 'jquery' in Object(obj)) { }

The problem here is that any object can define a property jquery as own, so a better approach would be to ask in the prototype, and ensure that the object is not null or undefined

if (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery)) { }

Due to coercion, the if statement will make short circuit by evaluating the && operator when obj is any of the falsy values (null, undefined, false, 0, ""), and then proceeds to perform the other validations.

Finally we can write an utility function:

function isjQuery(obj) {
  return (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery));

Let's take a look at: Logical Operators and truthy / falsy

How to get a web page's source code from Java

Try the following code with an added request property:


public class SocketConnection
    public static String getURLSource(String url) throws IOException
        URL urlObject = new URL(url);
        URLConnection urlConnection = urlObject.openConnection();
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

        return toString(urlConnection.getInputStream());

    private static String toString(InputStream inputStream) throws IOException
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
            String inputLine;
            StringBuilder stringBuilder = new StringBuilder();
            while ((inputLine = bufferedReader.readLine()) != null)

            return stringBuilder.toString();

PHP cURL GET request and request's body

The accepted answer is wrong. GET requests can indeed contain a body. This is the solution implemented by WordPress, as an example:

curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );

EDIT: To clarify, the initial curl_setopt is necessary in this instance, because libcurl will default the HTTP method to POST when using CURLOPT_POSTFIELDS (see documentation).

Simple dictionary in C++

Here's the map solution:

#include <iostream>
#include <map>

typedef std::map<char, char> BasePairMap;

int main()
    BasePairMap m;
    m['A'] = 'T';
    m['T'] = 'A';
    m['C'] = 'G';
    m['G'] = 'C';

    std::cout << "A:" << m['A'] << std::endl;
    std::cout << "T:" << m['T'] << std::endl;
    std::cout << "C:" << m['C'] << std::endl;
    std::cout << "G:" << m['G'] << std::endl;

    return 0;

Retrieve only the queried element in an object array in MongoDB collection

MongoDB 2.2's new $elemMatch projection operator provides another way to alter the returned document to contain only the first matched shapes element:

    {"shapes.color": "red"}, 
    {_id: 0, shapes: {$elemMatch: {color: "red"}}});


{"shapes" : [{"shape": "circle", "color": "red"}]}

In 2.2 you can also do this using the $ projection operator, where the $ in a projection object field name represents the index of the field's first matching array element from the query. The following returns the same results as above:

db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});

MongoDB 3.2 Update

Starting with the 3.2 release, you can use the new $filter aggregation operator to filter an array during projection, which has the benefit of including all matches, instead of just the first one.

    // Get just the docs that contain a shapes element where color is 'red'
    {$match: {'shapes.color': 'red'}},
    {$project: {
        shapes: {$filter: {
            input: '$shapes',
            as: 'shape',
            cond: {$eq: ['$$shape.color', 'red']}
        _id: 0


        "shapes" : [ 
                "shape" : "circle",
                "color" : "red"

AngularJS Uploading An Image With ng-upload

There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)


<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.


$scope.uploadFile = function(files) {
    var fd = new FormData();
    //Take the first selected file
    fd.append("file", files[0]);

    $, fd, {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success( ...all right!... ).error( ..damn!... );


The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.

Replace text inside td using jQuery having td containing other elements

Using text nodes in jquery is a particularly delicate endeavour and most operations are made to skip them altogether.

Instead of going through the trouble of carefully avoiding the wrong nodes, why not just wrap whatever you need to replace inside a <span> for instance:

<td><span class="replaceme">8: Tap on APN and Enter <B>www</B>.</span></td>


$('.replaceme').html('Whatever <b>HTML</b> you want here.');

oracle diff: how to compare two tables?

Try this:

(select * from T1 minus select * from T2) -- all rows that are in T1 but not in T2
union all
(select * from T2 minus select * from T1)  -- all rows that are in T2 but not in T1

No external tool. No performance issues with union all.

How do I show the schema of a table in a MySQL database?




Getting value from JQUERY datepicker

You could remove the name attribute of this input, so it won't be submited.

To access the value of this controll:

$("div#someID").datepicker( "getDate" )

and your may have a look at the document in

How to convert an XML file to nice pandas dataframe?

Chiming in to recommend the use of the xmltodict library. It handled your xml text pretty well and I've used it for ingesting an xml file with almost a million records. xmltodict handling xml load

How to apply CSS to iframe?

The following worked for me.

var iframe = top.frames[name].document;
var css = '' +
          '<style type="text/css">' +
          'body{margin:0;padding:0;background:transparent}' +

Run PostgreSQL queries from the command line

psql -U username -d mydatabase -c 'SELECT * FROM mytable'

If you're new to postgresql and unfamiliar with using the command line tool psql then there is some confusing behaviour you should be aware of when you've entered an interactive session.

For example, initiate an interactive session:

psql -U username mydatabase 

At this point you can enter a query directly but you must remember to terminate the query with a semicolon ;

For example:

mydatabase=# SELECT * FROM mytable;

If you forget the semicolon then when you hit enter you will get nothing on your return line because psql will be assuming that you have not finished entering your query. This can lead to all kinds of confusion. For example, if you re-enter the same query you will have most likely create a syntax error.

As an experiment, try typing any garble you want at the psql prompt then hit enter. psql will silently provide you with a new line. If you enter a semicolon on that new line and then hit enter, then you will receive the ERROR:

mydatabase=# asdfs 
mydatabase=# ;  
ERROR:  syntax error at or near "asdfs"
LINE 1: asdfs

The rule of thumb is: If you received no response from psql but you were expecting at least SOMETHING, then you forgot the semicolon ;

Why are there two ways to unstage a file in Git?

These 2 commands have several subtle differences if the file in question is already in the repo and under version control (previously committed etc.):

  • git reset HEAD <file> unstages the file in the current commit.
  • git rm --cached <file> will unstage the file for future commits also. It's unstaged untill it gets added again with git add <file>.

And there's one more important difference:

  • After running git rm --cached <file> and push your branch to the remote, anyone pulling your branch from the remote will get the file ACTUALLY deleted from their folder, even though in your local working set the file just becomes untracked (i.e. not physically deleted from the folder).

This last difference is important for projects which include a config file where each developer on the team has a different config (i.e. different base url, ip or port setting) so if you're using git rm --cached <file> anyone who pulls your branch will have to manually re-create the config, or you can send them yours and they can re-edit it back to their ip settings (etc.), because the delete only effects people pulling your branch from the remote.

How to lock orientation of one view controller to portrait mode only in Swift

Add this code to force portrait and lock it:

override func viewDidLoad() {

    // Force the device in portrait mode when the view controller gets loaded
    UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation") 

override func shouldAutorotate() -> Bool {
    // Lock autorotate
    return false

override func supportedInterfaceOrientations() -> Int {

    // Only allow Portrait
    return Int(UIInterfaceOrientationMask.Portrait.rawValue)

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {

    // Only allow Portrait
    return UIInterfaceOrientation.Portrait

In your AppDelegate - set supportedInterfaceOrientationsForWindow to whatever orientations you want the entire application to support:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.All

CodeIgniter -> Get current URL relative to base url

I don't know if there is such a function, but with $this->uri->uri_to_assoc() you get an associative array from the $_GET parameters. With this, and the controller you are in, you know how the URL looks like. In you above URL this would mean you would be in the controller dropbox and the array would be something like this:

array("derrek" => "shopredux", "ahahaha" => "hihihi");

With this you should be able to make such a function on your own.

How can I kill all sessions connecting to my oracle database?

I found the below snippet helpful. Taken from:

owner||'.'||object_name obj ,
oracle_username||' ('||s.status||')' oruser ,
os_user_name osuser ,
machine computer ,
l.process unix ,
s.sid||','||s.serial# ss , rs ,
to_char(s.logon_time,'yyyy/mm/dd hh24:mi:ss') time
from v$locked_object l ,
dba_objects o ,
v$session s ,
v$transaction t ,
v$rollname r
where l.object_id = o.object_id
and s.sid=l.session_id
and s.taddr=t.addr
and t.xidusn=r.usn
order by osuser, ss, obj

Then ran:

Alter System Kill Session '<value from ss above>'

To kill individual sessions.

error: (-215) !empty() in function detectMultiScale

no need to change the code

download that .xml file , then put the path of that file

it will solve the error (100%)

Dynamic WHERE clause in LINQ

You can also use the PredicateBuilder from LinqKit to chain multiple typesafe lambda expressions using Or or And.

Plotting lines connecting points

I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot is capable of plotting multiple lines with one command. If x and y are arrays, then plot draws one line for every column.

In your case, you can do the following:

x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5,  1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')

Have a long list of x's and y's, and want to connect adjacent pairs?

xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])

Want a specified (different) color for the dots and the lines?

plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')

Plot of two pairs of points, each connected by a separate line

Reading data from XML

Alternatively, you can use XPathNavigator:

XmlDocument doc = new XmlDocument();
XPathNavigator navigator = doc.CreateNavigator();

string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");


/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
                                      XPathNavigator navigator, string xpath) {
    StringBuilder sb = new StringBuilder();
    XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
    while (bookNodesIterator.MoveNext())
       sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
    return sb.ToString();

How to determine a user's IP address in node

var ip = req.headers['x-forwarded-for'] || 
     req.connection.remoteAddress || 
     req.socket.remoteAddress ||
     (req.connection.socket ? req.connection.socket.remoteAddress : null);

Note that sometimes you can get more than one IP address in req.headers['x-forwarded-for']. Also, an x-forwarded-for header will not always be set which may throw an error.

The general format of the field is:

x-forwarded-for: client, proxy1, proxy2, proxy3

where the value is a comma+space separated list of IP addresses, the left-most being the original client, and each successive proxy that passed the request adding the IP address where it received the request from. In this example, the request passed through proxy1, proxy2, and then proxy3. proxy3 appears as remote address of the request.

This is the solution suggested by Arnav Gupta with a fix Martin has suggested below in the comments for cases when x-forwarded-for is not set :

var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() || 
         req.connection.remoteAddress || 
         req.socket.remoteAddress || 

Suggestion using modern JS:

  • processing x-forwarded-for only if set, if so, take the first address
  • other parameters use optional chaining (?.)
const parseIp = (req) =>
    (typeof req.headers['x-forwarded-for'] === 'string'
        && req.headers['x-forwarded-for'].split(',').shift())
    || req.connection?.remoteAddress
    || req.socket?.remoteAddress
    || req.connection?.socket?.remoteAddress

// =>

Java abstract interface

It's not necessary, it's optional, just as public on interface methods.

See the JLS on this: abstract Interfaces Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.


9.4 Abstract Method Declarations


For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.

It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

It worked for me you can try your: Add this to VM options in Tomcat


What is the meaning of "__attribute__((packed, aligned(4))) "

Before answering, I would like to give you some data from Wiki

Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;


sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.


We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.

If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1

//Structure 2

#pragma pack(pop)

How to set an image's width and height without stretching it?

If using flexbox is a valid option for you (don't need to suport old browsers), check my other answer here (which is possibly a duplicate of this one):

Basically you'd need to wrap your img tag in a div and your css would look like this:

.img__container {
    display: flex;
    padding: 15px 12px;
    box-sizing: border-box;
    width: 400px; height: 200px;

    img {
        margin: auto;
        max-width: 100%;
        max-height: 100%;

How to copy to clipboard in Vim?

Nothing above worked for me on my windows laptop.

Ctrl+C was fine for copying.. but I needed Shift+Insert to Paste !

(A good reason to always get a laptop where Insert can always be accessed without pressing a secondary key)

Center a button in a Linear layout



How can I pass an Integer class correctly by reference?

What you are seeing here is not an overloaded + oparator, but autoboxing behaviour. The Integer class is immutable and your code:

Integer i = 0;
i = i + 1;  

is seen by the compiler (after the autoboxing) as:

Integer i = Integer.valueOf(0);
i = Integer.valueOf(i.intValue() + 1);  

so you are correct in your conclusion that the Integer instance is changed, but not sneakily - it is consistent with the Java language definition :-)

Cannot find the '@angular/common/http' module

Beware of auto imports. my HTTP_INTERCEPTORS was auto imported like this:

import { HTTP_INTERCEPTORS } from '@angular/common/http/src/interceptor';

instead of

import { HTTP_INTERCEPTORS } from '@angular/common/http';

which caused this error

How to substitute shell variables in complex text files

Call the perl binary, in search and replace per line mode ( the -pi ) by running the perl code ( the -e) in the single quotes, which iterates over the keys of the special %ENV hash containing the exported variable names as keys and the exported variable values as the keys' values and for each iteration simple replace a string containing a $<<key>> with its <<value>>.

 perl -pi -e 'foreach $key(sort keys %ENV){ s/\$$key/$ENV{$key}/g}' file

Caveat: An additional logic handling is required for cases in which two or more vars start with the same string ...

How to call Oracle MD5 hash function?

@user755806 I do not believe that your question was answered. I took your code but used the 'foo' example string, added a lower function and also found the length of the hash returned. In sqlplus or Oracle's sql developer Java database client you can use this to call the md5sum of a value. The column formats clean up the presentation.

column hash_key format a34;
column hash_key_len format 999999;
select dbms_obfuscation_toolkit.md5(
          input => UTL_RAW.cast_to_raw('foo')) as hash_key,
          input => UTL_RAW.cast_to_raw('foo'))) as hash_key_len
 from dual;

The result set

HASH_KEY                           HASH_KEY_LEN
---------------------------------- ------------
acbd18db4cc2f85cedef654fccc4a4d8             32

is the same value that is returned from a Linux md5sum command.

echo -n foo | md5sum
acbd18db4cc2f85cedef654fccc4a4d8  -
  1. Yes you can call or execute the sql statement directly in sqlplus or sql developer. I tested the sql statement in both clients against 11g.
  2. You can use any C, C#, Java or other programming language that can send a statement to the database. It is the database on the other end of the call that needs to be able to understand the sql statement. In the case of 11 g, the code will work.
  3. @tbone provides an excellent warning about the deprecation of the dbms_obfuscation_toolkit. However, that does not mean your code is unusable in 12c. It will work but you will want to eventually switch to dbms_crypto package. dbms_crypto is not available in my version of 11g.

C# Sort and OrderBy comparison

you should calculate the complexity of algorithms used by the methods OrderBy and Sort. QuickSort has a complexity of n (log n) as i remember, where n is the length of the array.

i've searched for orderby's too, but i could not find any information even in msdn library. if you have not any same values and sorting related to only one property, i prefer to use Sort() method; if not than use OrderBy.

Why doesn't JavaScript support multithreading?

I don't know the rationale for this decision, but I know that you can simulate some of the benefits of multi-threaded programming using setTimeout. You can give the illusion of multiple processes doing things at the same time, though in reality, everything happens in one thread.

Just have your function do a little bit of work, and then call something like:

setTimeout(function () {
    ... do the rest of the work...
}, 0);

And any other things that need doing (like UI updates, animated images, etc) will happen when they get a chance.

Difference between SRC and HREF

If you're talking HTML4, its list of attributes might help you with the subtleties. They're not interchangeable.

Scrollbar without fixed height/Dynamic height with scrollbar

Use this:

style="height: 150px; max-height: 300px; overflow: auto;" 

fixe a height, it will be the default height and then a scroll bar come to access to the entire height

Can I set a TTL for @Cacheable

Since Spring-boot 1.3.3, you may set expire time in CacheManager by using RedisCacheManager.setExpires or RedisCacheManager.setDefaultExpiration in CacheManagerCustomizer call-back bean.

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

Bro, I had the same problem. Thing is I built a query builder, quite an complex one that build his predicates dynamically pending on what parameters had been set and cached the queries. Anyways, before I built my query builder, I had a non object oriented procedural code build the same thing (except of course he didn't cache queries and use parameters) that worked flawless. Now when my builder tried to do the very same thing, my PostgreSQL threw this fucked up error that you received too. I examined my generated SQL code and found no errors. Strange indeed.

My search soon proved that it was one particular predicate in the WHERE clause that caused this error. Yet this predicate was built by code that looked like, well almost, exactly as how the procedural code looked like before this exception started to appear out of nowhere.

But I saw one thing I had done differently in my builder as opposed to what the procedural code did previously. It was the order of the predicates he put in the WHERE clause! So I started to move this predicate around and soon discovered that indeed the order of predicates had much to say. If I had this predicate all alone, my query worked (but returned an erroneous result-match of course), if I put him with just one or the other predicate it worked sometimes, didn't work other times. Moreover, mimicking the previous order of the procedural code didn't work either. What finally worked was to put this demonic predicate at the start of my WHERE clause, as the first predicate added! So again if I haven't made myself clear, the order my predicates where added to the WHERE method/clause was creating this exception.

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

  • Solution 1: Sometimes the build fails because, the target folder cannot be deleted. (It might be open in the backend due to the previous builds.)

    -> Open Task Manager

    -> In the Process tab

    -> Do "End Process" for the running "java.exe" processess

  • Solution 2:

    -> Restart eclipse

    -> Perform Maven Build with command : clean install -DSkipTests

How to set custom location for local installation of npm package?

For OSX, you can go to your user's $HOME (probably /Users/yourname/) and, if it doesn't already exist, create an .npmrc file (a file that npm uses for user configuration), and create a directory for your npm packages to be installed in (e.g., /Users/yourname/npm). In that .npmrc file, set "prefix" to your new npm directory, which will be where "globally" installed npm packages will be installed; these "global" packages will, obviously, be available only to your user account.

In .npmrc:


Then run this command from the command line:

npm config ls -l

It should give output on both your own local configuration and the global npm configuration, and you should see your local prefix configuration reflected, probably near the top of the long list of output.

For security, I recommend this approach to configuring your user account's npm behavior over chown-ing your /usr/local folders, which I've seen recommended elsewhere.

What is middleware exactly?

Middleware is a terribly nebulous term. What is "middleware" in one case won't be in another. In general, you can expect something classed as middleware to have the following characteristics:

  • Primarily (usually exclusively) software; usually doesn't need any specialized hardware.

  • If it weren't there, applications that depend on it would have to incorporate it as part of their application and would experience a lot of duplication.

  • Almost certainly connects two applications and passes data between them.

You'll notice that this is pretty much the same definition as an operating system. So, for instance, a TCP/IP stack or caching could be considered middleware. But your OS could provide the same features, too. Indeed, middleware can be thought of like a special extension to an operating system, specific to a set of applications that depend on it. It just provides a higher-level service.

Some examples of middleware:

  • distributed cache
  • message queue
  • transaction monitor
  • packet rewriter
  • automated backup system

Div with horizontal scrolling only

The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:

.container {
    width: 30em;
    overflow-x: auto;
    white-space: nowrap;

You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y to hidden. But understand that is also an option.

enter image description here

How can I issue a single command from the command line through sql plus?

sqlplus user/password@sid < sqlfile.sql

This will also work from the DOS command line. In this case the file sqlfile.sql contains the SQL you wish to execute.

Null & empty string comparison in Bash

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';

Or to verify that a variable is empty

# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi has good documentation about if in bash:

How to make a select with array contains value clause in psql

Note that this may also work:

SELECT * FROM table WHERE s=ANY(array)

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I ran across this post today as I was running into the same issue and had the same problem of the javascript not running with the CDATA tags listed above. I corrected the CDATA tags to look like:

<script type="text/javascript">

your javascript code here


Then everything worked perfectly!

Illegal access: this web application instance has been stopped already

In short: this happens likely when you are hot-deploying webapps. For instance, your ide+development server hot-deploys a war again. Threads, that have been created previously are still running. But meanwhile their classloader/context is invalid and faces the IllegalAccessException / IllegalStateException becouse its orgininating webapp (the former runtime-environment) has been redeployed.

So, as states here, a restart does not permanently resolve this issue. Instead, it is better to find/implement a managed Thread Pool, like this to handle the termination of threads appropriately. In JavaEE you will use these ManagedThreadExeuctorServices. A similar opinion and reference here.

Examples for this are the EvictorThread of Apache Commons Pool, that "cleans" pooled instances according to the pool's configuration (max idle etc.).

Find control by name from Windows Forms controls

You can use:


Where f is your form variable. That gives you the control with name name.

When should I use the Visitor Design Pattern?

While I have understood the how and when, I have never understood the why. In case it helps anyone with a background in a language like C++, you want to read this very carefully.

For the lazy, we use the visitor pattern because "while virtual functions are dispatched dynamically in C++, function overloading is done statically".

Or, put another way, to make sure that CollideWith(ApolloSpacecraft&) is called when you pass in a SpaceShip reference that is actually bound to an ApolloSpacecraft object.

class SpaceShip {};
class ApolloSpacecraft : public SpaceShip {};
class ExplodingAsteroid : public Asteroid {
  virtual void CollideWith(SpaceShip&) {
    cout << "ExplodingAsteroid hit a SpaceShip" << endl;
  virtual void CollideWith(ApolloSpacecraft&) {
    cout << "ExplodingAsteroid hit an ApolloSpacecraft" << endl;

How to update Python?

  • Official Python .msi installers are designed to replace:

    • any previous micro release (in x.y.z, z is "micro") because they are guaranteed to be backward-compatible and binary-compatible
    • a "snapshot" (built from source) installation with any micro version
  • A snapshot installer is designed to replace any snapshot with a lower micro version.

(See responsible code for 2.x, for 3.x)

Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:

  • If you installed any modules from bdist_wininst packages (Windows .exes), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logic
  • modules installed with setuptools/pip that reside in Lib\site-packages can just be deleted afterwards
  • packages that you installed per-user, if any, reside in %APPDATA%/Python/PythonXY/site-packages and can likewise be deleted

How can I check if a value is of type Integer?

This can work:

int no=0;

catch(Exception ex)
    Console.WriteLine("not numeric or string");

Clone() vs Copy constructor- which is recommended in java

Have in mind that clone() doesn't work out of the box. You will have to implement Cloneable and override the clone() method making in public.

There are a few alternatives, which are preferable (since the clone() method has lots of design issues, as stated in other answers), and the copy-constructor would require manual work:

How to do a newline in output

Actually you don't even need the block:

  Dir.chdir 'C:/Users/name/Music'
  music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
  puts 'what would you like to call the playlist?'
  playlist_name = gets.chomp + '.m3u', 'w').puts(music)