Programs & Examples On #Roaming

Why powershell does not run Angular commands?

script1.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at

This error happens due to a security measure which won't let scripts be executed on your system without you having approved of it. You can do so by opening up a powershell with administrative rights (search for powershell in the main menu and select Run as administrator from the context menu) and entering:

set-executionpolicy remotesigned

error: This is probably not a problem with npm. There is likely additional logging output above

I already have the same problem . and I fix it using npm update & npm cache clean --force

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

I had the SAME issue today and it was driving me nuts!!! What I had done was upgrade to node 8.10 and upgrade my NPM to the latest I uninstalled angular CLI

npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli

I then verified my Cache from NPM if it wasn't up to date I cleaned it and ran the install again if npm version is < 5 then use npm cache clean --force

npm install -g @angular/cli@latest

and created a new project file and create a new angular project.

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

npm cache clean --force
npm update

Do not forget to do "npm update". it is very important step .

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

If you downgrade to 5.3 and still get the same error in Windows like me.
After hours working with npm versions I found the following solution:

1. Download latest recommended version of nodejs, these days is node-v6.11.3-x64
2. Uninstall nodejs with it.
3. Go to C:\Users\{YourUsername}\AppData\Roaming folder and delete npm and npm-cache folders
4. Run installer of nodejs again and install it
5 Update npm to 5.3 with npm i -g [email protected] command line

Now you should use npm without any issues.

'ng' is not recognized as an internal or external command, operable program or batch file

This answer is based on the following answer by @YuSolution

In my case Installing MySQL changed my path variable and even after reinstalling @angular/cli globally many times I was not able to fix the issue.


In command prompt, run the following command

npm config get prefix

A path will be returned like


Copy this path and go to ControlPanel > System and Security > System, Click on Advanced System settings, go to advanced tab and select environment variable button like

enter image description here

Now in User Variables box click on Path row and edit and in variable value box paste your copied path.

Restart the command prompt and it will work

pgadmin4 : postgresql application server could not be contacted.

In Windows Just go to this path and clear it ,that works !!


'gulp' is not recognized as an internal or external command

In my case, this problem occured because I did npm install with another system user in my project folder before. Gulp was already installed globally. After deleting folder /node_modules/ in my project, and running npm install with the current user, it worked.

ng is not recognized as an internal or external command

1- Install

$ npm install -g @angular/cli

2- Make sure where your ng.cmd is present.

enter image description here

3- Then add this path into variables.

enter image description here

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

EISDIR stands for "Error, Is Directory". This means that NPM is trying to do something to a file but it is a directory. In your case, NPM is trying to "read" a file which is a directory (Line: 4). Since the operation cannot be done the error is thrown.

Three things to make sure here.

  1. Make sure the file exists. If it does not, you need to create it. (If NPM depends on any specific information in the file, you will need to have that information there).
  2. Make sure it is in fact a file and not a directory.
  3. It has the right permissions. You can change the file to have all permissions with "sudo chmod 777 FILE_NAME". (Careful: You are giving Read, Write and Execute permissions to every one on that file)

Npm install cannot find module 'semver'

Just make sure semver is installed: npm install -g semver

Global npm install location on windows?

According to:

  • Local install (default): puts stuff in ./node_modules of the current package root.
  • Global install (with -g): puts stuff in /usr/local or wherever node is installed.
  • Install it locally if you're going to require() it.
  • Install it globally if you're going to run it on the command line. -> If you need both, then install it in both places, or use npm link.

prefix Configuration

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary.

The docs might be a little outdated, but they explain why global installs can end up in different directories:

(dev) go|c:\srv> npm config ls -l | grep prefix
; prefix = "C:\\Program Files\\nodejs" (overridden)
prefix = "C:\\Users\\bjorn\\AppData\\Roaming\\npm"

Based on the other answers, it may seem like the override is now the default location on Windows, and that I may have installed my office version prior to this override being implemented.

This also suggests a solution for getting all team members to have globals stored in the same absolute path relative to their PC, i.e. (run as Administrator):

mkdir %PROGRAMDATA%\npm
npm config set prefix %PROGRAMDATA%\npm

open a new cmd.exe window and reinstall all global packages.

Explanation (by lineno.):

  1. Create a folder in a sensible location to hold the globals (Microsoft is adamant that you shouldn't write to ProgramFiles, so %PROGRAMDATA% seems like the next logical place.
  2. The directory needs to be on the path, so use setx .. /M to set the system path (under HKEY_LOCAL_MACHINE). This is what requires you to run this in a shell with administrator permissions.
  3. Tell npm to use this new path. (Note: folder isn't visible in %PATH% in this shell, so you must open a new window).

Cordova - Error code 1 for command | Command failed for

Delete platforms/android folder and try to rebuild. That helped me a lot.

(Visual Studio Tools for Apache Cordova)

How do I create a shortcut via command-line in Windows?

The best way is to run this batch file. open notepad and type:-

@echo off
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "GIVETHEPATHOFLINK.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs

Save as filename.bat(be careful while saving select all file types) worked well in win XP.

SSH Key: “Permissions 0644 for '' are too open.” on mac

Key should be readable by the logged in user.

Try this:

chmod 400 ~/.ssh/Key file
chmod 400 ~/.ssh/

Installing Node.js (and npm) on Windows 10

go to

and hit the button that says "Download For ..."

This'll download the .msi (or .pkg for mac) which will do all the installation and paths for you, unlike the selected answer.

How to fix request failed on channel 0

shell request failed on channel 0

mean you don't have shell or remote commands access, fix your user permission on server to have shell access or if you just want tunneling use -N and -T options

NLTK and Stopwords Fail #lookuperror

You don't seem to have the stopwords corpus on your computer.

You need to start the NLTK Downloader and download all the data you need.

Open a Python console and do the following:

>>> import nltk
showing info

In the GUI window that opens simply press the 'Download' button to download all corpora or go to the 'Corpora' tab and only download the ones you need/want.

Github permission denied: ssh add agent has no identities

try this:

ssh-add ~/.ssh/id_rsa

worked for me

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

You can go to the Start Menu and search the Node.js icon and open the shell and then install anything with

install <packagename> -g

Could not extract response: no suitable HttpMessageConverter found for response type

Here is a simple solution

try adding this dependency


'pip' is not recognized as an internal or external command

Control Panel -> add/remove programs -> Python -> Modify -> optional Features (you can click everything) then press next -> Check "Add python to environment variables" -> Install

enter image description here

And that should solve your path issues, so jump to command prompt and you can use pip now.

"Could not find a part of the path" error message

Probably unrelated, but consider using Path.Combine instead of destination_dir + dir.Substring(...). From the look of it, your .Substring() will leave a backlash at the beginning, but the helper classes like Path are there for a reason.

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

'npm' is not recognized as internal or external command, operable program or batch file

I installed Node.js and while trying to install Ionic and cordova using this piece of code:

npm install -g cordova ionic

I faced the above error. I added 'C:\Program Files\nodejs' to my Environment Variable 'PATH'. But still was unable to get over this issue. Turned out that my PATH variable was longer than 2048 characters and so I was unable to add the Nodejs path to it. I had to remove the path of another program and add the Nodejs path. Close and reopen the cmd prompt and try to install Ionic again. This worked for me.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

java.lang.ClassNotFoundException is indicate that class is not found in class path. it could be the version of log4j is not compatible. check for different log4j version.

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

I just wanted to mention that I got a similar error in SQL Server Management Studio 2016, where I basically ignored it. Later, I launched Visual Studio (2015), and this error occurred there as well.

I searched and found the answer here recommending that files be deleted from the


folder. However, in my case, this folder was empty.

Since I remembered that I saw the error in Management Studio first, I checked, and there was a similar folder at

%localappdata%\Microsoft\SQL Server Management Studio\13.0\ComponentModelCache

This folder was not empty. I closed both Visual Studio and Management Studio, and deleted the files from this folder.

Afterwards, both Management Studio and Visual Studio launched without error.

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

Node.js Error: Cannot find module express

I'm not proud sharing this, but in my case I had:


 //and the correct form is:
 require('express-handlebars'); //Use dash instead.

nodejs npm global config missing on windows

It looks like the files npm uses to edit its config files are not created on a clean install, as npm has a default option for each one. This is why you can still get options with npm config get <option>: having those files only overrides the defaults, it doesn't create the options from scratch.

I had never touched my npm config stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc (on a Windows 8.1 machine with Git Bash), yet I could run npm config get <something> and, if it was a correct npm option, it returned a value. When I ran npm config set <option> <value>, the file ~/.npmrc seemed to be created automatically, with the option & its value as the only non-commented-out line.

As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc is deleted, too, and recreated if you set anything else later.

In your case (assuming it is still the same over a year later), it looks like you never set the proxy option in npm. Therefore, as npm's config help page says, it is set to whatever your http_proxy (case-insensitive) environment variable is. This means there is nothing to delete, unless you want to "delete" your HTTP proxy, although you could set the option or environment variable to something else and hope neither breaks your set-up somehow.

Repository access denied. access via a deployment key is read-only

Sometimes it doesn't work because you manually set another key for bitbucket in ~/.ssh/config.

How to add default signature in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

JSchException: Algorithm negotiation fail

I had the same issue, running Netbeans 8.0 on Windows, and JRE 1.7.

I just installed JRE 1.8 from (note that it's called Version 8 but it's version 1.8 when you install it), and it fixed it.

Failed loading english.pickle with

This is what worked for me just now:

# Do this in a separate python interpreter session, since you only have to do it once
import nltk'punkt')

# Do this in your ipython notebook or analysis script
from nltk.tokenize import word_tokenize

sentences = [
    "Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.",
    "Professor Plum has a green plant in his study.",
    "Miss Scarlett watered Professor Plum's green plant while he was away from his office last week."

sentences_tokenized = []
for s in sentences:

sentences_tokenized is a list of a list of tokens:

[['Mr.', 'Green', 'killed', 'Colonel', 'Mustard', 'in', 'the', 'study', 'with', 'the', 'candlestick', '.', 'Mr.', 'Green', 'is', 'not', 'a', 'very', 'nice', 'fellow', '.'],
['Professor', 'Plum', 'has', 'a', 'green', 'plant', 'in', 'his', 'study', '.'],
['Miss', 'Scarlett', 'watered', 'Professor', 'Plum', "'s", 'green', 'plant', 'while', 'he', 'was', 'away', 'from', 'his', 'office', 'last', 'week', '.']]

The sentences were taken from the example ipython notebook accompanying the book "Mining the Social Web, 2nd Edition"

How to decrypt an encrypted Apple iTunes iPhone backup?

Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.

You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.

Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.

I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.

Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.

I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.

In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.

Good luck!

Counting the number of files in a directory using Java

This might not be appropriate for your application, but you could always try a native call (using jni or jna), or exec a platform-specific command and read the output before falling back to list().length. On *nix, you could exec ls -1a | wc -l (note - that's dash-one-a for the first command, and dash-lowercase-L for the second). Not sure what would be right on windows - perhaps just a dir and look for the summary.

Before bothering with something like this I'd strongly recommend you create a directory with a very large number of files and just see if list().length really does take too long. As this blogger suggests, you may not want to sweat this.

I'd probably go with Varkhan's answer myself.

How do I get a file's last modified time in Perl?

You need the stat call, and the file name:

my $last_mod_time = (stat ($file))[9];

Perl also has a different version:

my $last_mod_time = -M $file;

but that value is relative to when the program started. This is useful for things like sorting, but you probably want the first version.

Emulate/Simulate iOS in Linux
On this site, you can emulate a lot of iOS's devices online.

Can't use WAMP , port 80 is used by IIS 7.5

Yes, you can just change the port to to any number. For instance change Listen 80 to Listen 81 in the httpd.conf file. Now try with http://localhost:81 and it will respond on port 81!!

How to leave space in HTML

“Insensitive to space” is an oversimplification. A more accurate description is that consecutive whitespace characters (spaces, tabs, newlines) are equivalent to a single space, in normal content.

You make empty spaces between words using space characters: “hello world”. I you want more space, you should consider what you are doing, since in normal text content, that does not make sense. For spacing elements, use CSS margin properties.

To get useful example codes, you need to describe a specific problem, like markup and a description of desired rendering.

API Gateway CORS: no 'Access-Control-Allow-Origin' header

I found a simple solution within

API Gateway > Select your API endpoint > Select the method (in my case it was the POST)

Now there is a dropdown ACTIONS > Enable CORS .. select it.

Now select the dropdown ACTIONS again > Deploy API (re-deploy it)

enter image description here

It worked !

Calculating arithmetic mean (one type of average) in Python

from statistics import mean

for example

from statistics import mean


and result is


How to edit a JavaScript alert box title?

I had a similar issue when I wanted to change the box title and button title of the default confirm box. I have gone for the Jquery Ui dialog plugin

When I had the following:

function testConfirm() {
  if (confirm("Are you sure you want to delete?")) {
    //some stuff

I have changed it to:

function testConfirm() {

  var $dialog = $('<div></div>')
    .html("Are you sure you want to delete?")
      resizable: false,
      title: "Confirm Deletion",
      modal: true,
      buttons: {
        Cancel: function() {
        "Delete": function() {
          //some stuff


Can be seen working here

Hope that helps.

How to send a html email with the bash command "sendmail"?

The following works:

echo "From: ${from}";
echo "To: ${to}";
echo "Subject: ${subject}";
echo "Content-Type: text/html";
echo "MIME-Version: 1.0";
echo "";
echo "${message}";
) | sendmail -t

For troubleshooting msmtp, which is compatible with sendmail, see:

Convert datetime value into string


  DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;

mysql update query with sub query

The main issue is that the inner query cannot be related to your where clause on the outer update statement, because the where filter applies first to the table being updated before the inner subquery even executes. The typical way to handle a situation like this is a multi-table update.

  Competition as C
  inner join (
    select CompetitionId, count(*) as NumberOfTeams
    from PicksPoints as p
    where UserCompetitionID is not NULL
    group by CompetitionID
  ) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = A.NumberOfTeams


Reading a .txt file using Scanner class in Java

You should use either

File file = new File("bin/10_Random.txt");


File file = new File("src/10_Random.txt");

Relative to the project folder in Eclipse.

How to select the first row of each group?

Window functions:

Something like this should do the trick:

import org.apache.spark.sql.functions.{row_number, max, broadcast}
import org.apache.spark.sql.expressions.Window

val df = sc.parallelize(Seq(
  (0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
  (1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
  (2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
  (3,"cat8",35.6))).toDF("Hour", "Category", "TotalValue")

val w = Window.partitionBy($"hour").orderBy($"TotalValue".desc)

val dfTop = df.withColumn("rn", row_number.over(w)).where($"rn" === 1).drop("rn")
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

This method will be inefficient in case of significant data skew.

Plain SQL aggregation followed by join:

Alternatively you can join with aggregated data frame:

val dfMax = df.groupBy($"hour".as("max_hour")).agg(max($"TotalValue").as("max_value"))

val dfTopByJoin = df.join(broadcast(dfMax),
    ($"hour" === $"max_hour") && ($"TotalValue" === $"max_value"))

// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

It will keep duplicate values (if there is more than one category per hour with the same total value). You can remove these as follows:


Using ordering over structs:

Neat, although not very well tested, trick which doesn't require joins or window functions:

val dfTop =$"Hour", struct($"TotalValue", $"Category").alias("vs"))
  .select($"Hour", $"vs.Category", $"vs.TotalValue")
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

With DataSet API (Spark 1.6+, 2.0+):

Spark 1.6:

case class Record(Hour: Integer, Category: String, TotalValue: Double)[Record]
  .reduce((x, y) => if (x.TotalValue > y.TotalValue) x else y)

// +---+--------------+
// | _1|            _2|
// +---+--------------+
// |[0]|[0,cat26,30.9]|
// |[1]|[1,cat67,28.5]|
// |[2]|[2,cat56,39.6]|
// |[3]| [3,cat8,35.6]|
// +---+--------------+

Spark 2.0 or later:[Record]
  .reduceGroups((x, y) => if (x.TotalValue > y.TotalValue) x else y)

The last two methods can leverage map side combine and don't require full shuffle so most of the time should exhibit a better performance compared to window functions and joins. These cane be also used with Structured Streaming in completed output mode.

Don't use:

df.orderBy(...).groupBy(...).agg(first(...), ...)

It may seem to work (especially in the local mode) but it is unreliable (see SPARK-16207, credits to Tzach Zohar for linking relevant JIRA issue, and SPARK-30335).

The same note applies to


which internally uses equivalent execution plan.

Why does printf not flush after the call unless a newline is in the format string?

The stdout stream is line buffered by default, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:

Print to stderrinstead using fprintf (stderr is unbuffered by default):

fprintf(stderr, "I will be printed immediately");

Flush stdout whenever you need it to using fflush:

printf("Buffered, will be flushed");
fflush(stdout); // Will now print everything in the stdout buffer

Edit: From Andy Ross's comment below, you can also disable buffering on stdout by using setbuf:

setbuf(stdout, NULL);

or its secure version setvbuf as explained here

setvbuf(stdout, NULL, _IONBF, 0); 

Creating a constant Dictionary in C#

This is the closest thing you can get to a "CONST Dictionary":

public static int GetValueByName(string name)
    switch (name)
        case "bob": return 1;
        case "billy": return 2;
        default: return -1;

The compiler will be smart enough to build the code as clean as possible.

How to Set RadioButtonFor() in MVC 2 as Checked by default

This question on StackOverflow deals with RadioButtonListFor and the answer addresses your question too. You can set the selected property in the RadioButtonListViewModel.

SQL - select distinct only on one column

A very typical approach to this type of problem is to use row_number():

select t.*
from (select t.*,
             row_number() over (partition by number order by id) as seqnum
      from t
     ) t
where seqnum = 1;

This is more generalizable than using a comparison to the minimum id. For instance, you can get a random row by using order by newid(). You can select 2 rows by using where seqnum <= 2.

How to merge rows in a column into one cell in excel?

If you prefer to do this without VBA, you can try the following:

  1. Have your data in cells A1:A999 (or such)
  2. Set cell B1 to "=A1"
  3. Set cell B2 to "=B1&A2"
  4. Copy cell B2 all the way down to B999 (e.g. by copying B2, selecting cells B3:B99 and pasting)

Cell B999 will now contain the concatenated text string you are looking for.

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.


Check this SO question that explains how to do it.

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT , COUNT(*) AS player_count
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t

Remove the first character of a string

Depending on the structure of the string, you can use lstrip:

str = str.lstrip(':')

But this would remove all colons at the beginning, i.e. if you have ::foo, the result would be foo. But this function is helpful if you also have strings that do not start with a colon and you don't want to remove the first character then.

How to import set of icons into Android Studio project

Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.

How to make an element width: 100% minus padding?

Use css calc()

Super simple and awesome.

input {
    width: -moz-calc(100% - 15px);
    width: -webkit-calc(100% - 15px);
    width: calc(100% - 15px);

As seen here: Div width 100% minus fixed amount of pixels
By webvitaly (
Original source:

Just copied this over here, because I almost missed it in the other thread.

WPF button click in C# code

Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;

private void btn1_Click(object sender, RoutedEventArgs e)
    // do something

How do I prevent a Gateway Timeout with FastCGI on Nginx

In http nginx section (/etc/nginx/nginx.conf) add or modify:

keepalive_timeout 300s

In server nginx section (/etc/nginx/sites-available/ add these lines:

client_max_body_size 50M;
fastcgi_buffers 8 1600k;
fastcgi_buffer_size 3200k;
fastcgi_connect_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;

In php file in the case (/etc/php/7.X/fpm/pool.d/www.conf) modify:

request_terminate_timeout = 300

I hope help you.

Remove a modified file from pull request

Switch to the branch from which you created the pull request:

$ git checkout pull-request-branch

Overwrite the modified file(s) with the file in another branch, let's consider it's master:

git checkout origin/master -- src/main/java/

Commit and push it to the remote:

git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch

Python script header

From the manpage for env (GNU coreutils 6.10):

env - run a program in a modified environment

In theory you could use env to reset the environment (removing many of the existing environment variables) or add additional environment variables in the script header. Practically speaking, the two versions you mentioned are identical. (Though others have mentioned a good point: specifying python through env lets you abstractly specify python without knowing its path.)

How can I see an the output of my C programs using Dev-C++?

Add a line getchar(); or system("pause"); before your return 0; in main function. It will work for you.

How can I resolve the error: "The command [...] exited with code 1"?

I know this is too late for sure, but, this could help someone as well.

In my case, i found that the source file is being used by another process which was restricting from copying to the destination. I found that by using command prompt ( just copy paste the post build command to the command prompt and executed gave me the error info).

Make sure that you can copy from the command prompt,

Convert Base64 string to an image file?

This code worked for me.

$decoded = base64_decode($base64);_x000D_
$file = 'invoice.pdf';_x000D_
file_put_contents($file, $decoded);_x000D_
if (file_exists($file)) {_x000D_
    header('Content-Description: File Transfer');_x000D_
    header('Content-Type: application/octet-stream');_x000D_
    header('Content-Disposition: attachment; filename="'.basename($file).'"');_x000D_
    header('Expires: 0');_x000D_
    header('Cache-Control: must-revalidate');_x000D_
    header('Pragma: public');_x000D_
    header('Content-Length: ' . filesize($file));_x000D_

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

If you want to use default you don't need to modify mail.php file.

  1. Create account on
  2. Go to Inboxes > My Inbox > SMTP Settings > Integration Laravel
  3. Modify .env file and replace all nulls of correct credentials:
  1. Run:
php artisan config:cache

If you are using Gmail there is an instruction for Gmail:

What does the DOCKER_HOST variable do?

Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:

$(boot2docker shellinit)

I had tested these commands:

>>  docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>>  boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
    export DOCKER_HOST=tcp://
    export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
    export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory

Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)...

>>  $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>>  docker info
Containers: 3

jQuery date/time picker

My best experience with a datepicker is with the prototype-based AnyTime. I know that's not jQuery, but it may still be worth the compromise for you. I know absolutely no prototype, and it's still easy enough to work with.

One caveat I've found: it is not forward compatible on some browsers. That is, it did not work with a newer version of prototype on Chrome.

How to use 'find' to search for files created on a specific date?

cp `ls -ltr | grep 'Jun 14' | perl -wne 's/^.*\s+(\S+)$/$1/; print $1 . "\n";'` /some_destination_dir

JavaScript replace \n with <br />

Use a regular expression for .replace().:

messagetoSend = messagetoSend.replace(/\n/g, "<br />");

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");

HTML5 event handling(onfocus and onfocusout) using angular 2

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

works for me from Pardeep Jain

Is it possible to delete an object's property in PHP?

This also works if you are looping over an object.


No need to use brackets.

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had same issue and I solved it by "pod setup" after installing cocoapods.

Python JSON dump / append to .txt with each variable on new line

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

Does MS Access support "CASE WHEN" clause if connect with ODBC?

I have had to use a multiple IIF statement to create a similar result in ACCESS SQL.

IIf([refi type] Like "FHA ST*","F",IIf([refi type]="VA IRRL","V"))

All remaining will stay Null.

How does setTimeout work in Node.JS?

The only way to ensure code is executed is to place your setTimeout logic in a different process.

Use the child process module to spawn a new node.js program that does your logic and pass data to that process through some kind of a stream (maybe tcp).

This way even if some long blocking code is running in your main process your child process has already started itself and placed a setTimeout in a new process and a new thread and will thus run when you expect it to.

Further complication are at a hardware level where you have more threads running then processes and thus context switching will cause (very minor) delays from your expected timing. This should be neglible and if it matters you need to seriously consider what your trying to do, why you need such accuracy and what kind of real time alternative hardware is available to do the job instead.

In general using child processes and running multiple node applications as separate processes together with a load balancer or shared data storage (like redis) is important for scaling your code.

Generate random password string with requirements in javascript

var letters = ['a','b','c','d','e','f','g','h','i','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
    var numbers = [0,1,2,3,4,5,6,7,8,9];
    var randomstring = '';

        for(var i=0;i<5;i++){
            var rlet = Math.floor(Math.random()*letters.length);
            randomstring += letters[rlet];
        for(var i=0;i<3;i++){
            var rnum = Math.floor(Math.random()*numbers.length);
            randomstring += numbers[rnum];

Convert a char to upper case using regular expressions (EditPad Pro)

I know this thread is about EditPad Pro, but I came here because I had the same need with a javascript regexp.

For the people who are here needing the same tip, you can use a function or lambda as the replace argument.

I use the function below to convert css names with - to the javascript equivalent, for example, "border-top" will be transformed into "borderTop":

    s = s.replace(/\-[a-z]/g, x => x[1].toUpperCase());

Using with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(, space, txt);

Example gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

  onClick={ this.props.onClick } 

onClick(e) {


Custom Adapter for List View

It is very simple.

import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

 * Created by Belal on 9/14/2017.

//we need to extend the ArrayAdapter class as we are building an adapter
public class MyListAdapter extends ArrayAdapter<Hero> {

    //the list values in the List of type hero 
    List<Hero> heroList;

    //activity context 
    Context context;

    //the layout resource file for the list items
    int resource;

    //constructor initializing the values 
    public MyListAdapter(Context context, int resource, List<Hero> heroList) {
        super(context, resource, heroList);
        this.context = context;
        this.resource = resource;
        this.heroList = heroList;

    //this will return the ListView Item as a View
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        //we need to get the view of the xml for our list item
        //And for this we need a layoutinflater
        LayoutInflater layoutInflater = LayoutInflater.from(context);

        //getting the view
        View view = layoutInflater.inflate(resource, null, false);

        //getting the view elements of the list from the view
        ImageView imageView = view.findViewById(;
        TextView textViewName = view.findViewById(;
        TextView textViewTeam = view.findViewById(;
        Button buttonDelete = view.findViewById(;

        //getting the hero of the specified position
        Hero hero = heroList.get(position);

        //adding values to the list item 

        //adding a click listener to the button to remove item from the list
        buttonDelete.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                //we will call this method to remove the selected value from the list
                //we are passing the position which is to be removed in the method 

        //finally returning the view
        return view;

    //this method will remove the item from the list 
    private void removeHero(final int position) {
        //Creating an alert dialog to confirm the deletion
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("Are you sure you want to delete this?");

        //if the response is positive in the alert 
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {

                //removing the item 

                //reloading the list 

        //if response is negative nothing is being done 
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {


        //creating and displaying the alert dialog 
        AlertDialog alertDialog = builder.create();;

Source: Custom ListView Android Tutorial

Differences between git pull origin master & git pull origin/master

git pull origin master will pull changes from the origin remote, master branch and merge them to the local checked-out branch.

git pull origin/master will pull changes from the locally stored branch origin/master and merge that to the local checked-out branch. The origin/master branch is essentially a "cached copy" of what was last pulled from origin, which is why it's called a remote branch in git parlance. This might be somewhat confusing.

You can see what branches are available with git branch and git branch -r to see the "remote branches".

No connection could be made because the target machine actively refused it?

This is really specific, but if you receive this error after trying to connect to a database using mongo, what worked for me was running mongod.exe before running mongo.exe and then the connection worked fine. Hope this helps someone.

How to find char in string and get all the indexes?

def find_offsets(haystack, needle):
    Find the start of all (possibly-overlapping) instances of needle in haystack
    offs = -1
    while True:
        offs = haystack.find(needle, offs+1)
        if offs == -1:
            yield offs

for offs in find_offsets("ooottat", "o"):
    print offs

results in


How to unapply a migration in ASP.NET Core with EF Core

In order to unapply a migration in EF Core 1.0 use the command:

dotnet ef database update {migration_name}

Use the migration name of the migration until which you would like to preserve your changes. The list of names of the migration can be found using:

dotnet ef migrations list

Case in Select Statement

you can also use:

         WHEN upper( like 'P%' THEN
         WHEN upper( like 'T%' THEN
         WHEN upper( like 'D%' THEN
       END as type
FROM table t

MSOnline can't be imported on PowerShell (Connect-MsolService error)

Connects to both Office 365 and Exchange Online in one easy to use script.

REMINDER: You must have the following installed in order to manage Office 365 via PowerShell.

Microsoft Online Services Sign-in Assistant:

Azure AD Module for Windows PowerShell 32 bit - 64 bit -


I want to declare an empty array in java and then I want do update it but the code is not working

So the issue is in your array declaration you are declaring an empty array with the empty curly braces{} instead of an array that allows slots.

Roughly speaking, there can be three types of inputs :

 1. int array[] = null; #Does not point to any memory locations so is a null arrau
 2. int array[] = {) which is sort of equivalent to int array[] = new int[0];
 3. int array[] = new int[n] where n is some number indicating the number of 
memory locations in the array

Why shouldn't I use mysql_* functions in PHP?

PHP offers three different APIs to connect to MySQL. These are the mysql(removed as of PHP 7), mysqli, and PDO extensions.

The mysql_* functions used to be very popular, but their use is not encouraged anymore. The documentation team is discussing the database security situation, and educating users to move away from the commonly used ext/mysql extension is part of this (check php.internals: deprecating ext/mysql).

And the later PHP developer team has taken the decision to generate E_DEPRECATED errors when users connect to MySQL, whether through mysql_connect(), mysql_pconnect() or the implicit connection functionality built into ext/mysql.

ext/mysql was officially deprecated as of PHP 5.5 and has been removed as of PHP 7.

See the Red Box?

When you go on any mysql_* function manual page, you see a red box, explaining it should not be used anymore.


Moving away from ext/mysql is not only about security, but also about having access to all the features of the MySQL database.

ext/mysql was built for MySQL 3.23 and only got very few additions since then while mostly keeping compatibility with this old version which makes the code a bit harder to maintain. Missing features that is not supported by ext/mysql include: (from PHP manual).

Reason to not use mysql_* function:

  • Not under active development
  • Removed as of PHP 7
  • Lacks an OO interface
  • Doesn't support non-blocking, asynchronous queries
  • Doesn't support prepared statements or parameterized queries
  • Doesn't support stored procedures
  • Doesn't support multiple statements
  • Doesn't support transactions
  • Doesn't support all of the functionality in MySQL 5.1

Above point quoted from Quentin's answer

Lack of support for prepared statements is particularly important as they provide a clearer, less error prone method of escaping and quoting external data than manually escaping it with a separate function call.

See the comparison of SQL extensions.

Suppressing deprecation warnings

While code is being converted to MySQLi/PDO, E_DEPRECATED errors can be suppressed by setting error_reporting in php.ini to exclude E_DEPRECATED:

error_reporting = E_ALL ^ E_DEPRECATED

Note that this will also hide other deprecation warnings, which, however, may be for things other than MySQL. (from PHP manual)

The article PDO vs. MySQLi: Which Should You Use? by Dejan Marjanovic will help you to choose.

And a better way is PDO, and I am now writing a simple PDO tutorial.

A simple and short PDO tutorial

Q. First question in my mind was: what is `PDO`?

A. “PDO – PHP Data Objects – is a database access layer providing a uniform method of access to multiple databases.”

alt text

Connecting to MySQL

With mysql_* function or we can say it the old way (deprecated in PHP 5.5 and above)

$link = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('testdb', $link);
mysql_set_charset('UTF-8', $link);

With PDO: All you need to do is create a new PDO object. The constructor accepts parameters for specifying the database source PDO's constructor mostly takes four parameters which are DSN (data source name) and optionally username, password.

Here I think you are familiar with all except DSN; this is new in PDO. A DSN is basically a string of options that tell PDO which driver to use, and connection details. For further reference, check PDO MySQL DSN.

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');

Note: you can also use charset=UTF-8, but sometimes it causes an error, so it's better to use utf8.

If there is any connection error, it will throw a PDOException object that can be caught to handle Exception further.

Good read: Connections and Connection management ¶

You can also pass in several driver options as an array to the fourth parameter. I recommend passing the parameter which puts PDO into exception mode. Because some PDO drivers don't support native prepared statements, so PDO performs emulation of the prepare. It also lets you manually enable this emulation. To use the native server-side prepared statements, you should explicitly set it false.

The other is to turn off prepare emulation which is enabled in the MySQL driver by default, but prepare emulation should be turned off to use PDO safely.

I will later explain why prepare emulation should be turned off. To find reason please check this post.

It is only usable if you are using an old version of MySQL which I do not recommended.

Below is an example of how you can do it:

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 
              array(PDO::ATTR_EMULATE_PREPARES => false,

Can we set attributes after PDO construction?

Yes, we can also set some attributes after PDO construction with the setAttribute method:

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Error Handling

Error handling is much easier in PDO than mysql_*.

A common practice when using mysql_* is:

//Connected to MySQL
$result = mysql_query("SELECT * FROM table", $link) or die(mysql_error($link));

OR die() is not a good way to handle the error since we can not handle the thing in die. It will just end the script abruptly and then echo the error to the screen which you usually do NOT want to show to your end users, and let bloody hackers discover your schema. Alternately, the return values of mysql_* functions can often be used in conjunction with mysql_error() to handle errors.

PDO offers a better solution: exceptions. Anything we do with PDO should be wrapped in a try-catch block. We can force PDO into one of three error modes by setting the error mode attribute. Three error handling modes are below.

  • PDO::ERRMODE_SILENT. It's just setting error codes and acts pretty much the same as mysql_* where you must check each result and then look at $db->errorInfo(); to get the error details.
  • PDO::ERRMODE_WARNING Raise E_WARNING. (Run-time warnings (non-fatal errors). Execution of the script is not halted.)
  • PDO::ERRMODE_EXCEPTION: Throw exceptions. It represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about exceptions in PHP. It acts very much like or die(mysql_error());, when it isn't caught. But unlike or die(), the PDOException can be caught and handled gracefully if you choose to do so.

Good read:


$stmt->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );

And you can wrap it in try-catch, like below:

try {
    //Connect as appropriate as above
    $db->query('hi'); //Invalid query!
catch (PDOException $ex) {
    echo "An Error occured!"; //User friendly message/message you want to show to user

You do not have to handle with try-catch right now. You can catch it at any time appropriate, but I strongly recommend you to use try-catch. Also it may make more sense to catch it at outside the function that calls the PDO stuff:

function data_fun($db) {
    $stmt = $db->query("SELECT * FROM table");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);

//Then later
try {
catch(PDOException $ex) {
    //Here you can handle error and show message/perform action you want.

Also, you can handle by or die() or we can say like mysql_*, but it will be really varied. You can hide the dangerous error messages in production by turning display_errors off and just reading your error log.

Now, after reading all the things above, you are probably thinking: what the heck is that when I just want to start leaning simple SELECT, INSERT, UPDATE, or DELETE statements? Don't worry, here we go:

Selecting Data

PDO select image

So what you are doing in mysql_* is:

$result = mysql_query('SELECT * from table') or die(mysql_error());

$num_rows = mysql_num_rows($result);

while($row = mysql_fetch_assoc($result)) {
    echo $row['field1'];

Now in PDO, you can do this like:

$stmt = $db->query('SELECT * FROM table');

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['field1'];


$stmt = $db->query('SELECT * FROM table');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

//Use $results

Note: If you are using the method like below (query()), this method returns a PDOStatement object. So if you want to fetch the result, use it like above.

foreach($db->query('SELECT * FROM table') as $row) {
    echo $row['field1'];

In PDO Data, it is obtained via the ->fetch(), a method of your statement handle. Before calling fetch, the best approach would be telling PDO how you’d like the data to be fetched. In the below section I am explaining this.

Fetch Modes

Note the use of PDO::FETCH_ASSOC in the fetch() and fetchAll() code above. This tells PDO to return the rows as an associative array with the field names as keys. There are many other fetch modes too which I will explain one by one.

First of all, I explain how to select fetch mode:


In the above, I have been using fetch(). You can also use:

Now I come to fetch mode:

  • PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

There are even more choices! Read about them all in PDOStatement Fetch documentation..

Getting the row count:

Instead of using mysql_num_rows to get the number of returned rows, you can get a PDOStatement and do rowCount(), like:

$stmt = $db->query('SELECT * FROM table');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';

Getting the Last Inserted ID

$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();

Insert and Update or Delete statements

Insert and update PDO image

What we are doing in mysql_* function is:

$results = mysql_query("UPDATE table SET field='value'") or die(mysql_error());
echo mysql_affected_rows($result);

And in pdo, this same thing can be done by:

$affected_rows = $db->exec("UPDATE table SET field='value'");
echo $affected_rows;

In the above query PDO::exec execute an SQL statement and returns the number of affected rows.

Insert and delete will be covered later.

The above method is only useful when you are not using variable in query. But when you need to use a variable in a query, do not ever ever try like the above and there for prepared statement or parameterized statement is.

Prepared Statements

Q. What is a prepared statement and why do I need them?
A. A prepared statement is a pre-compiled SQL statement that can be executed multiple times by sending only the data to the server.

The typical workflow of using a prepared statement is as follows (quoted from Wikipedia three 3 point):

  1. Prepare: The statement template is created by the application and sent to the database management system (DBMS). Certain values are left unspecified, called parameters, placeholders or bind variables (labelled ? below):

    INSERT INTO PRODUCT (name, price) VALUES (?, ?)

  2. The DBMS parses, compiles, and performs query optimization on the statement template, and stores the result without executing it.

  3. Execute: At a later time, the application supplies (or binds) values for the parameters, and the DBMS executes the statement (possibly returning a result). The application may execute the statement as many times as it wants with different values. In this example, it might supply 'Bread' for the first parameter and 1.00 for the second parameter.

You can use a prepared statement by including placeholders in your SQL. There are basically three ones without placeholders (don't try this with variable its above one), one with unnamed placeholders, and one with named placeholders.

Q. So now, what are named placeholders and how do I use them?
A. Named placeholders. Use descriptive names preceded by a colon, instead of question marks. We don't care about position/order of value in name place holder:

 $stmt->bindParam(':bla', $bla);


You can also bind using an execute array as well:

$stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name");
$stmt->execute(array(':name' => $name, ':id' => $id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Another nice feature for OOP friends is that named placeholders have the ability to insert objects directly into your database, assuming the properties match the named fields. For example:

class person {
    public $name;
    public $add;
    function __construct($a,$b) {
        $this->name = $a;
        $this->add = $b;

$demo = new person('john','29 bla district');
$stmt = $db->prepare("INSERT INTO table (name, add) value (:name, :add)");

Q. So now, what are unnamed placeholders and how do I use them?
A. Let's have an example:

$stmt = $db->prepare("INSERT INTO folks (name, add) values (?, ?)");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->bindValue(2, $add, PDO::PARAM_STR);


$stmt = $db->prepare("INSERT INTO folks (name, add) values (?, ?)");
$stmt->execute(array('john', '29 bla district'));

In the above, you can see those ? instead of a name like in a name place holder. Now in the first example, we assign variables to the various placeholders ($stmt->bindValue(1, $name, PDO::PARAM_STR);). Then, we assign values to those placeholders and execute the statement. In the second example, the first array element goes to the first ? and the second to the second ?.

NOTE: In unnamed placeholders we must take care of the proper order of the elements in the array that we are passing to the PDOStatement::execute() method.


  1. SELECT:

    $stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name");
    $stmt->execute(array(':name' => $name, ':id' => $id));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  2. INSERT:

    $stmt = $db->prepare("INSERT INTO table(field1,field2) VALUES(:field1,:field2)");
    $stmt->execute(array(':field1' => $field1, ':field2' => $field2));
    $affected_rows = $stmt->rowCount();
  3. DELETE:

    $stmt = $db->prepare("DELETE FROM table WHERE id=:id");
    $stmt->bindValue(':id', $id, PDO::PARAM_STR);
    $affected_rows = $stmt->rowCount();
  4. UPDATE:

    $stmt = $db->prepare("UPDATE table SET name=? WHERE id=?");
    $stmt->execute(array($name, $id));
    $affected_rows = $stmt->rowCount();


However PDO and/or MySQLi are not completely safe. Check the answer Are PDO prepared statements sufficient to prevent SQL injection? by ircmaxell. Also, I am quoting some part from his answer:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES GBK');
$stmt = $pdo->prepare("SELECT * FROM test WHERE name = ? LIMIT 1");
$stmt->execute(array(chr(0xbf) . chr(0x27) . " OR 1=1 /*"));

Tool to compare directories (Windows 7)

I use WinMerge. It is free and works pretty well (works for files and directories).

Why emulator is very slow in Android Studio?

The Best Solution is to use Android Emulator with Intel Virtualization Technology.

Now if your system have a Processor that have a feature called as Intel Virtualization Technology, then Intel X86 images will be huge benefit for you. because it supports Intel® Hardware Accelerated Execution Manager (Intel® HAXM).

To check that your processor support HAXM or not : Click Here

You need to manually install the Intel HAXM in your system. Follow these steps for that.

  • First of all go to - adt -> extras -> intel -> Hardware_Accelerated_Execution_Manager
  • Make sure that Intel Virtualization is enabled from BIOS Settings.
  • Now install Intel HAXM in your system and select amount of memory(i prefer to set it as default value).
  • After installation create new Android Virtual Device (AVD) which should have a Target of API Level xx
  • Now set the CPU/ABI as Intel Atom(x86).
  • If you are on Windows then do not set RAM value more than 768 MB while setting up an emulator.
  • Run the emulator. It will be blazing fast then ordinary one.

Hope it will be helpful for you. :) Thanks.

How to determine device screen size category (small, normal, large, xlarge) using code?

private String getDeviceDensity() {
    int density = mContext.getResources().getDisplayMetrics().densityDpi;
    switch (density)
        case DisplayMetrics.DENSITY_MEDIUM:
            return "MDPI";
        case DisplayMetrics.DENSITY_HIGH:
            return "HDPI";
        case DisplayMetrics.DENSITY_LOW:
            return "LDPI";
        case DisplayMetrics.DENSITY_XHIGH:
            return "XHDPI";
        case DisplayMetrics.DENSITY_TV:
            return "TV";
        case DisplayMetrics.DENSITY_XXHIGH:
            return "XXHDPI";
        case DisplayMetrics.DENSITY_XXXHIGH:
            return "XXXHDPI";
            return "Unknown";

How to make the main content div fill height of screen with css

These are not necessary

  • remove height in %
  • remove jQuery

Stretch div using bottom & top :

    position: absolute;
    top: 40px; /* Header Height */
    bottom: 20px; /* Footer Height */
    width: 100%;

check my code :

or check here:

body {_x000D_
.header {_x000D_
    height: 40px;_x000D_
    background-color: red;_x000D_
.mainBody {_x000D_
    background-color: yellow;_x000D_
    position: absolute;_x000D_
    top: 40px;_x000D_
    bottom: 20px;_x000D_
.content {_x000D_
.footer {_x000D_
    height: 20px;_x000D_
    background-color: blue;_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
<div class="header" >_x000D_
<div class="mainBody">_x000D_
    <div class="content" >Hello world</div>_x000D_
<div class="footer">_x000D_

How do I accomplish an if/else in mustache.js?

You can define a helper in the view. However, the conditional logic is somewhat limited. Moxy-Stencil ( seems to address this with "parameterized" helpers, eg:

{{isActive param}}

and in the view:

view.isActive = function (path: string){ return path === this.path ? "class='active'" : '' }

html text input onchange event

I used this line to listen for input events from javascript.
It is useful because it listens for text change and text pasted events.

myElement.addEventListener('input', e => { myEvent() });

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

Ok, I figured it out. I just wrapped it in a try catch and send back null.

    public String test() {
            String cert=null;
            String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN 
                     where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
            try {
                Object o = (String) jdbc.queryForObject(sql, String.class);
                cert = (String) o;
            } catch (EmptyResultDataAccessException e) {
            return cert;

What does flex: 1 mean?

In Chrome Ver 84, flex: 1 is equivalent to flex: 1 1 0%. The followings are a bunch of screenshots.

enter image description here

Browser back button handling

Warn/confirm User if Back button is Pressed is as below.

window.onbeforeunload = function() { return "Your work will be lost."; };

You can get more information using below mentioned links.

Disable Back Button in Browser using JavaScript

I hope this will help to you.

Removing an item from a select box

You can delete the selected item with this:

$("#selectBox option:selected").remove();

This is useful if you have a list and not a dropdown.

Check if string is in a pandas dataframe

Pandas seem to be recommending df.to_numpy since the other methods still raise a FutureWarning:

So, an alternative that would work int this case is:

c = b.to_numpy().tolist()
if 'Mel' in c:
     print("Mel is in the dataframe column Names")

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

Here is the closest solution I could get using just css.


<div class="ellipsis"> <span>...</span>
Hello this is Mr_Green from Stackoverflow. I love CSS. I live in CSS and I will never leave working on CSS even my work is on other technologies.</div>


div {
    height: 3em;
    line-height: 1.5em;
    width: 80%;
    border: 1px solid green;
    overflow: hidden;
    position: relative;
div:after {
    content:". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . .";
    background-color: white;
    color: white;
    display: inline;
    position: relative;
    box-shadow: 8px 1px 1px white;
    z-index: 1;
span {
    position: absolute;
    bottom: 0px;
    right: 0px;
    background-color: white;

Working Fiddle (resize the window to check)

Link to my blog for explanation

Updated Fiddle

I hope now some css expert would have got idea on how to make it perfect. :)

How to make a HTML Page in A4 paper size page(s)?

Create section with each page, and use the below code to adjust margins, height and width.

If you are printing A4 size.

Then user

Size : 8.27in and 11.69 inches

@page Section1 {
    size: 8.27in 11.69in; 
    margin: .5in .5in .5in .5in; 
    mso-header-margin: .5in; 
    mso-footer-margin: .5in; 
    mso-paper-source: 0;

div.Section1 {
    page: Section1;

then create a div with all your content in it.

<div class="Section1"> 
    type your content here... 


@media print {
    .page-break { 
        height: 0; 
        page-break-before: always; 
        margin: 0; 
        border-top: none; 

body, p, a,
span, td { 
    font-size: 9pt;
    font-family: Arial, Helvetica, sans-serif;

body {
    margin-left: 2em; 
    margin-right: 2em;

.page {
    height: 947px;
    padding-top: 5px;
    page-break-after: always;   
    font-family: Arial, Helvetica, sans-serif;
    position: relative;
    border-bottom: 1px solid #000;

How to close a web page on a button click, a hyperlink or a link button click?

double click the button and add write // this.close();

  private void buttonClick(object sender, EventArgs e)

How to hide a div from code (c#)

The above answers are fine but I would add to be sure the div is defined in the designer.cs file. This doesn't always happen when adding a div to the .aspx file. Not sure why but there are threads concerning this issue in this forum. Eg:

protected global::System.Web.UI.HtmlControls.HtmlGenericControl theDiv;

Changing API level Android Studio

Changing the minSdkVersion in the manifest is not necessary. If you change it in the gradle build file, as seen below, you accomplish what you need to do.

defaultConfig {
   applicationId "com.demo.myanswer"
   minSdkVersion 14
   targetSdkVersion 23
   versionCode 1
   versionName "1.0"

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

How to zip a whole folder using PHP

Try this:

$zip = new ZipArchive;
$zip->open('', ZipArchive::CREATE);
foreach (glob("target_folder/*") as $file) {
    if ($file != 'target_folder/important.txt') unlink($file);

This will not zip recursively though.

How do I set the visibility of a text box in SSRS using an expression?

This didn't work

=IIf((CountRows("ScannerStatisticsData") = 0),False,True)

but this did and I can't really explain why

=IIf((CountRows("ScannerStatisticsData") < 1),False,True)

guess SSRS doesn't like equal comparisons as much as less than.

How do you properly determine the current script directory?

#!/usr/bin/env python
import inspect
import os
import sys

def get_script_dir(follow_symlinks=True):
    if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze
        path = os.path.abspath(sys.executable)
        path = inspect.getabsfile(get_script_dir)
    if follow_symlinks:
        path = os.path.realpath(path)
    return os.path.dirname(path)


It works on CPython, Jython, Pypy. It works if the script is executed using execfile() (sys.argv[0] and __file__ -based solutions would fail here). It works if the script is inside an executable zip file (/an egg). It works if the script is "imported" (PYTHONPATH=/path/to/ python -mscript_to_run) from a zip file; it returns the archive path in this case. It works if the script is compiled into a standalone executable (sys.frozen). It works for symlinks (realpath eliminates symbolic links). It works in an interactive interpreter; it returns the current working directory in this case.

Invalidating JSON Web Tokens


An approach that I take as being practical is to store a refresh token (which can be a GUID) and a counterpart refresh token ID (that does not change no matter how many refreshes are done) on the database and add them as claims for the user when the user's JWT is being generated. An alternative to a database can be used, e.g. memory cache. But I'm using database in this answer.

Then, create a JWT refresh Web API endpoint that the client can call before the expiry of the JWT. When the refresh is called, get the refresh token from the claims in the JWT.

On any call to the JWT refresh endpoint, validate the current refresh token and the refresh token ID as a pair on the database. Generate a new refresh token, and use it to replace the old refresh token on the database, using the refresh token ID. Remember they are claims that can be extracted from the JWT

Extract the user's claims from the current JWT. Begin the process of generating a new JWT. Replace the value of the old refresh token claim with the newly generated refresh token that has also been newly saved on the database. With all that, generate the new JWT and send it to the client.

So, after a refresh token has been used, whether by the intended user or an attacker, any other attempt to use a/the refresh token, that is not paired, on the database, with its refresh token ID, would not lead to the generation of a new JWT, hence preventing any client having that refresh token ID from being able to use the backend anymore, leading to a full logout of such clients (including the legitimate client).

That explains the basic information.

The next thing to add to that is to have a window for when a JWT can be refreshed, such that anything outside that window would be a suspicious activity. For example, the window can be 10min before the expiration of a JWT. The date-time a JWT was generated can be saved as a claim in that JWT itself. And when such suspicious activity occurs, i.e. when someone else tries to reuse that refresh token ID outside or within the window after it has already been used within the window, should mark the refresh token ID as invalid. Hence, even the valid owner of the refresh token ID would have to log in afresh.

A refresh token that can't be found to be paired, on the database, with a presented refresh token ID implies that the refresh token ID should be invalidated. Because an idle user may try to use a refresh token that an attacker, for example, has already used.

A JWT that was stolen and used by an attacker, before the intended user does, would be marked as invalid too when the user attempts to use the refresh token too, as explained earlier.

The only situation not covered is if a client never attempts to refresh its JWT even after an attacker may have already stolen it. But this is unlikely to happen to a client that's not in custody (or something similar) of an attacker, meaning that the client cannot be predicted by the attacker as regards when the client would stop using the backend.

If the client initiates a usual logout. The logout should be made to delete the refresh token ID and associated records from the database, hence, preventing any client from generating a refresh JWT.

open new tab(window) by clicking a link in jquery

Try this:, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

How can I inject a property value into a Spring Bean which was configured using annotations?

Personally I love this new way in Spring 3.0 from the docs:

private @Value("${propertyName}") String propertyField;

No getters or setters!

With the properties being loaded via the config:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="" name="propertiesBean"/>

To further my glee I can even control click on the EL expression in IntelliJ and it brings me to the property definition!

There's also the totally non xml version:

public class AppConfig {

    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();

JavaScript blob filename without link

Late, but since I had the same problem I add my solution:

function newFile(data, fileName) {
    var json = JSON.stringify(data);
    //IE11 support
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        let blob = new Blob([json], {type: "application/json"});
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {// other browsers
        let file = new File([json], fileName, {type: "application/json"});
        let exportUrl = URL.createObjectURL(file);

Plot 3D data in R

Adding to the solutions of others, I'd like to suggest using the plotly package for R, as this has worked well for me.

Below, I'm using the reformatted dataset suggested above, from xyz-tripplets to axis vectors x and y and a matrix z:

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

plot_ly(x=x,y=y,z=z, type="surface")

enter image description here

The rendered surface can be rotated and scaled using the mouse. This works fairly well in RStudio.

You can also try it with the built-in volcano dataset from R:

plot_ly(z=volcano, type="surface")

enter image description here

How to add new elements to an array?

There is another option which i haven't seen here and which doesn't involve "complex" Objects or Collections.

String[] array1 = new String[]{"one", "two"};
String[] array2 = new String[]{"three"};
String[] array = new String[array1.length + array2.length];
System.arraycopy(array1, 0, array, 0, array1.length);
System.arraycopy(array2, 0, array, array1.length, array2.length);

Track a new remote branch created on GitHub

When the branch is no remote branch you can push your local branch direct to the remote.

git checkout master
git push origin master

or when you have a dev branch

git checkout dev
git push origin dev

or when the remote branch exists

git branch dev -t origin/dev

There are some other posibilites to push a remote branch.

Where Sticky Notes are saved in Windows 10 1607

Sticky notes in Windows 10 are stored here: C:\Users\"Username"\Appdata\Roaming\Microsoft\Sticky Notes

If you want to restore your sticky notes from earlier versions of windwos, just copy the .snt file and place it in the above location.

N.B: Replace only if you don't have any new notes in Windows 10!

Unable to establish SSL connection, how do I fix my SSL cert?

This problem happened for me only in special cases, when I called website from some internet providers,

I've configured only ip v4 in VirtualHost configuration of apache, but some of router use ip v6, and when I added ip v6 to apache config the problem solved.

Correct way to set Bearer token with CURL

This should works

//setup the request, you can also use CURLOPT_URL
$ch = curl_init('API_URL');

// Returns the data/output as a string instead of raw data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//Set your auth headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
   'Content-Type: application/json',
   'Authorization: Bearer ' . $token

// get stringified data/output. See CURLOPT_RETURNTRANSFER
$data = curl_exec($ch);

// get info about the request
$info = curl_getinfo($ch);
// close curl resource to free up system resources

Git: add vs push vs commit

  • git add adds files to the Git index, which is a staging area for objects prepared to be commited.
  • git commit commits the files in the index to the repository, git commit -a is a shortcut to add all the modified tracked files to the index first.
  • git push sends all the pending changes to the remote repository to which your branch is mapped (eg. on GitHub).

In order to understand Git you would need to invest more effort than just glancing over the documentation, but it's definitely worth it. Just don't try to map Git commands directly to Subversion, as most of them don't have a direct counterpart.

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

.NET code to send ZPL to Zebra printers

@liquide's answer works great.

System.IO.File.Copy(inputFilePath, printerPath);

Which I found from the Zebra's ZPL Programmer's Guide Volume 1 (2005) enter image description here

NSAttributedString add text alignment

I was searching for the same issue and was able to center align the text in a NSAttributedString this way:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];

NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
[attribString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.

Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.

1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

Finding second occurrence of a substring in a string in Java

int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);

This overload starts looking for the substring from the given index.

How to provide animation when calling another activity in Android?

You must use OverridePendingTransition method to achieve it, which is in the Activity class. Sample Animations in the apidemos example's res/anim folder. Check it. More than check the demo in ApiDemos/App/Activity/animation.


public void onResume(){
    // TODO LC: preliminary support for views transitions
    this.overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);

How do I implement charts in Bootstrap?

You can use a 3rd party library like Shield UI for charting - that is tested and works well on all legacy and new web browsers and devices.

Stateless vs Stateful

A stateful app is one that stores information about what has happened or changed since it started running. Any public info about what "mode" it is in, or how many records is has processed, or whatever, makes it stateful.

Stateless apps don't expose any of that information. They give the same response to the same request, function or method call, every time. HTTP is stateless in its raw form - if you do a GET to a particular URL, you get (theoretically) the same response every time. The exception of course is when we start adding statefulness on top, e.g. with ASP.NET web apps :) But if you think of a static website with only HTML files and images, you'll know what I mean.

How to generate javadoc comments in Android Studio

Android Studio -> Preferences -> Editor -> Intentions -> Java -> Declaration -> Enable "Add JavaDoc"

And, While selecting Methods to Implement (Ctrl/Cmd + i), on the left bottom, you should be seeing checkbox to enable Copy JavaDoc.

Difference between session affinity and sticky session?

Sticky session means that when a request comes into a site from a client all further requests go to the same server initial client request accessed. I believe that session affinity is a synonym for sticky session.

Oracle: how to UPSERT (update or insert into a table?)

I've been using the first code sample for years. Notice notfound rather than count.

UPDATE tablename SET val1 = in_val1, val2 = in_val2
    WHERE val3 = in_val3;
IF ( sql%notfound ) THEN
    INSERT INTO tablename
        VALUES (in_val1, in_val2, in_val3);

The code below is the possibly new and improved code

MERGE INTO tablename USING dual ON ( val3 = in_val3 )
WHEN MATCHED THEN UPDATE SET val1 = in_val1, val2 = in_val2
    VALUES (in_val1, in_val2, in_val3)

In the first example the update does an index lookup. It has to, in order to update the right row. Oracle opens an implicit cursor, and we use it to wrap a corresponding insert so we know that the insert will only happen when the key does not exist. But the insert is an independent command and it has to do a second lookup. I don't know the inner workings of the merge command but since the command is a single unit, Oracle could have execute the correct insert or update with a single index lookup.

I think merge is better when you do have some processing to be done that means taking data from some tables and updating a table, possibly inserting or deleting rows. But for the single row case, you may consider the first case since the syntax is more common.

Fetching data from MySQL database using PHP, Displaying it in a form for editing

<form action="Delegate_update.php" method="post">
  <input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
  <input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
  <input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
  <input type="submit" name= "submit" value="Update">

look into this

T-SQL query to show table definition?

This will return columns, datatypes, and indexes defined on the table:

--List all tables in DB
select * from sysobjects where xtype = 'U'

--Table Definition
sp_help TableName

This will return triggers defined on the table:

--Triggers in SQL Table
select * from sys.triggers where parent_id = object_id(N'SQLTableName') 

LINQ to SQL - How to select specific columns and return strongly typed list

Basically you are doing it the right way. However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query):

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new Person { Name = a.Name, Age = a.Age }).ToList();

Apparently, the Person class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

class PersonInformation {
   public string Name {get;set;}
   public int Age {get;set;}

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();

You can freely swap var with List<PersonInformation> here without affecting anything (as this is what the compiler does).

Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new { a.Name, a.Age }).ToList();

Note that in all of these cases, the result is statically typed (it's type is known at compile time). The latter type is a List of a compiler generated anonymous class similar to the PersonInformation class I wrote above. As of C# 3.0, there's no dynamic typing in the language.


If you really want to return a List<Person> (which might or might not be the best thing to do), you can do this:

var result = from a in new DataContext().Persons
             where a.Age > 18
             select new { a.Name, a.Age };

List<Person> list = result.AsEnumerable()
                          .Select(o => new Person {
                                           Name = o.Name, 
                                           Age = o.Age

You can merge the above statements too, but I separated them for clarity.

Can't check signature: public key not found

There is a similar is a tomcat digital signature.

$ gpg --verify apache-tomcat-9.0.16-windows-
gpg: Signature made 2019?02? 5?  0:32:50
gpg:                using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Can't check signature: No public key

but then I use the RSA key it provided to receive the public key to verify.

$ gpg --receive-keys A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: key 10C01C5A2F6059E7: 38 signatures not checked due to missing keys
gpg: key 10C01C5A2F6059E7: public key "Mark E D Thomas <[email protected]>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg:               imported: 1

Then successfully.

$ gpg --verify
gpg: assuming signed data in ''
gpg: Signature made 2019?02? 5?  0:32:50
gpg:                using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Good signature from "Mark E D Thomas <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: A9C5 DF4D 22E9 9998 D987  5A51 10C0 1C5A 2F60 59E7

Show how many characters remaining in a HTML text box using JavaScript

I needed something like that and the solution I gave with the help of jquery is this:

<textarea class="textlimited" data-textcounterid="counter1" maxlength="30">text</textarea>
<span class='textcounter' id="counter1"></span>

With this script:

// the selector below will catch the keyup events of elements decorated with class textlimited and have a maxlength
     //get the fields limit
    var maxLength = $(this).attr("maxlength");

    // check if the limit is passed
    if(this.value.length > maxLength){
        return false;

    // find the counter element by the id specified in the source input element
    var counterElement = $(".textcounter#" + $(this).data("textcounterid"));
    // update counter 's text
    counterElement.html((maxLength - this.value.length) + " chars left");

? live demo Here

How to return only the Date from a SQL Server DateTime datatype

DECLARE @yourdate DATETIME = '11/1/2014 12:25pm'    

Pass a PHP array to a JavaScript function

You can pass PHP arrays to JavaScript using json_encode PHP function.

    $phpArray = array(
        0 => "Mon", 
        1 => "Tue", 
        2 => "Wed", 
        3 => "Thu",
        4 => "Fri", 
        5 => "Sat",
        6 => "Sun",

<script type="text/javascript">

    var jArray = <?php echo json_encode($phpArray); ?>;

    for(var i=0; i<jArray.length; i++){


How to get base URL in Web API controller?

In the action method of the request to the url "http://localhost:85458/api/ctrl/"

var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) ;

this will get you http://localhost:85458

Error in finding last used cell in Excel with VBA

I was looking for a way to mimic the CTRL+Shift+End, so dotNET solution is great, except with my Excel 2010 I need to add a set if I want to avoid an error:

Function GetLastCell(sh As Worksheet) As Range
  Set GetLastCell = sh.Cells(1, 1).SpecialCells(xlLastCell)
End Function

and how to check this for yourself:

Sub test()
  Dim ws As Worksheet, r As Range
  Set ws = ActiveWorkbook.Sheets("Sheet1")
  Set r = GetLastCell(ws)
  MsgBox r.Column & "-" & r.Row
End Sub

Get value from hashmap based on key to JSTL

I had issue with the solutions mentioned above as specifying the string key would give me javax.el.PropertyNotFoundException. The code shown below worked for me. In this I used status to count the index of for each loop and displayed the value of index I am interested on

<c:forEach items="${requestScope.key}"  var="map" varStatus="status" >
    <c:if test="${status.index eq 1}">
        <option><c:out value=${map.value}/></option>

Hiding axis text in matplotlib plots

I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my image

plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

I used the tick_params call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file.

Post to another page within a PHP script

For PHP processing, look into cURL. It will allow you to call pages on your back end and retrieve data from it. Basically you would do something like this:

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL,$fetch_url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($ch,CURLOPT_USERAGENT, $user_agent;
curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,60);
$response = curl_exec ( $ch );

You can also look into the PHP HTTP Extension.

What does the 'Z' mean in Unix timestamp '120314170138Z'?

"Z" doesn't stand for "Zulu"

I don't have any more information than the Wikipedia article cited by the two existing answers, but I believe the interpretation that "Z" stands for "Zulu" is incorrect. UTC time is referred to as "Zulu time" because of the use of Z to identify it, not the other way around. The "Z" seems to have been used to mark the time zone as the "zero zone", in which case "Z" unsurprisingly stands for "zero" (assuming the following information from Wikipedia is accurate):

Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications — zones M and Y have the same clock time but differ by 24 hours: a full day). These can be vocalized using the NATO phonetic alphabet which pronounces the letter Z as Zulu, leading to the use of the term "Zulu Time" for Greenwich Mean Time, or UT1 from January 1, 1972 onward.

How do I generate a stream from a string?

Modernized and slightly modified version of the extension methods for ToStream:

public static Stream ToStream(this string value) => ToStream(value, Encoding.UTF8);

public static Stream ToStream(this string value, Encoding encoding) 
                          => new MemoryStream(encoding.GetBytes(value ?? string.Empty));

Modification as suggested in @Palec's comment of @Shaun Bowe answer.

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)

How to copy file from one location to another location?

Use the New Java File classes in Java >=7.

Create the below method and import the necessary libs.

public static void copyFile( File from, File to ) throws IOException {
    Files.copy( from.toPath(), to.toPath() );

Use the created method as below within main:

File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);

try {
        copyFile(dirFrom, dirTo);
} catch (IOException ex) {
        Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);

NB:- fileFrom is the file that you want to copy to a new file fileTo in a different folder.

Credits - @Scott: Standard concise way to copy a file in Java?

Eclipse not recognizing JVM 1.8

Here are steps:

  • download 1.8 JDK from this site
  • install it
  • copy the jre folder & paste it in "C:\Program Files (x86)\EclipseNeon\"
  • rename the folder to "jre"
  • start the eclipse again

It should work.

Documentation for using JavaScript code inside a PDF file

Look for books by Ted Padova. Over the years, he has written a series of books called The Acrobat PDF {5,6,7,8,9...} Bible. They contain chapter(s) on JavaScript in PDF files. They are not as comprehensive as the reference documentation listed here, but in the books there are some realistic use-cases discussed in context.

There was also a talk on hacking PDF files by a computer scientist, given at a conference in 2010. The link on the talk's announcement-page to the slides is dead, but Google is your friend-. The talk is not exclusively on JavaScript, though. YouTube video - JavaScript starts at 06:00.

is it possible to add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

GROUP BY to combine/concat a column

A good question. Should tell you it took some time to crack this one. Here is my result.


VALUES  (1, 'Me', 'act1', 'ab'),
        (2, 'Me', 'act1', 'cd'),
        (3, 'You', 'act2', 'xy'),
        (4, 'You', 'act2', 'st')

        SELECT ',' + T2.PAGEURL  
        FROM @TABLE T2  
        WHERE T1.USERS = T2.USERS  
        FOR XML PATH ('')  

Moment js date time comparison

pass date to moment like this it will compare and give result. if you dont want format remove it

moment(Date1).format("YYYY-MM-DD") > moment(Date2).format("YYYY-MM-DD")

How to delete duplicate lines in a file without sorting it in Unix?

uniq would be fooled by trailing spaces and tabs. In order to emulate how a human makes comparison, I am trimming all trailing spaces and tabs before comparison.

I think that the $!N; needs curly braces or else it continues, and that is the cause of infinite loop.

I have bash 5.0 and sed 4.7 in Ubuntu 20.10. The second one-liner did not work, at the character set match.

Three variations, first to eliminate adjacent repeat lines, second to eliminate repeat lines wherever they occur, third to eliminate all but the last instance of lines in file.


# First line in a set of duplicate lines is kept, rest are deleted.
# Emulate human eyes on trailing spaces and tabs by trimming those.
# Use after norepeat() to dedupe blank lines.

dedupe() {
 sed -E '
   s/[ \t]+$//;

# Delete duplicate, nonconsecutive lines from a file. Ignore blank
# lines. Trailing spaces and tabs are trimmed to humanize comparisons
# squeeze blank lines to one

norepeat() {
 sed -n -E '
  s/[ \t]+$//;

lastrepeat() {
 sed -n -E '
  s/[ \t]+$//;
  # delete previous repeated line if found
  # after searching for previous repeat, move tested last line to end
  # squeeze blank lines to one

How to access SOAP services from iPhone

Have a look at gsoap that includes two iOS examples in the download package under ios_plugin. The tool converts WSDL to code for SOAP and XML REST.

How to change Apache Tomcat web server port number

Navigate to /tomcat-root/conf folder. Within you will find the server.xml file.

Open the server.xml in your preferred editor. Search the below similar statement (not exactly same as below will differ)

    <Connector port="8080" protocol="HTTP/1.1" 
           redirectPort="8443" />

Going to give the port number to 9090

     <Connector port="9090" protocol="HTTP/1.1" 
           redirectPort="8443" />

Save the file and restart the server. Now the tomcat will listen at port 9090

Set colspan dynamically with jquery

I've also found that if you had display:none, then programmatically changed it to be visible, you might also have to set


rather than display:inline or display:block otherwise the cell might only show as taking up 1 cell, no matter how large you have the colspan set to.

Loading context in Spring using web.xml

From the spring docs

Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.

The <context-param>:



You can then use the WebApplicationContext to get a handle on your beans.

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");

See for more info

Application Crashes With "Internal Error In The .NET Runtime"

I am not sure it may help everyone, but I could get around this by running

devenv.exe /ResetSettings the path {Visual_Studio_root}\Common7\Ide

I had the following errors in the event log and VS was just crashing and restarting all the time:

Faulting application name: devenv.exe, version: 14.0.25123.0, time stamp: 0x56f22f32
Faulting module name: clr.dll, version: 4.7.2115.0, time stamp: 0x59af88f2
Exception code: 0xc0000005
Fault offset: 0x0015f90e
Faulting process id: 0x3a7c
Faulting application start time: 0x01d353463eaf0c36
Faulting application path: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe
Faulting module path: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Report Id: a232f984-6e80-4f61-9003-e18a035c8f93
Faulting package full name: 
Faulting package-relative application ID: 

Which keycode for escape key with jQuery

Try with the keyup event:

$(document).keyup(function(e) {
  if (e.keyCode === 13) $('.save').click();     // enter
  if (e.keyCode === 27) $('.cancel').click();   // esc

force browsers to get latest js and css files in application

I use a similar way to do the same you are doing without modifying each page. Added a PreRender event is master file. It keeps my logic at one place and applicable to both js and css files.

protected void Page_PreRender(object sender, EventArgs e)
        HtmlLink link = null;
        LiteralControl script = null;

        foreach (Control c in Header.Controls)
            //StyleSheet add version
            if (c is HtmlLink)
                link = c as HtmlLink;

                if (link.Href.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase))
                    link.Href += string.Format("?v={0}", ConfigurationManager.AppSettings["agVersion"]);


            //Js add version
            if (c is LiteralControl)
                script = c as LiteralControl;

                if (script.Text.Contains(".js"))
                    var foundIndexes = new List<int>();

                    for (int i = script.Text.IndexOf(".js\""); i > -1; i = script.Text.IndexOf(".js\"", i + 1))


                    for (int i = foundIndexes.Count - 1; i >= 0; i--)

                        script.Text = script.Text.Insert(foundIndexes[i] + 3, string.Format("?v={0}", ConfigurationManager.AppSettings["agVersion"]));



How to restart VScode after editing extension's config?

Execute the workbench.action.reloadWindow command.

There are some ways to do so:

  1. Open the command palette (Ctrl + Shift + P) and execute the command:

    >Reload Window    
  2. Define a keybinding for the command (for example CTRL+F5) in keybindings.json:

        "key": "ctrl+f5",
        "command": "workbench.action.reloadWindow",
        "when": "editorTextFocus"

IEnumerable vs List - What to Use? How do they work?

I will share one misused concept that I fell into one day:

var names = new List<string> {"mercedes", "mazda", "bmw", "fiat", "ferrari"};

var startingWith_M = names.Where(x => x.StartsWith("m"));

var startingWith_F = names.Where(x => x.StartsWith("f"));

// updating existing list
names[0] = "ford";

// Guess what should be printed before continuing
print( startingWith_M.ToList() );
print( startingWith_F.ToList() );

Expected result

// I was expecting    
print( startingWith_M.ToList() ); // mercedes, mazda
print( startingWith_F.ToList() ); // fiat, ferrari

Actual result

// what printed actualy   
print( startingWith_M.ToList() ); // mazda
print( startingWith_F.ToList() ); // ford, fiat, ferrari


As per other answers, the evaluation of the result was deferred until calling ToList or similar invocation methods for example ToArray.

So I can rewrite the code in this case as:

var names = new List<string> {"mercedes", "mazda", "bmw", "fiat", "ferrari"};

// updating existing list
names[0] = "ford";

// before calling ToList directly
var startingWith_M = names.Where(x => x.StartsWith("m"));

var startingWith_F = names.Where(x => x.StartsWith("f"));

print( startingWith_M.ToList() );
print( startingWith_F.ToList() );

Play arround

OS X Terminal shortcut: Jump to beginning/end of line

in iterm2

fn + leftArraw or fn + rightArrow

this worked for me

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

That is because you are not fully qualifying your cells object. Try this

With Worksheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Notice the DOT before Cells?

Transaction marked as rollback only: How do I find the cause

Found a good explanation with solutions:

1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.


2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.

Working with TIFFs (import, export) in Python using numpy

PyLibTiff worked better for me than PIL, which as of December 2020 still doesn't support color images with more than 8 bits per color.

from libtiff import TIFF

tif ='filename.tif') # open tiff file in read mode
# read an image in the currect TIFF directory as a numpy array
image = tif.read_image()

# read all images in a TIFF file:
for image in tif.iter_images(): 

tif ='filename.tif', mode='w')

You can install PyLibTiff with

pip3 install numpy libtiff

The readme of PyLibTiff also mentions the tifffile library but I haven't tried it.

delete map[key] in go?

Copied from Go 1 release notes

In the old language, to delete the entry with key k from the map represented by m, one wrote the statement,

m[k] = value, false

This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.

In Go 1, that syntax has gone; instead there is a new built-in function, delete. The call

delete(m, k)

will delete the map entry retrieved by the expression m[k]. There is no return value. Deleting a non-existent entry is a no-op.

Updating: Running go fix will convert expressions of the form m[k] = value, false into delete(m, k) when it is clear that the ignored value can be safely discarded from the program and false refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.

How to enable scrolling of content inside a modal?

This is how I did it purely with CSS overriding some classes:

.modal {
  height: 60%;

  .modal-body {
    height: 80%;
    overflow-y: scroll;

Hope it helps you.

ArrayList filter

As you didn't give us very much information, I'm assuming the language you're writing the code in is C#. First of all: Prefer System.Collections.Generic.List over an ArrayList. Secondly: One way would be to loop through every item in the list and check whether it contains "How". Another way would be to use LINQ. Here's a quick example that filters out every item which doesn't contain "How":

var list = new List<string>();
list.AddRange(new string[] {
    "How are you?",
    "How you doing?",
    "Mike", });

foreach (string str in list.Where(s => s.Contains("How")))

How can I remove a key and its value from an associative array?

You may need two or more loops depending on your array:

$arr[$key1][$key2][$key3]=$value1; // ....etc

foreach ($arr as $key1 => $values) {
  foreach ($key1 as $key2 => $value) {

Spring MVC - How to get all request params in a map in Spring controller?

There are two interfaces

  1. org.springframework.web.context.request.WebRequest
  2. org.springframework.web.context.request.NativeWebRequest

Allows for generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API.


@RequestMapping(value = "/", method = GET)
public List<T> getAll(WebRequest webRequest){
    Map<String, String[]> params = webRequest.getParameterMap();

P.S. There are Docs about arguments which can be used as Controller params.

Angularjs error Unknown provider

bmleite has the correct answer about including the module.

If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.


angular.module('ModuleName', [])   // creates a module.

angular.module('ModuleName')       // gets you a pre-existing module.

So if you are extending a existing module, remember not to overwrite when trying to fetch it.

How do I protect javascript files?

I think the only way is to put required data on the server and allow only logged-in user to access the data as required (you can also make some calculations server side). This wont protect your javascript code but make it unoperatable without the server side code

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;

document.addEventListener('mousemove', function(e){

How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

Is it possible to do a sparse checkout without checking out the whole repository first?

In my case, I want to skip the Pods folder when cloning the project. I did step by step like below and it works for me. Hope it helps.

mkdir my_folder
cd my_folder
git init
git remote add origin -f <URL>
git config core.sparseCheckout true 
echo '!Pods/*\n/*' > .git/info/sparse-checkout
git pull origin master

Memo, If you want to skip more folders, just add more line in sparse-checkout file.

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.

Printing column separated by comma using Awk command line

Try this awk

awk -F, '{$0=$3}1' file
  • , Divide fields by ,
  • $0=$3 Set the line to only field 3
  • 1 Print all out. (explained here)

This could also be used:

awk -F, '{print $3}' file

Downcasting in Java

I believe this applies to all statically typed languages:

String s = "some string";
Object o = s; // ok
String x = o; // gives compile-time error, o is not neccessarily a string
String x = (String)o; // ok compile-time, but might give a runtime exception if o is not infact a String

The typecast effectively says: assume this is a reference to the cast class and use it as such. Now, lets say o is really an Integer, assuming this is a String makes no sense and will give unexpected results, thus there needs to be a runtime check and an exception to notify the runtime environment that something is wrong.

In practical use, you can write code working on a more general class, but cast it to a subclass if you know what subclass it is and need to treat it as such. A typical example is overriding Object.equals(). Assume we have a class for Car:

boolean equals(Object o) {
    if(!(o instanceof Car)) return false;
    Car other = (Car)o;
    // compare this to other and return

Google Maps API v3 marker with label

the above solutions wont work on ipad-2

recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about this blog and now my map search is working smoothly on ipad-2 :)

Git: How to commit a manually deleted file?

It says right there in the output of git status:

#   (use "git add/rm <file>..." to update what will be committed)

so just do:

git rm <filename>

Passing arguments to angularjs filters

From what I understand you can't pass an arguments to a filter function (when using the 'filter' filter). What you would have to do is to write a custom filter, sth like this:

.filter('weDontLike', function(){

return function(items, name){

    var arrayToReturn = [];        
    for (var i=0; i<items.length; i++){
        if (items[i].name != name) {

    return arrayToReturn;

Here is the working jsFiddle:

The other simple alternative, without writing custom filters is to store a name to filter out in a scope and then write:

$scope.weDontLike = function(item) {
  return != $;

How can I pass a list as a command-line argument with argparse?

If you have a nested list where the inner lists have different types and lengths and you would like to preserve the type, e.g.,

[[1, 2], ["foo", "bar"], [3.14, "baz", 20]]

then you can use the solution proposed by @sam-mason to this question, shown below:

from argparse import ArgumentParser
import json

parser = ArgumentParser()
parser.add_argument('-l', type=json.loads)
parser.parse_args(['-l', '[[1,2],["foo","bar"],[3.14,"baz",20]]'])

which gives:

Namespace(l=[[1, 2], ['foo', 'bar'], [3.14, 'baz', 20]])

Convert List(of object) to List(of string)

Not possible without iterating to build a new list. You can wrap the list in a container that implements IList.

You can use LINQ to get a lazy evaluated version of IEnumerable<string> from an object list like this:

var stringList = myList.OfType<string>();

How to make a radio button look like a toggle button


Example Image (you can run the code below):

Toggle Buttons (Radio and Checkbox) in Pure CSS and HTML

After looking for something really clean and straight forward, I ended up building this with ONE simple change from another code that was built only thinking on checkboxes, so I tryed the funcionality for RADIOS and it worked too(!).

The CSS (SCSS) is fully from @mallendeo (as established on the JS credits), what I did was simply change the type of the input to RADIO, and gave the same name to all the radio switches.... and VOILA!! They deactivate automatically one to the other!!

Very clean, and as you asked it's only CSS and HTML!!

It is exactly what I was looking for since 3 days after trying and editing more than a dozen of options (which mostly requiered jQuery, or didn't allow labels, or even wheren't really compatible with current browsers). This one's got it all!

I'm obligated to include the code in here to allow you to see a working example, so:

/** Toggle buttons_x000D_
 * @mallendeo_x000D_
 * forked @davidtaubmann_x000D_
 * from
html, body {_x000D_
  display: -webkit-box;_x000D_
  display: -webkit-flex;_x000D_
  display: -ms-flexbox;_x000D_
  display: flex;_x000D_
  min-height: 100%;_x000D_
  -webkit-box-pack: center;_x000D_
  -webkit-justify-content: center;_x000D_
      -ms-flex-pack: center;_x000D_
          justify-content: center;_x000D_
  -webkit-box-align: center;_x000D_
  -webkit-align-items: center;_x000D_
      -ms-flex-align: center;_x000D_
          align-items: center;_x000D_
  -webkit-box-orient: vertical;_x000D_
  -webkit-box-direction: normal;_x000D_
  -webkit-flex-direction: column;_x000D_
      -ms-flex-direction: column;_x000D_
          flex-direction: column;_x000D_
  font-family: sans-serif;_x000D_
ul, li {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
.tg-list {_x000D_
  text-align: center;_x000D_
  display: -webkit-box;_x000D_
  display: -webkit-flex;_x000D_
  display: -ms-flexbox;_x000D_
  display: flex;_x000D_
  -webkit-box-align: center;_x000D_
  -webkit-align-items: center;_x000D_
      -ms-flex-align: center;_x000D_
          align-items: center;_x000D_
.tg-list-item {_x000D_
  margin: 0 10px;;_x000D_
h2 {_x000D_
  color: #777;_x000D_
h4 {_x000D_
  color: #999;_x000D_
.tgl {_x000D_
  display: none;_x000D_
.tgl, .tgl:after, .tgl:before, .tgl *, .tgl *:after, .tgl *:before, .tgl + .tgl-btn {_x000D_
  box-sizing: border-box;_x000D_
.tgl::-moz-selection, .tgl:after::-moz-selection, .tgl:before::-moz-selection, .tgl *::-moz-selection, .tgl *:after::-moz-selection, .tgl *:before::-moz-selection, .tgl + .tgl-btn::-moz-selection {_x000D_
  background: none;_x000D_
.tgl::selection, .tgl:after::selection, .tgl:before::selection, .tgl *::selection, .tgl *:after::selection, .tgl *:before::selection, .tgl + .tgl-btn::selection {_x000D_
  background: none;_x000D_
.tgl + .tgl-btn {_x000D_
  outline: 0;_x000D_
  display: block;_x000D_
  width: 4em;_x000D_
  height: 2em;_x000D_
  position: relative;_x000D_
  cursor: pointer;_x000D_
  -webkit-user-select: none;_x000D_
     -moz-user-select: none;_x000D_
      -ms-user-select: none;_x000D_
          user-select: none;_x000D_
.tgl + .tgl-btn:after, .tgl + .tgl-btn:before {_x000D_
  position: relative;_x000D_
  display: block;_x000D_
  content: "";_x000D_
  width: 50%;_x000D_
  height: 100%;_x000D_
.tgl + .tgl-btn:after {_x000D_
  left: 0;_x000D_
.tgl + .tgl-btn:before {_x000D_
  display: none;_x000D_
.tgl:checked + .tgl-btn:after {_x000D_
  left: 50%;_x000D_
.tgl-light + .tgl-btn {_x000D_
  background: #f0f0f0;_x000D_
  border-radius: 2em;_x000D_
  padding: 2px;_x000D_
  -webkit-transition: all .4s ease;_x000D_
  transition: all .4s ease;_x000D_
.tgl-light + .tgl-btn:after {_x000D_
  border-radius: 50%;_x000D_
  background: #fff;_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
.tgl-light:checked + .tgl-btn {_x000D_
  background: #9FD6AE;_x000D_
.tgl-ios + .tgl-btn {_x000D_
  background: #fbfbfb;_x000D_
  border-radius: 2em;_x000D_
  padding: 2px;_x000D_
  -webkit-transition: all .4s ease;_x000D_
  transition: all .4s ease;_x000D_
  border: 1px solid #e8eae9;_x000D_
.tgl-ios + .tgl-btn:after {_x000D_
  border-radius: 2em;_x000D_
  background: #fbfbfb;_x000D_
  -webkit-transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;_x000D_
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;_x000D_
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 4px 0 rgba(0, 0, 0, 0.08);_x000D_
.tgl-ios + .tgl-btn:hover:after {_x000D_
  will-change: padding;_x000D_
.tgl-ios + .tgl-btn:active {_x000D_
  box-shadow: inset 0 0 0 2em #e8eae9;_x000D_
.tgl-ios + .tgl-btn:active:after {_x000D_
  padding-right: .8em;_x000D_
.tgl-ios:checked + .tgl-btn {_x000D_
  background: #86d993;_x000D_
.tgl-ios:checked + .tgl-btn:active {_x000D_
  box-shadow: none;_x000D_
.tgl-ios:checked + .tgl-btn:active:after {_x000D_
  margin-left: -.8em;_x000D_
.tgl-skewed + .tgl-btn {_x000D_
  overflow: hidden;_x000D_
  -webkit-transform: skew(-10deg);_x000D_
          transform: skew(-10deg);_x000D_
  -webkit-backface-visibility: hidden;_x000D_
          backface-visibility: hidden;_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
  font-family: sans-serif;_x000D_
  background: #888;_x000D_
.tgl-skewed + .tgl-btn:after, .tgl-skewed + .tgl-btn:before {_x000D_
  -webkit-transform: skew(10deg);_x000D_
          transform: skew(10deg);_x000D_
  display: inline-block;_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  line-height: 2em;_x000D_
  font-weight: bold;_x000D_
  color: #fff;_x000D_
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);_x000D_
.tgl-skewed + .tgl-btn:after {_x000D_
  left: 100%;_x000D_
  content: attr(data-tg-on);_x000D_
.tgl-skewed + .tgl-btn:before {_x000D_
  left: 0;_x000D_
  content: attr(data-tg-off);_x000D_
.tgl-skewed + .tgl-btn:active {_x000D_
  background: #888;_x000D_
.tgl-skewed + .tgl-btn:active:before {_x000D_
  left: -10%;_x000D_
.tgl-skewed:checked + .tgl-btn {_x000D_
  background: #86d993;_x000D_
.tgl-skewed:checked + .tgl-btn:before {_x000D_
  left: -100%;_x000D_
.tgl-skewed:checked + .tgl-btn:after {_x000D_
  left: 0;_x000D_
.tgl-skewed:checked + .tgl-btn:active:after {_x000D_
  left: 10%;_x000D_
.tgl-flat + .tgl-btn {_x000D_
  padding: 2px;_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
  background: #fff;_x000D_
  border: 4px solid #f2f2f2;_x000D_
  border-radius: 2em;_x000D_
.tgl-flat + .tgl-btn:after {_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
  background: #f2f2f2;_x000D_
  content: "";_x000D_
  border-radius: 1em;_x000D_
.tgl-flat:checked + .tgl-btn {_x000D_
  border: 4px solid #7FC6A6;_x000D_
.tgl-flat:checked + .tgl-btn:after {_x000D_
  left: 50%;_x000D_
  background: #7FC6A6;_x000D_
.tgl-flip + .tgl-btn {_x000D_
  padding: 2px;_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
  font-family: sans-serif;_x000D_
  -webkit-perspective: 100px;_x000D_
          perspective: 100px;_x000D_
.tgl-flip + .tgl-btn:after, .tgl-flip + .tgl-btn:before {_x000D_
  display: inline-block;_x000D_
  -webkit-transition: all .4s ease;_x000D_
  transition: all .4s ease;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  line-height: 2em;_x000D_
  font-weight: bold;_x000D_
  color: #fff;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  -webkit-backface-visibility: hidden;_x000D_
          backface-visibility: hidden;_x000D_
  border-radius: 4px;_x000D_
.tgl-flip + .tgl-btn:after {_x000D_
  content: attr(data-tg-on);_x000D_
  background: #02C66F;_x000D_
  -webkit-transform: rotateY(-180deg);_x000D_
          transform: rotateY(-180deg);_x000D_
.tgl-flip + .tgl-btn:before {_x000D_
  background: #FF3A19;_x000D_
  content: attr(data-tg-off);_x000D_
.tgl-flip + .tgl-btn:active:before {_x000D_
  -webkit-transform: rotateY(-20deg);_x000D_
          transform: rotateY(-20deg);_x000D_
.tgl-flip:checked + .tgl-btn:before {_x000D_
  -webkit-transform: rotateY(180deg);_x000D_
          transform: rotateY(180deg);_x000D_
.tgl-flip:checked + .tgl-btn:after {_x000D_
  -webkit-transform: rotateY(0);_x000D_
          transform: rotateY(0);_x000D_
  left: 0;_x000D_
  background: #7FC6A6;_x000D_
.tgl-flip:checked + .tgl-btn:active:after {_x000D_
  -webkit-transform: rotateY(20deg);_x000D_
          transform: rotateY(20deg);_x000D_
<h2>Toggle 'em</h2>_x000D_
<ul class='tg-list'>_x000D_
  <li class='tg-list-item'>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='rd1'>_x000D_
    <input class='tgl tgl-light' id='rd1' name='group' type='radio'>_x000D_
    <label class='tgl-btn' for='rd1'></label>_x000D_
    <label class='tgl-btn' for='rd1'>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='rd2'>_x000D_
      <h4>iOS 7 (Disabled)</h4>_x000D_
    <input checked class='tgl tgl-ios' disabled id='rd2' name='group' type='radio'>_x000D_
    <label class='tgl-btn' for='rd2'></label>_x000D_
    <label class='tgl-btn' for='rd2'>_x000D_
      <h4>iOS 7 (Disabled)</h4>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='rd3'>_x000D_
    <input class='tgl tgl-skewed' id='rd3' name='group' type='radio'>_x000D_
    <label class='tgl-btn' data-tg-off='OFF' data-tg-on='ON' for='rd3'></label>_x000D_
    <label class='tgl-btn' for='rd3'>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='rd4'>_x000D_
    <input class='tgl tgl-flat' id='rd4' name='group' type='radio'>_x000D_
    <label class='tgl-btn' for='rd4'></label>_x000D_
    <label class='tgl-btn' for='rd4'>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='rd5'>_x000D_
    <input class='tgl tgl-flip' id='rd5' name='group' type='radio'>_x000D_
    <label class='tgl-btn' data-tg-off='Nope' data-tg-on='Yeah!' for='rd5'></label>_x000D_
    <label class='tgl-btn' for='rd5'>_x000D_
<ul class='tg-list'>_x000D_
  <li class='tg-list-item'>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='cb1'>_x000D_
    <input class='tgl tgl-light' id='cb1' type='checkbox'>_x000D_
    <label class='tgl-btn' for='cb1'></label>_x000D_
    <label class='tgl-btn' for='cb1'>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='cb2'>_x000D_
      <h4>iOS 7</h4>_x000D_
    <input class='tgl tgl-ios' id='cb2' type='checkbox'>_x000D_
    <label class='tgl-btn' for='cb2'></label>_x000D_
    <label class='tgl-btn' for='cb2'>_x000D_
      <h4>iOS 7</h4>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='cb3'>_x000D_
    <input class='tgl tgl-skewed' id='cb3' type='checkbox'>_x000D_
    <label class='tgl-btn' data-tg-off='OFF' data-tg-on='ON' for='cb3'></label>_x000D_
    <label class='tgl-btn' for='cb3'>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='cb4'>_x000D_
    <input class='tgl tgl-flat' id='cb4' type='checkbox'>_x000D_
    <label class='tgl-btn' for='cb4'></label>_x000D_
    <label class='tgl-btn' for='cb4'>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='cb5'>_x000D_
    <input class='tgl tgl-flip' id='cb5' type='checkbox'>_x000D_
    <label class='tgl-btn' data-tg-off='Nope' data-tg-on='Yeah!' for='cb5'></label>_x000D_
    <label class='tgl-btn' for='cb5'>_x000D_

If you run the snippet, you'll see I leave the iOS radio checked and disabled, so you can watch how it is also affected when activating another one. I also included 2 labels for each radio, one before and one after. The copy of the original code to show the working checkboxes in the same window is also included.

java Arrays.sort 2d array

Java 8 is now very common nowadays.

Arrays.sort(myArr,(double[] a,double[] b)->{
                //here multiple lines of code can be placed
                return a[0]-b[0]; 

How to display a gif fullscreen for a webpage background?

if it's background, use background-size: cover;

    background-image: url('');_x000D_
    background-size: cover;_x000D_
    height: 100vh;_x000D_

How to export SQL Server database to MySQL?

You can use MySQL Workbench which provides a way to quickly migrate data and applications from Microsoft SQL Server to MySQL employing less time and effort.

This tool has a lot of cool features like:

  • Database migrations - enables migrations from Microsoft SQL Server, Sybase ASE and PostgreSQL.
  • Migration project management - allows migrations to be configured, copied, edited, executed and scheduled.

Read more

How to Allow Remote Access to PostgreSQL database

If using PostgreSql 9.5.1, please follow the below configuration:

  1. Open hg_hba.conf in pgAdmin pgAdmin
  2. Select your path, and open it, then add a setting pg_hba.conf
  3. Restart postgresql service

Access iframe elements in JavaScript

If your iframe is in the same domain as your parent page you can access the elements using document.frames collection.

// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on document.frames['myIFrame'].document like you are working on
// normal document object in JS

If your iframe is not in the same domain the browser should prevent such access for security reasons.

How to get the ASCII value in JavaScript for the characters

Here is the example:

var charCode = "a".charCodeAt(0);_x000D_

Or if you have longer strings:

var string = "Some string";_x000D_
for (var i = 0; i < string.length; i++) {_x000D_

String.charCodeAt(x) method will return ASCII character code at a given position.

Get element inside element by class and ID - JavaScript

You can do it like this:

var list = document.getElementById("foo").getElementsByClassName("bar");
if (list && list.length > 0) {
    list[0].innerHTML = "Goodbye world!";

or, if you want to do it with with less error checking and more brevity, it can be done in one line like this:

document.getElementById("foo").getElementsByClassName("bar")[0].innerHTML = "Goodbye world!";

In explanation:

  1. You get the element with id="foo".
  2. You then find the objects that are contained within that object that have class="bar".
  3. That returns an array-like nodeList, so you reference the first item in that nodeList
  4. You can then set the innerHTML of that item to change its contents.

Caveats: some older browsers don't support getElementsByClassName (e.g. older versions of IE). That function can be shimmed into place if missing.

This is where I recommend using a library that has built-in CSS3 selector support rather than worrying about browser compatibility yourself (let someone else do all the work). If you want just a library to do that, then Sizzle will work great. In Sizzle, this would be be done like this:

Sizzle("#foo .bar")[0].innerHTML = "Goodbye world!";

jQuery has the Sizzle library built-in and in jQuery, this would be:

$("#foo .bar").html("Goodbye world!");

Checking something isEmpty in Javascript?

const isEmpty = val => val == null || !(Object.keys(val) || val).length;

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

When publishing to IIS, by Web Deploy, I just checked the File Publish Options and executed. Now it works! After this deploy the checkboxes do not need to be checked. I don't think this can be a solutions for everybody, but it is the only thing I needed to do to solve my problem. Good luck.

Finding the second highest number in array

Use following function

public static int secHigh(int arr[]){
            int firstHigh = 0,secHigh = 0;
            for(int x: arr){
                if(x > firstHigh){
                    secHigh = firstHigh;
                    firstHigh = x;
                }else if(x > secHigh){
                    secHigh = x;
            return secHigh;

Function Call

int secondHigh = secHigh(arr);

Failed to locate the winutils binary in the hadoop binary path

Set up HADOOP_HOME variable in windows to resolve the problem.

You can find answer in org/apache/hadoop/hadoop-common/2.2.0/hadoop-common-2.2.0-sources.jar!/org/apache/hadoop/util/ :

IOException from

  public static final String getQualifiedBinPath(String executable) 
  throws IOException {
    // construct hadoop bin path to the specified executable
    String fullExeName = HADOOP_HOME_DIR + File.separator + "bin" 
      + File.separator + executable;
    File exeFile = new File(fullExeName);
    if (!exeFile.exists()) {
      throw new IOException("Could not locate executable " + fullExeName
        + " in the Hadoop binaries.");
    return exeFile.getCanonicalPath();


// first check the Dflag hadoop.home.dir with JVM scope
String home = System.getProperty("hadoop.home.dir");
// fall back to the system/user-global env variable
if (home == null) {
  home = System.getenv("HADOOP_HOME");

plotting different colors in matplotlib

Joe Kington's excellent answer is already 4 years old, Matplotlib has incrementally changed (in particular, the introduction of the cycler module) and the new major release, Matplotlib 2.0.x, has introduced stylistic differences that are important from the point of view of the colors used by default.

The color of individual lines

The color of individual lines (as well as the color of different plot elements, e.g., markers in scatter plots) is controlled by the color keyword argument,

plt.plot(x, y, color=my_color)

my_color is either

The color cycle

By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).

The color cycle is a property of the axes object, and in older releases was simply a sequence of valid color names (by default a string of one character color names, "bgrcmyk") and you could set it as in


(as noted in a comment this API has been deprecated, more on this later).

In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"], the Vega category10 palette.

enter image description here

(the image is a screenshot from

The cycler module: composable cycles

The following code shows that the color cycle notion has been deprecated

In [1]: from matplotlib import rc_params

In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/ UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

Now the relevant property is the 'axes.prop_cycle'

In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

Previously, the color_cycle was a generic sequence of valid color denominations, now by default it is a cycler object containing a label ('color') and a sequence of valid color denominations. The step forward with respect to the previous interface is that it is possible to cycle not only on the color of lines but also on other line attributes, e.g.,

In [5]: from cycler import cycler

In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])

In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}

As you have seen, the cycler objects are composable and when you iterate on a composed cycler what you get, at each iteration, is a dictionary of keyword arguments for plt.plot.

You can use the new defaults on a per axes object ratio,


or you can install temporarily the new default

plt.rc('axes', prop_cycle=new_prop_cycle)

or change altogether the default editing your .matplotlibrc file.

Last possibility, use a context manager

with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):

to have the new cycler used in a group of different plots, reverting to defaults at the end of the context.

The doc string of the cycler() function is useful, but the (not so much) gory details about the cycler module and the cycler() function, as well as examples, can be found in the fine docs.

Angularjs simple file download causes router to redirect$location#html-link-rewriting

In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.

  • Links that contain target element Example:
    <a href="/ext/link?a=b" target="_self">link</a>

  • Absolute links that go to a different domain Example:
    <a href="">link</a>

  • Links starting with '/' that lead to a different base path when base is defined Example:
    <a href="/not-my-base/link">link</a>

So in your case, you should add a target attribute like so...

<a target="_self" href="" download="foo.pdf">

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

As far as I remember, in the current JDBC, Resultsets and statements implement the AutoCloseable interface. That means they are closed automatically upon being destroyed or going out of scope.

How to iterate through range of Dates in Java?

private static void iterateBetweenDates(Date startDate, Date endDate) {
    Calendar startCalender = Calendar.getInstance();
    Calendar endCalendar = Calendar.getInstance();

    for(; startCalender.compareTo(endCalendar)<=0;
          startCalender.add(Calendar.DATE, 1)) {
        // write your main logic here


Want to make Font Awesome icons clickable

Please use Like below.
<a style="cursor: pointer" **(click)="yourFunctionComponent()"** >
<i class="fa fa-dribbble fa-4x"></i>

The above can be used so that the fa icon will be shown and also on the click function you could write your logic.

Dynamically Add Images React Webpack

So you have to add an import statement on your parent component:

class ParentClass extends Component {
  render() {
    const img = require('../images/img.png');
    return (

and in the child class:

class ChildClass extends Component {
  render() {
    return (

Add zero-padding to a string

"1".PadLeft(4, '0');

Change value in a cell based on value in another cell


CSS selector for disabled input type="submit"

I used @jensgram solution to hide a div that contains a disabled input. So I hide the entire parent of the input.

Here is the code :

div:has(>input[disabled=disabled]) {
    display: none;

Maybe it could help some of you.

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

You can convert a string to a date easily by:


How do I delete all the duplicate records in a MySQL table without temp tables

This doesn't use TEMP Tables, but real tables instead. If the problem is just about temp tables and not about table creation or dropping tables, this will work:



RENAME TABLE TableA_Verify TO TableA;

Android - Handle "Enter" in an EditText

InputType on the textfield must be text in order for what CommonsWare said to work. Just tried all of this, no inputType before the trial and nothing worked, Enter kept registering as soft enter. After inputType = text, everything including the setImeLabel worked.

Example : android:inputType="text"

Cannot uninstall angular-cli

I have also faced the same issue in recent past for me I have do the following commands one by one in terminal.

sudo npm uninstall -g angular-cli
sudo npm cache clean

After this run

ng -v

If still get angular-cli version 1.0.0-beta.2x.x then run the following command

which ng

It will show the ng path. Go to the path and if it is linked with any file remove the same the link and actual ng file. In my case the link is in /usr/bin/ng and actual path of ng file is /lib/node_modules/@angular/cli/bin/ng.

sudo rm -rf /lib/node_modules/@angular/cli/bin/ng
sudo rm -rf /usr/bin/ng

Next you need to install @angular/cli using

sudo npm install -g @angular/cli

Close all the terminal and run ng -v and you are on. May be it will help someone. Thanks :)

Convert char * to LPWSTR

This version, using the Windows API function MultiByteToWideChar(), handles the memory allocation for arbitrarily long input strings.

int lenA = lstrlenA(input);
int lenW = ::MultiByteToWideChar(CP_ACP, 0, input, lenA, NULL, 0);
if (lenW>0)
    output = new wchar_t[lenW];
    ::MultiByteToWideChar(CP_ACP, 0, input, lenA, output, lenW);

git: Switch branch and ignore any changes without committing

None of these answers helped me because I still had untracked files even after reset and stash. I had to do:

git reset --hard HEAD
git clean -d -f

How to replace multiple strings in a file using PowerShell

With version 3 of PowerShell you can chain the replace calls together:

 (Get-Content $sourceFile) | ForEach-Object {
    $_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
 } | Set-Content $destinationFile

Why is the parent div height zero when it has floated children

Ordinarily, floats aren't counted in the layout of their parents.

To prevent that, add overflow: hidden to the parent.

CentOS 64 bit bad ELF interpreter

In general, when you get an error like this, just do

yum provides

then you'll see something like:

glibc-2.20-5.fc21.i686 : The GNU libc libraries
Repo        : fedora
Matched from:
Provides    :

and then you just run the following like BRPocock wrote (in case you were wondering what the logic was...):

yum install glibc.i686

Duplicate / Copy records in the same MySQL table

Slight variation, main difference being to set the primary key field ("varname") to null, which produces a warning but works. By setting the primary key to null, the auto-increment works when inserting the record in the last statement.

This code also cleans up previous attempts, and can be run more than once without problems:

DELETE FROM `tbl` WHERE varname="primary key value for new record";
CREATE TEMPORARY TABLE tmp SELECT * FROM `tbl` WHERE varname="primary key value for old record";
UPDATE tmp SET varname=NULL;

Stash just a single file

You can interactively stash single lines with git stash -p (analogous to git add -p).

It doesn't take a filename, but you could just skip other files with d until you reached the file you want stashed and the stash all changes in there with a.

How to set ssh timeout?

Use the -o ConnectTimeout and -o BatchMode=yes -o StrictHostKeyChecking=no .

ConnectTimeout keeps the script from hanging, BatchMode keeps it from hanging with Host unknown, YES to add to known_hosts, and StrictHostKeyChecking adds the fingerprint automatically.

**** NOTE **** The "StrictHostKeyChecking" was only intended for internal networks where you trust you hosts. Depending on the version of the SSH client, the "Are you sure you want to add your fingerprint" can cause the client to hang indefinitely (mainly old versions running on AIX). Most modern versions do not suffer from this issue. If you have to deal with fingerprints with multiple hosts, I recommend maintaining the known_hosts file with some sort of configuration management tool like puppet/ansible/chef/salt/etc.

How to set the action for a UIBarButtonItem in Swift

Swift 4/5 example = self
button.action = #selector(buttonClicked(sender:))

@objc func buttonClicked(sender: UIBarButtonItem) {

Removing element from array in component state

You could use the update() immutability helper from react-addons-update, which effectively does the same thing under the hood, but what you're doing is fine.

this.setState(prevState => ({
  data: update(, {$splice: [[index, 1]]})

Converting string to Date and DateTime

$d = new DateTime('10-16-2003');

$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16

Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.

jQuery get an element by its data-id


Rerouting stdin and stdout from C

Why use freopen()? The C89 specification has the answer in one of the endnotes for the section on <stdio.h>:

116. The primary use of the freopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout), as those identifiers need not be modifiable lvalues to which the value returned by the fopen function may be assigned.

freopen is commonly misused, e.g. stdin = freopen("newin", "r", stdin);. This is no more portable than fclose(stdin); stdin = fopen("newin", "r");. Both expressions attempt to assign to stdin, which is not guaranteed to be assignable.

The right way to use freopen is to omit the assignment: freopen("newin", "r", stdin);

How generate unique Integers based on GUIDs

Here is the simplest way:

Guid guid = Guid.NewGuid();
Random random = new Random();
int i = random.Next();

You'll notice that guid is not actually used here, mainly because there would be no point in using it. Microsoft's GUID algorithm does not use the computer's MAC address any more - GUID's are actually generated using a pseudo-random generator (based on time values), so if you want a random integer it makes more sense to use the Random class for this.

Update: actually, using a GUID to generate an int would probably be worse than just using Random ("worse" in the sense that this would be more likely to generate collisions). This is because not all 128 bits in a GUID are random. Ideally, you would want to exclude the non-varying bits from a hashing function, although it would be a lot easier to just generate a random number, as I think I mentioned before. :)

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

Since I don't have a 50 reputation Stackoverflow wont let me comment on the second best answer. Found another trick for finding the culprit label in the Storyboard.

So once you know the id of the label, open your storyboard in a seperate tab with view controllers displayed and just do command F and command V and will take you straight to that label :)

Generating a drop down list of timezones with PHP

See this example also

     function get_timezones() 
        $o = array();
        $t_zones = timezone_identifiers_list();
        foreach($t_zones as $a)
            $t = '';

                //this throws exception for 'US/Pacific-New'
                $zone = new DateTimeZone($a);

                $seconds = $zone->getOffset( new DateTime("now" , $zone) );
                $hours = sprintf( "%+02d" , intval($seconds/3600));
                $minutes = sprintf( "%02d" , ($seconds%3600)/60 );

                $t = $a ."  [ $hours:$minutes ]" ;

                $o[$a] = $t;

            //exceptions must be catched, else a blank page
            catch(Exception $e)
                //die("Exception : " . $e->getMessage() . '<br />');
                //what to do in catch ? , nothing just relax


        return $o;

    $o = get_timezones();

    <select name="time_zone">
        foreach($o as $tz => $label)
            echo "<option value="$tz">$label</option>";

SQL Server - NOT IN

Use a LEFT JOIN checking the right side for nulls.

FROM TableA a
LEFT JOIN TableB on a.Id = b.Id

The above would match up TableA and TableB based on the Id column in each, and then give you the rows where the B side is empty.

Custom checkbox image android

Checkboxes being children of Button you can just give your checkbox a background image with several states as described here, under "Button style":

...and exemplified here:

Uninstall Eclipse under OSX?

No need to uninstall anything, you can just delete the eclipse/ folder, but you should also use a fresh workspace or delete the workspace/.metadata folder.

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

I used inbuilt function dropDuplicates(). Scala code given below

val data = sc.parallelize(List(("Foo",41,"US",3),


Output :

|  x|  y|  z|count|
|Baz| 22| US|    6|
|Foo| 39| UK|    1|
|Foo| 41| US|    3|
|Bar| 57| CA|    2|

how to create a Java Date object of midnight today and midnight tomorrow?

Remember, Date is not used to represent dates (!). To represent date you need a calendar. This:

Calendar c = new GregorianCalendar();

will create a Calendar instance representing present date in your current time zone. Now what you need is to truncate every field below day (hour, minute, second and millisecond) by setting it to 0. You now have a midnight today.

Now to get midnight next day, you need to add one day:

c.add(Calendar.DAY_OF_MONTH, 1);

Note that adding 86400 seconds or 24 hours is incorrect due to summer time that might occur in the meantime.

UPDATE: However my favourite way to deal with this problem is to use DateUtils class from Commons Lang:

Date start = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH))
Date end = DateUtils.addDays(start, 1);

It uses Calendar behind the scenes...

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> import pickle
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]

Modelling an elevator using Object-Oriented Analysis and Design

I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.

A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:

  1. Representation of the central controller (assuming there is one).

  2. Representations of elevators

  3. Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.

  4. Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).

  5. Representation of a human and cargo (may be important for factoring in maximal loads)

  6. Representation of the building (in some cases, as certain floors may be blocked at times, etc.)